libmicrohttpd-1.0.2/0000755000175000017500000000000015035216653011365 500000000000000libmicrohttpd-1.0.2/src/0000755000175000017500000000000015035216652012153 500000000000000libmicrohttpd-1.0.2/src/tools/0000755000175000017500000000000015035216653013314 500000000000000libmicrohttpd-1.0.2/src/tools/perf_replies.c0000644000175000017500000017074515035214304016064 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice unmodified, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file tools/perf_replies.c * @brief Implementation of HTTP server optimised for fast replies * based on MHD. * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include "microhttpd.h" #include "mhd_tool_str_to_uint.h" #include "mhd_tool_get_cpu_count.h" #if defined(MHD_REAL_CPU_COUNT) #if MHD_REAL_CPU_COUNT == 0 #undef MHD_REAL_CPU_COUNT #endif /* MHD_REAL_CPU_COUNT == 0 */ #endif /* MHD_REAL_CPU_COUNT */ #define PERF_RPL_ERR_CODE_BAD_PARAM 65 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /* Static constants */ static const char *const tool_copyright = "Copyright (C) 2023 Evgeny Grin (Karlson2k)"; /* Package or build specific string, like "Debian 1.2.3-4" or "RevX, built by MSYS2" */ static const char *const build_revision = "" #ifdef MHD_BUILD_REV_STR MHD_BUILD_REV_STR #endif /* MHD_BUILD_REV_STR */ ; #define PERF_REPL_PORT_FALLBACK 48080 /* Dynamic variables */ static char self_name[500] = "perf_replies"; static uint16_t mhd_port = 0; static void set_self_name (int argc, char *const *argv) { if ((argc >= 1) && (NULL != argv[0])) { const char *last_dir_sep; last_dir_sep = strrchr (argv[0], '/'); #ifdef _WIN32 if (1) { const char *last_w32_dir_sep; last_w32_dir_sep = strrchr (argv[0], '\\'); if ((NULL == last_dir_sep) || ((NULL != last_w32_dir_sep) && (last_w32_dir_sep > last_dir_sep))) last_dir_sep = last_w32_dir_sep; } #endif /* _WIN32 */ if (NULL != last_dir_sep) { size_t name_len; name_len = strlen (last_dir_sep + 1); if ((0 != name_len) && ((sizeof(self_name) / sizeof(char)) > name_len)) { strcpy (self_name, last_dir_sep + 1); return; } } } /* Set default name */ strcpy (self_name, "perf_replies"); return; } static unsigned int detect_cpu_core_count (void) { int sys_cpu_count; sys_cpu_count = mhd_tool_get_system_cpu_count (); if (0 >= sys_cpu_count) { int proc_cpu_count; fprintf (stderr, "Failed to detect the number of logical CPU cores " "available on the system.\n"); proc_cpu_count = mhd_tool_get_proc_cpu_count (); if (0 < proc_cpu_count) { fprintf (stderr, "The number of CPU cores available for this process " "is used as a fallback.\n"); sys_cpu_count = proc_cpu_count; } #ifdef MHD_REAL_CPU_COUNT if (0 >= sys_cpu_count) { fprintf (stderr, "configure-detected hardcoded number is used " "as a fallback.\n"); sys_cpu_count = MHD_REAL_CPU_COUNT; } #endif if (0 >= sys_cpu_count) sys_cpu_count = 1; printf ("Assuming %d logical CPU core%s on this system.\n", sys_cpu_count, (1 == sys_cpu_count) ? "" : "s"); } else { printf ("Detected %d logical CPU core%s on this system.\n", sys_cpu_count, (1 == sys_cpu_count) ? "" : "s"); } return (unsigned int) sys_cpu_count; } static unsigned int get_cpu_core_count (void) { static unsigned int num_cpu_cores = 0; if (0 == num_cpu_cores) num_cpu_cores = detect_cpu_core_count (); return num_cpu_cores; } static unsigned int detect_process_cpu_core_count (void) { unsigned int num_proc_cpu_cores; unsigned int sys_cpu_cores; int res; sys_cpu_cores = get_cpu_core_count (); res = mhd_tool_get_proc_cpu_count (); if (0 > res) { fprintf (stderr, "Cannot detect the number of logical CPU cores available " "for this process.\n"); if (1 != sys_cpu_cores) printf ("Assuming all %u system logical CPU cores are available to run " "threads of this process.\n", sys_cpu_cores); else printf ("Assuming single logical CPU core available for this process.\n"); num_proc_cpu_cores = sys_cpu_cores; } else { printf ("Detected %d logical CPU core%s available to run threads " "of this process.\n", res, (1 == res) ? "" : "s"); num_proc_cpu_cores = (unsigned int) res; } if (num_proc_cpu_cores > sys_cpu_cores) { fprintf (stderr, "WARNING: Detected number of CPU cores available " "for this process (%u) is larger than detected number " "of CPU cores on the system (%u).\n", num_proc_cpu_cores, sys_cpu_cores); num_proc_cpu_cores = sys_cpu_cores; fprintf (stderr, "Using %u as the number of logical CPU cores available " "for this process.\n", num_proc_cpu_cores); } return num_proc_cpu_cores; } static unsigned int get_process_cpu_core_count (void) { static unsigned int proc_num_cpu_cores = 0; if (0 == proc_num_cpu_cores) proc_num_cpu_cores = detect_process_cpu_core_count (); return proc_num_cpu_cores; } static unsigned int num_threads = 0; static unsigned int get_num_threads (void) { #if 0 /* disabled code */ static const unsigned int max_threads = 32; #endif /* disabled code */ if (0 < num_threads) return num_threads; num_threads = get_cpu_core_count () / 2; if (0 == num_threads) num_threads = 1; else { unsigned int num_proc_cpus; num_proc_cpus = get_process_cpu_core_count (); if (num_proc_cpus >= num_threads) { printf ("Using half of all available CPU cores, assuming the other half " "is used by client / requests generator.\n"); } else { printf ("Using all CPU cores available for this process as more than " "half of CPU cores on this system are still available for use " "by client / requests generator.\n"); num_threads = num_proc_cpus; } } #if 0 /* disabled code */ if (max_threads < num_threads) { printf ("Number of threads is limited to %u as more threads " "are unlikely to improve performance.\n", max_threads); num_threads = max_threads; } #endif /* disabled code */ return num_threads; } /** * The result of short parameters processing */ enum PerfRepl_param_result { PERF_RPL_PARAM_ERROR, /**< Error processing parameter */ PERF_RPL_PARAM_ONE_CHAR, /**< Processed exactly one character */ PERF_RPL_PARAM_FULL_STR, /**< Processed current parameter completely */ PERF_RPL_PARAM_STR_PLUS_NEXT /**< Current parameter completely and next parameter processed */ }; /** * Extract parameter value * @param param_name the name of the parameter * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @param[out] param_value the pointer where to store resulting value * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result get_param_value (const char *param_name, const char *param_tail, const char *next_param, unsigned int *param_value) { const char *value_str; size_t digits; if (0 != param_tail[0]) { if ('=' != param_tail[0]) value_str = param_tail; else value_str = param_tail + 1; } else value_str = next_param; if (NULL != value_str) digits = mhd_tool_str_to_uint (value_str, param_value); else digits = 0; if ((0 == digits) || (0 != value_str[digits])) { fprintf (stderr, "Parameter '%s' is not followed by valid number.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (0 != param_tail[0]) return PERF_RPL_PARAM_FULL_STR; return PERF_RPL_PARAM_STR_PLUS_NEXT; } static void show_help (void) { printf ("Usage: %s [OPTIONS] [PORT_NUMBER]\n", self_name); printf ("Start MHD-based web-server optimised for fast replies.\n"); printf ("\n"); printf ("Threading options (mutually exclusive):\n"); printf (" -A, --all-cpus use all available CPU cores (for \n" " testing with remote client)\n"); printf (" -t NUM, --threads=NUM use NUM threads\n"); printf (" -P, --thread-per-conn use thread-per-connection mode,\n" " the number of threads is limited only\n" " by the number of connection\n"); printf ("\n"); printf ("Force polling function (mutually exclusive):\n"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_EPOLL)) printf (" -e, --epoll use 'epoll' functionality\n"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_POLL)) printf (" -p, --poll use poll() function\n"); printf (" -s, --select use select() function\n"); printf ("\n"); printf ("Response body size options (mutually exclusive):\n"); printf (" -E, --empty empty response, 0 bytes\n"); printf (" -T, --tiny tiny response, 3 bytes (default)\n"); printf (" -M, --medium medium response, 8 KiB\n"); printf (" -L, --large large response, 1 MiB\n"); printf (" -X, --xlarge extra large response, 8 MiB\n"); printf (" -J, --jumbo jumbo response, 101 MiB\n"); printf ("\n"); printf ("Response use options (mutually exclusive):\n"); printf (" -S, --shared pool of pre-generated shared response\n" " objects (default)\n"); printf (" -I, --single single pre-generated response object\n" " used for all requests\n"); printf (" -U, --unique response object generated for every\n" " request and used one time only\n"); printf ("\n"); printf ("Other options:\n"); printf (" -c NUM, --connections=NUM reject more than NUM client \n" " connections\n"); printf (" -O NUM, --timeout=NUM set connection timeout to NUM seconds,\n" " zero means no timeout\n"); printf (" --date-header use the 'Date:' header in every\n" " reply\n"); printf (" --help display this help and exit\n"); printf (" -V, --version output version information and exit\n"); printf ("\n"); printf ("This tool is part of GNU libmicrohttpd suite.\n"); printf ("%s\n", tool_copyright); } struct PerfRepl_parameters { unsigned int port; int all_cpus; unsigned int threads; int thread_per_conn; int epoll; int poll; int select; int empty; int tiny; int medium; int large; int xlarge; int jumbo; int shared; int single; int unique; unsigned int connections; unsigned int timeout; int date_header; int help; int version; }; static struct PerfRepl_parameters tool_params = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static enum PerfRepl_param_result process_param__all_cpus (const char *param_name) { if (0 != tool_params.threads) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-t' or '--threads'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.thread_per_conn) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-P' or '--thread-per-conn'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.all_cpus = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process parameter '-t' or '--threads' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__threads (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; if (tool_params.all_cpus) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-A' or '--all-cpus'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.thread_per_conn) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-P' or '--thread-per-conn'.\n", param_name); return PERF_RPL_PARAM_ERROR; } value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; if (0 == param_value) { fprintf (stderr, "'0' is not valid value for parameter '%s'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.threads = param_value; return value_res; } static enum PerfRepl_param_result process_param__thread_per_conn (const char *param_name) { if (tool_params.all_cpus) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-A' or '--all-cpus'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (0 != tool_params.threads) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-t' or '--threads'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.thread_per_conn = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__epoll (const char *param_name) { if (tool_params.poll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-p' or '--poll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.select) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-s' or '--select'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.epoll = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__poll (const char *param_name) { if (tool_params.epoll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-e' or '--epoll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.select) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-s' or '--select'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.poll = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__select (const char *param_name) { if (tool_params.epoll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-e' or '--epoll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.poll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-p' or '--poll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.select = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__empty (const char *param_name) { if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.empty = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__tiny (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.tiny = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__medium (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.medium = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__large (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.large = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__xlarge (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.xlarge = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__jumbo (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.jumbo = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__shared (const char *param_name) { if (tool_params.single) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-I' or '--single'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.unique) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-U' or '--unique'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.shared = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__single (const char *param_name) { if (tool_params.shared) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-S' or '--shared'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.unique) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-U' or '--unique'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.single = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__unique (const char *param_name) { if (tool_params.shared) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-S' or '--shared'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.single) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-I' or '--single'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.unique = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process parameter '-c' or '--connections' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__connections (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; if (0 == param_value) { fprintf (stderr, "'0' is not valid value for parameter '%s'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.connections = param_value; return value_res; } /** * Process parameter '-O' or '--timeout' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__timeout (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; tool_params.timeout = param_value; return value_res; } static enum PerfRepl_param_result process_param__date_header (const char *param_name) { tool_params.date_header = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__help (const char *param_name) { /* Use only one of help | version */ if (! tool_params.version) tool_params.help = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__version (const char *param_name) { /* Use only one of help | version */ if (! tool_params.help) tool_params.version = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process "short" (one character) parameter. * @param param the pointer to character after "-" or after another valid * parameter * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value with result */ static enum PerfRepl_param_result process_short_param (const char *param, const char *next_param) { const char param_chr = param[0]; if ('A' == param_chr) return process_param__all_cpus ("-A"); else if ('t' == param_chr) return process_param__threads ("-t", param + 1, next_param); else if ('P' == param_chr) return process_param__thread_per_conn ("-P"); else if ('e' == param_chr) return process_param__epoll ("-e"); else if ('p' == param_chr) return process_param__poll ("-p"); else if ('s' == param_chr) return process_param__select ("-s"); else if ('E' == param_chr) return process_param__empty ("-E"); else if ('T' == param_chr) return process_param__tiny ("-T"); else if ('M' == param_chr) return process_param__medium ("-M"); else if ('L' == param_chr) return process_param__large ("-L"); else if ('X' == param_chr) return process_param__xlarge ("-X"); else if ('J' == param_chr) return process_param__jumbo ("-J"); else if ('S' == param_chr) return process_param__shared ("-S"); else if ('I' == param_chr) return process_param__single ("-I"); else if ('U' == param_chr) return process_param__unique ("-U"); else if ('c' == param_chr) return process_param__connections ("-c", param + 1, next_param); else if ('O' == param_chr) return process_param__timeout ("-O", param + 1, next_param); else if ('V' == param_chr) return process_param__version ("-V"); fprintf (stderr, "Unrecognised parameter: -%c.\n", param_chr); return PERF_RPL_PARAM_ERROR; } /** * Process string of "short" (one character) parameters. * @param params_str the pointer to first character after "-" * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value with result */ static enum PerfRepl_param_result process_short_params_str (const char *params_str, const char *next_param) { if (0 == params_str[0]) { fprintf (stderr, "Unrecognised parameter: -\n"); return PERF_RPL_PARAM_ERROR; } do { enum PerfRepl_param_result param_res; param_res = process_short_param (params_str, next_param); if (PERF_RPL_PARAM_ONE_CHAR != param_res) return param_res; } while (0 != (++params_str)[0]); return PERF_RPL_PARAM_FULL_STR; } /** * Process "long" (--something) parameters. * @param param the pointer to first character after "--" * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_long_param (const char *param, const char *next_param) { const size_t param_len = strlen (param); if ((MHD_STATICSTR_LEN_ ("all-cpus") == param_len) && (0 == memcmp (param, "all-cpus", MHD_STATICSTR_LEN_ ("all-cpus")))) return process_param__all_cpus ("--all-cpus"); else if ((MHD_STATICSTR_LEN_ ("threads") <= param_len) && (0 == memcmp (param, "threads", MHD_STATICSTR_LEN_ ("threads")))) return process_param__threads ("--threads", param + MHD_STATICSTR_LEN_ ("threads"), next_param); else if ((MHD_STATICSTR_LEN_ ("thread-per-conn") == param_len) && (0 == memcmp (param, "thread-per-conn", MHD_STATICSTR_LEN_ ("thread-per-conn")))) return process_param__thread_per_conn ("--thread-per-conn"); else if ((MHD_STATICSTR_LEN_ ("epoll") == param_len) && (0 == memcmp (param, "epoll", MHD_STATICSTR_LEN_ ("epoll")))) return process_param__epoll ("--epoll"); else if ((MHD_STATICSTR_LEN_ ("poll") == param_len) && (0 == memcmp (param, "poll", MHD_STATICSTR_LEN_ ("poll")))) return process_param__poll ("--poll"); else if ((MHD_STATICSTR_LEN_ ("select") == param_len) && (0 == memcmp (param, "select", MHD_STATICSTR_LEN_ ("select")))) return process_param__select ("--select"); else if ((MHD_STATICSTR_LEN_ ("empty") == param_len) && (0 == memcmp (param, "empty", MHD_STATICSTR_LEN_ ("empty")))) return process_param__empty ("--empty"); else if ((MHD_STATICSTR_LEN_ ("tiny") == param_len) && (0 == memcmp (param, "tiny", MHD_STATICSTR_LEN_ ("tiny")))) return process_param__tiny ("--tiny"); else if ((MHD_STATICSTR_LEN_ ("medium") == param_len) && (0 == memcmp (param, "medium", MHD_STATICSTR_LEN_ ("medium")))) return process_param__medium ("--medium"); else if ((MHD_STATICSTR_LEN_ ("large") == param_len) && (0 == memcmp (param, "large", MHD_STATICSTR_LEN_ ("large")))) return process_param__large ("--large"); else if ((MHD_STATICSTR_LEN_ ("xlarge") == param_len) && (0 == memcmp (param, "xlarge", MHD_STATICSTR_LEN_ ("xlarge")))) return process_param__xlarge ("--xlarge"); else if ((MHD_STATICSTR_LEN_ ("jumbo") == param_len) && (0 == memcmp (param, "jumbo", MHD_STATICSTR_LEN_ ("jumbo")))) return process_param__jumbo ("--jumbo"); else if ((MHD_STATICSTR_LEN_ ("shared") == param_len) && (0 == memcmp (param, "shared", MHD_STATICSTR_LEN_ ("shared")))) return process_param__shared ("--shared"); else if ((MHD_STATICSTR_LEN_ ("single") == param_len) && (0 == memcmp (param, "single", MHD_STATICSTR_LEN_ ("single")))) return process_param__single ("--single"); else if ((MHD_STATICSTR_LEN_ ("unique") == param_len) && (0 == memcmp (param, "unique", MHD_STATICSTR_LEN_ ("unique")))) return process_param__unique ("--unique"); else if ((MHD_STATICSTR_LEN_ ("connections") <= param_len) && (0 == memcmp (param, "connections", MHD_STATICSTR_LEN_ ("connections")))) return process_param__connections ("--connections", param + MHD_STATICSTR_LEN_ ("connections"), next_param); else if ((MHD_STATICSTR_LEN_ ("timeout") <= param_len) && (0 == memcmp (param, "timeout", MHD_STATICSTR_LEN_ ("timeout")))) return process_param__timeout ("--timeout", param + MHD_STATICSTR_LEN_ ("timeout"), next_param); else if ((MHD_STATICSTR_LEN_ ("date-header") == param_len) && (0 == memcmp (param, "date-header", MHD_STATICSTR_LEN_ ("date-header")))) return process_param__date_header ("--date-header"); else if ((MHD_STATICSTR_LEN_ ("help") == param_len) && (0 == memcmp (param, "help", MHD_STATICSTR_LEN_ ("help")))) return process_param__help ("--help"); else if ((MHD_STATICSTR_LEN_ ("version") == param_len) && (0 == memcmp (param, "version", MHD_STATICSTR_LEN_ ("version")))) return process_param__version ("--version"); fprintf (stderr, "Unrecognised parameter: --%s.\n", param); return PERF_RPL_PARAM_ERROR; } static int process_params (int argc, char *const *argv) { int proc_dash_param = ! 0; int i; for (i = 1; i < argc; ++i) { /** * The currently processed argument */ const char *const p = argv[i]; const char *const p_next = (argc == (i + 1)) ? NULL : (argv[i + 1]); if (NULL == p) { fprintf (stderr, "The NULL in the parameter number %d. " "The error in the C library?\n", i); continue; } else if (0 == p[0]) continue; /* Empty */ else if (proc_dash_param && ('-' == p[0])) { enum PerfRepl_param_result param_res; if ('-' == p[1]) { if (0 == p[2]) { proc_dash_param = 0; /* The '--' parameter */ continue; } param_res = process_long_param (p + 2, p_next); } else param_res = process_short_params_str (p + 1, p_next); if (PERF_RPL_PARAM_ERROR == param_res) return PERF_RPL_ERR_CODE_BAD_PARAM; if (PERF_RPL_PARAM_STR_PLUS_NEXT == param_res) ++i; else if (PERF_RPL_PARAM_ONE_CHAR == param_res) abort (); continue; } else if (('0' <= p[0]) && ('9' >= p[0])) { /* Process the port number */ unsigned int read_port; size_t num_digits; num_digits = mhd_tool_str_to_uint (p, &read_port); if (0 != p[num_digits]) { fprintf (stderr, "Error in specified port number: %s\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } else if (65535 < read_port) { fprintf (stderr, "Wrong port number: %s\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } mhd_port = (uint16_t) read_port; } else { fprintf (stderr, "Unrecognised parameter: %s\n\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } } return 0; } static void print_version (void) { printf ("%s (GNU libmicrohttpd", self_name); if (0 != build_revision[0]) printf ("; %s", build_revision); printf (") %s\n", MHD_get_version ()); printf ("%s\n", tool_copyright); } static void print_all_cores_used (void) { printf ("No CPU cores on this machine are left unused and available " "for the client / requests generator. " "Testing with remote client is recommended.\n"); } static void check_param_port (void) { if (0 != tool_params.port) return; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) tool_params.port = PERF_REPL_PORT_FALLBACK; } /** * Apply parameter '-A' or '--all-cpus' */ static void check_apply_param__all_cpus (void) { if (! tool_params.all_cpus) return; num_threads = get_process_cpu_core_count (); printf ("Requested use of all available CPU cores for MHD threads.\n"); if (get_cpu_core_count () == num_threads) print_all_cores_used (); } /** * Apply parameter '-t' or '--threads' */ static void check_apply_param__threads (void) { if (0 == tool_params.threads) return; num_threads = tool_params.threads; if (get_process_cpu_core_count () < num_threads) { fprintf (stderr, "WARNING: The requested number of threads (%u) is " "higher than the number of detected available CPU cores (%u).\n", num_threads, get_process_cpu_core_count ()); fprintf (stderr, "This decreases the performance. " "Consider using fewer threads.\n"); } if (get_cpu_core_count () == num_threads) { printf ("The requested number of threads is equal to the number of " "detected CPU cores.\n"); print_all_cores_used (); } } /** * Apply parameter '-P' or '--thread-per-conn' * @return non-zero - OK, zero - error */ static int check_apply_param__thread_per_conn (void) { if (! tool_params.thread_per_conn) return ! 0; if (tool_params.epoll) { fprintf (stderr, "'Thread-per-connection' mode cannot be used together " "with 'epoll'.\n"); return 0; } num_threads = 1; return ! 0; } /* non-zero - OK, zero - error */ static int check_param__epoll (void) { if (! tool_params.epoll) return ! 0; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { fprintf (stderr, "'epoll' was requested, but this MHD build does not " "support 'epoll' functionality.\n"); return 0; } return ! 0; } /* non-zero - OK, zero - error */ static int check_param__poll (void) { if (! tool_params.poll) return ! 0; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_POLL)) { fprintf (stderr, "poll() was requested, but this MHD build does not " "support polling by poll().\n"); return 0; } return ! 0; } static void check_param__empty_tiny_medium_large_xlarge_jumbo (void) { if (0 == (tool_params.empty | tool_params.tiny | tool_params.medium | tool_params.large | tool_params.xlarge | tool_params.jumbo)) tool_params.tiny = ! 0; } static void check_param__shared_single_unique (void) { if (0 == (tool_params.shared | tool_params.single | tool_params.unique)) tool_params.shared = ! 0; } /* Must be called after 'check_apply_param__threads()' and 'check_apply_param__all_cpus()' */ /* non-zero - OK, zero - error */ static int check_param__connections (void) { if (0 == tool_params.connections) return ! 0; if (get_num_threads () > tool_params.connections) { fprintf (stderr, "The connections number limit (%u) is less than number " "of threads used (%u). Use higher value for connections limit.\n", tool_params.connections, get_num_threads ()); return 0; } return ! 0; } /** * Apply decoded parameters * @return 0 if success, * positive error code if case of error, * -1 to exit program with success (0) error code. */ static int check_apply_params (void) { if (tool_params.help) { show_help (); return -1; } else if (tool_params.version) { print_version (); return -1; } check_param_port (); check_apply_param__all_cpus (); check_apply_param__threads (); if (! check_apply_param__thread_per_conn ()) return PERF_RPL_ERR_CODE_BAD_PARAM; if (! check_param__epoll ()) return PERF_RPL_ERR_CODE_BAD_PARAM; if (! check_param__poll ()) return PERF_RPL_ERR_CODE_BAD_PARAM; check_param__empty_tiny_medium_large_xlarge_jumbo (); check_param__shared_single_unique (); if (! check_param__connections ()) return PERF_RPL_ERR_CODE_BAD_PARAM; return 0; } static uint64_t mini_rnd (void) { /* Simple xoshiro256+ implementation */ static uint64_t s[4] = { 0xE220A8397B1DCDAFuLL, 0x6E789E6AA1B965F4uLL, 0x06C45D188009454FuLL, 0xF88BB8A8724C81ECuLL }; /* Good enough for static initialisation */ const uint64_t ret = s[0] + s[3]; const uint64_t t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = ((s[3] << 45u) | (s[3] >> (64u - 45u))); return ret; } /* The pool of shared responses */ static struct MHD_Response **resps = NULL; static unsigned int num_resps = 0; /* The single response */ static struct MHD_Response *resp_single = NULL; /* Use the same memory area to avoid multiple copies. The system will keep it in cache. */ static const char tiny_body[] = "Hi!"; static char *body_dyn = NULL; /* Non-static body data */ static size_t body_dyn_size; /* Non-zero - success, zero - failure */ static int init_response_body_data (void) { if (0 != body_dyn_size) { body_dyn = (char *) malloc (body_dyn_size); if (NULL == body_dyn) { fprintf (stderr, "Failed to allocate memory.\n"); return 0; } if (16u * 1024u >= body_dyn_size) { /* Fill the body with HTML-like content */ size_t pos; size_t filler_pos; static const char body_header[] = "\n" "\nSample page title\n\n" "\n"; static const char body_filler[] = "The quick brown fox jumps over the lazy dog.
\n"; static const char body_footer[] = "\n" "\n"; pos = 0; memcpy (body_dyn + pos, body_header, MHD_STATICSTR_LEN_ (body_header)); pos += MHD_STATICSTR_LEN_ (body_header); for (filler_pos = 0; filler_pos < (body_dyn_size - (MHD_STATICSTR_LEN_ (body_header) + MHD_STATICSTR_LEN_ (body_footer))); ++filler_pos) { body_dyn[pos + filler_pos] = body_filler[filler_pos % MHD_STATICSTR_LEN_ (body_filler)]; } pos += filler_pos; memcpy (body_dyn + pos, body_footer, MHD_STATICSTR_LEN_ (body_footer)); } else if (2u * 1024u * 1024u >= body_dyn_size) { /* Fill the body with binary-like content */ size_t pos; for (pos = 0; pos < body_dyn_size; ++pos) { body_dyn[pos] = (char) (unsigned char) (255U - pos % 256U); } } else { /* Fill the body with pseudo-random binary-like content */ size_t pos; uint64_t rnd_data; for (pos = 0; pos < body_dyn_size - body_dyn_size % 8; pos += 8) { rnd_data = mini_rnd (); body_dyn[pos + 0] = (char) (unsigned char) (rnd_data >> 0); body_dyn[pos + 1] = (char) (unsigned char) (rnd_data >> 8); body_dyn[pos + 2] = (char) (unsigned char) (rnd_data >> 16); body_dyn[pos + 3] = (char) (unsigned char) (rnd_data >> 24); body_dyn[pos + 4] = (char) (unsigned char) (rnd_data >> 32); body_dyn[pos + 5] = (char) (unsigned char) (rnd_data >> 40); body_dyn[pos + 6] = (char) (unsigned char) (rnd_data >> 48); body_dyn[pos + 7] = (char) (unsigned char) (rnd_data >> 56); } rnd_data = mini_rnd (); for ((void) pos; pos < body_dyn_size; ++pos) { body_dyn[pos] = (char) (unsigned char) (rnd_data); rnd_data >>= 8u; } } } return ! 0; } static struct MHD_Response * create_response_object (void) { #if MHD_VERSION >= 0x00097701 if (NULL != body_dyn) return MHD_create_response_from_buffer_static (body_dyn_size, body_dyn); else if (tool_params.empty) return MHD_create_response_empty (MHD_RF_NONE); return MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (tiny_body), tiny_body); #else /* MHD_VERSION < 0x00097701 */ if (NULL != body_dyn) return MHD_create_response_from_buffer (body_dyn_size, (void *) body_dyn, MHD_RESPMEM_PERSISTENT); else if (tool_params.empty) return MHD_create_response_from_buffer (0, (void *) tiny_body, MHD_RESPMEM_PERSISTENT); return MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (tiny_body), (void *) tiny_body, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ } static int init_data (void) { unsigned int i; if (tool_params.medium) body_dyn_size = 8U * 1024U; else if (tool_params.large) body_dyn_size = 1024U * 1024U; else if (tool_params.xlarge) body_dyn_size = 8U * 1024U * 1024U; else if (tool_params.jumbo) body_dyn_size = 101U * 1024U * 1024U; else body_dyn_size = 0; if (! init_response_body_data ()) return 25; if (tool_params.unique) return 0; /* Responses are generated on-fly */ if (tool_params.single) { resp_single = create_response_object (); if (NULL == resp_single) { fprintf (stderr, "Failed to create response.\n"); return 25; } return 0; } /* Use more responses to minimise waiting in threads while the response used by other thread. */ if (! tool_params.thread_per_conn) num_resps = 16 * get_num_threads (); else num_resps = 16 * get_cpu_core_count (); resps = (struct MHD_Response **) malloc ((sizeof(struct MHD_Response *)) * num_resps); if (NULL == resps) { if (NULL != body_dyn) { free (body_dyn); body_dyn = NULL; } fprintf (stderr, "Failed to allocate memory.\n"); return 25; } for (i = 0; i < num_resps; ++i) { resps[i] = create_response_object (); if (NULL == resps[i]) { fprintf (stderr, "Failed to create responses.\n"); break; } } if (i == num_resps) return 0; /* Success */ /* Cleanup */ while (i-- != 0) MHD_destroy_response (resps[i]); free (resps); resps = NULL; num_resps = 0; if (NULL != body_dyn) free (body_dyn); body_dyn = NULL; return 32; } static void deinit_data (void) { if (NULL != resp_single) MHD_destroy_response (resp_single); resp_single = NULL; if (NULL != resps) { unsigned int i; for (i = 0; i < num_resps; ++i) MHD_destroy_response (resps[i]); num_resps = 0; free (resps); } resps = NULL; if (NULL != body_dyn) free (body_dyn); body_dyn = NULL; } static enum MHD_Result answer_shared_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; unsigned int resp_index; static volatile unsigned int last_index = 0; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ /* This kind of operation does not guarantee that numbers are not reused in parallel threads, when processed simultaneously, but this should not be a big problem, as it just slow down replies a bit due to response locking. */ resp_index = (last_index++) % num_resps; return MHD_queue_response (connection, MHD_HTTP_OK, resps[resp_index]); } static enum MHD_Result answer_single_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ return MHD_queue_response (connection, MHD_HTTP_OK, resp_single); } static enum MHD_Result answer_unique_empty_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_empty (MHD_RF_NONE); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (0, NULL, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static enum MHD_Result answer_unique_tiny_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (tiny_body), tiny_body); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (tiny_body), (void *) tiny_body, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static enum MHD_Result answer_unique_dyn_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_from_buffer_static (body_dyn_size, body_dyn); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (body_dyn_size, (void *) body_dyn, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static void print_perf_warnings (void) { int newline_needed = 0; #if defined (_DEBUG) fprintf (stderr, "WARNING: Running with debug asserts enabled, " "the performance is suboptimal.\n"); newline_needed |= ! 0; #endif /* _DEBUG */ #if defined(__GNUC__) && ! defined (__OPTIMIZE__) fprintf (stderr, "WARNING: This tool is compiled without enabled compiler " "optimisations, the performance is suboptimal.\n"); newline_needed |= ! 0; #endif /* __GNUC__ && ! __OPTIMIZE__ */ #if defined(__GNUC__) && defined (__OPTIMIZE_SIZE__) fprintf (stderr, "WARNING: This tool is compiled with size-optimisations, " "the performance is suboptimal.\n"); #endif /* __GNUC__ && ! __OPTIMIZE__ */ #if MHD_VERSION >= 0x00097701 if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_DEBUG_BUILD)) { fprintf (stderr, "WARNING: The libmicrohttpd is compiled with " "debug asserts enabled, the performance is suboptimal.\n"); newline_needed |= ! 0; } #endif /* MHD_VERSION >= 0x00097701 */ if (newline_needed) printf ("\n"); } /* Borrowed from daemon.c */ /* TODO: run-time detection */ /** * Default connection limit. */ #ifdef MHD_POSIX_SOCKETS #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 4) #else #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2) #endif static unsigned int get_mhd_conn_limit (struct MHD_Daemon *d) { /* TODO: implement run-time detection */ (void) d; /* Unused */ if (0 != tool_params.connections) return tool_params.connections; return (unsigned int) MHD_MAX_CONNECTIONS_DEFAULT; } static const char * get_mhd_response_size (void) { if (tool_params.empty) return "0 bytes (empty)"; else if (tool_params.tiny) return "3 bytes (tiny)"; else if (tool_params.medium) return "8 KiB (medium)"; else if (tool_params.large) return "1 MiB (large)"; else if (tool_params.xlarge) return "8 MiB (xlarge)"; else if (tool_params.jumbo) return "101 MiB (jumbo)"; return "!!internal error!!"; } static int run_mhd (void) { MHD_AccessHandlerCallback reply_func; struct MHD_Daemon *d; unsigned int use_num_threads; unsigned int flags = MHD_NO_FLAG; struct MHD_OptionItem opt_arr[16]; size_t opt_count = 0; const union MHD_DaemonInfo *d_info; const char *poll_mode; uint16_t port; if (tool_params.thread_per_conn) use_num_threads = 0; else use_num_threads = get_num_threads (); printf ("\n"); print_perf_warnings (); printf ("Responses:\n"); printf (" Sharing: "); if (tool_params.shared) { reply_func = &answer_shared_response; printf ("pre-generated shared pool with %u objects\n", num_resps); } else if (tool_params.single) { reply_func = &answer_single_response; printf ("single pre-generated reused response object\n"); } else { /* Unique responses */ if (tool_params.empty) reply_func = &answer_unique_empty_response; else if (tool_params.tiny) reply_func = &answer_unique_tiny_response; else reply_func = &answer_unique_dyn_response; printf ("one-time response object generated for every request\n"); } printf (" Body size: %s\n", get_mhd_response_size ()); flags |= MHD_USE_ERROR_LOG; flags |= MHD_USE_INTERNAL_POLLING_THREAD; if (tool_params.epoll) flags |= MHD_USE_EPOLL; else if (tool_params.poll) flags |= MHD_USE_POLL; else if (tool_params.select) (void) flags; /* No special additional flag */ else flags |= MHD_USE_AUTO; if (tool_params.thread_per_conn) flags |= MHD_USE_THREAD_PER_CONNECTION; if (! tool_params.date_header) flags |= MHD_USE_SUPPRESS_DATE_NO_CLOCK; if (0 != tool_params.connections) { opt_arr[opt_count].option = MHD_OPTION_CONNECTION_LIMIT; opt_arr[opt_count].value = (intptr_t) tool_params.connections; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1 < use_num_threads) { opt_arr[opt_count].option = MHD_OPTION_THREAD_POOL_SIZE; opt_arr[opt_count].value = (intptr_t) use_num_threads; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1) { opt_arr[opt_count].option = MHD_OPTION_CONNECTION_TIMEOUT; opt_arr[opt_count].value = (intptr_t) tool_params.timeout; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1) { struct MHD_OptionItem option = { MHD_OPTION_END, 0, NULL }; opt_arr[opt_count] = option; if (opt_count >= (sizeof(opt_arr) / sizeof(opt_arr[0]))) abort (); } d = MHD_start_daemon (flags, mhd_port, NULL, NULL, reply_func, NULL, MHD_OPTION_ARRAY, opt_arr, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Error starting MHD daemon.\n"); return 15; } d_info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == d_info) abort (); flags = (unsigned int) d_info->flags; if (0 != (flags & MHD_USE_POLL)) poll_mode = "poll()"; else if (0 != (flags & MHD_USE_EPOLL)) poll_mode = "epoll"; else poll_mode = "select()"; d_info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == d_info) abort (); port = d_info->port; if (0 == port) fprintf (stderr, "Cannot detect port number. Consider specifying " "port number explicitly.\n"); printf ("MHD is running.\n"); printf (" Bind port: %u\n", (unsigned int) port); printf (" Polling function: %s\n", poll_mode); printf (" Threading: "); if (MHD_USE_THREAD_PER_CONNECTION == (flags & MHD_USE_THREAD_PER_CONNECTION)) printf ("thread per connection\n"); else if (1 == get_num_threads ()) printf ("one MHD thread\n"); else printf ("%u MHD threads in thread pool\n", get_num_threads ()); printf (" Connections limit: %u\n", get_mhd_conn_limit (d)); printf (" Connection timeout: %u%s\n", tool_params.timeout, 0 == tool_params.timeout ? " (no timeout)" : ""); printf (" 'Date:' header: %s\n", tool_params.date_header ? "Yes" : "No"); printf ("To test with remote client use " "http://HOST_IP:%u/\n", (unsigned int) port); printf ("To test with client on the same host use " "http://127.0.0.1:%u/\n", (unsigned int) port); printf ("\nPress ENTER to stop.\n"); if (1) { char buf[10]; (void) fgets (buf, sizeof(buf), stdin); } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { int ret; set_self_name (argc, argv); ret = process_params (argc, argv); if (0 != ret) return ret; ret = check_apply_params (); if (0 > ret) return 0; if (0 != ret) return ret; ret = init_data (); if (0 != ret) return ret; ret = run_mhd (); deinit_data (); return ret; } libmicrohttpd-1.0.2/src/tools/mhd_tool_get_cpu_count.h0000644000175000017500000000357014760713577020150 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_get_cpu_count.h * @brief Declaration of functions to detect the number of available * CPU cores. * @author Karlson2k (Evgeny Grin) */ #ifndef SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ #define SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ 1 /** * Detect the number of logical CPU cores available for the process. * The number of cores available for this process could be different from * value of cores available on the system. The OS may have limit on number * assigned/allowed cores for single process and process may have limited * CPU affinity. * @return the number of logical CPU cores available for the process or * -1 if failed to detect */ int mhd_tool_get_proc_cpu_count (void); /** * Try to detect the number of logical CPU cores available for the system. * The number of available logical CPU cores could be changed any time due to * CPU hotplug. * @return the number of logical CPU cores available, * -1 if failed to detect. */ int mhd_tool_get_system_cpu_count (void); #endif /* SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ */ libmicrohttpd-1.0.2/src/tools/mhd_tool_get_cpu_count.c0000644000175000017500000007205015035214301020113 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_get_cpu_count.c * @brief Implementation of functions to detect the number of available * CPU cores. * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_tool_get_cpu_count.h" #ifdef HAVE_SYS_TYPES_H # include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_PARAM_H # include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_SYS__CPUSET_H # include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_STDDEF_H # include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STRING_H # include #endif /* HAVE_STRING_H */ #ifdef HAVE_SYS_SYSCTL_H # include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_FEATURES_H # include #endif /* HAVE_FEATURES_H */ #ifdef HAVE_UNISTD_H # include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_VXCPULIB_H # include #endif #ifdef HAVE_WINDOWS_H # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* ! WIN32_LEAN_AND_MEAN */ # include # ifndef ALL_PROCESSOR_GROUPS # define ALL_PROCESSOR_GROUPS 0xFFFFu # endif /* ALL_PROCESSOR_GROUPS */ #elif defined(_WIN32) && ! defined (__CYGWIN__) # error Windows headers are required for Windows build #endif /* HAVE_WINDOWS_H */ #ifdef HAVE_SCHED_H # include #endif /* HAVE_SCHED_H */ #ifdef HAVE_SYS_CPUSET_H # include #endif /* HAVE_SYS_CPUSET_H */ #ifdef HAVE_STDBOOL_H # include #endif /* HAVE_STDBOOL_H */ #if ! defined(HAS_DECL_CPU_SETSIZE) && ! defined(CPU_SETSIZE) # define CPU_SETSIZE (1024) # define CPU_SETSIZE_SAFE (64) #else /* HAS_DECL_CPU_SETSIZE || CPU_SETSIZE */ # define CPU_SETSIZE_SAFE CPU_SETSIZE #endif /* HAS_DECL_CPU_SETSIZE || CPU_SETSIZE */ /* Check and fix possible missing macros */ #if ! defined(HAS_DECL_CTL_HW) && defined(CTL_HW) # define HAS_DECL_CTL_HW 1 #endif /* ! HAS_DECL_CTL_HW && CTL_HW */ #if ! defined(HAS_DECL_HW_NCPUONLINE) && defined(HW_NCPUONLINE) # define HAS_DECL_HW_NCPUONLINE 1 #endif /* ! HAS_DECL_HW_NCPUONLINE && HW_NCPUONLINE */ #if ! defined(HAS_DECL_HW_AVAILCPU) && defined(HW_AVAILCPU) # define HAS_DECL_HW_AVAILCPU 1 #endif /* ! HAS_DECL_HW_AVAILCPU && HW_AVAILCPU */ #if ! defined(HAS_DECL_HW_NCPU) && defined(HW_NCPU) # define HAS_DECL_HW_NCPU 1 #endif /* ! HAS_DECL_HW_NCPU && HW_NCPU */ #if ! defined(HAS_DECL__SC_NPROCESSORS_ONLN) && defined(_SC_NPROCESSORS_ONLN) # define HAS_DECL__SC_NPROCESSORS_ONLN 1 #endif /* ! HAS_DECL__SC_NPROCESSORS_ONLN && _SC_NPROCESSORS_ONLN */ #if ! defined(HAS_DECL__SC_NPROC_ONLN) && defined(_SC_NPROC_ONLN) # define HAS_DECL__SC_NPROC_ONLN 1 #endif /* ! HAS_DECL__SC_NPROC_ONLN && _SC_NPROC_ONLN */ #if ! defined(HAS_DECL__SC_CRAY_NCPU) && defined(_SC_CRAY_NCPU) # define HAS_DECL__SC_CRAY_NCPU 1 #endif /* ! HAS_DECL__SC_CRAY_NCPU && _SC_CRAY_NCPU */ #if ! defined(HAS_DECL__SC_NPROCESSORS_CONF) && defined(_SC_NPROCESSORS_CONF) # define HAS_DECL__SC_NPROCESSORS_CONF 1 #endif /* ! HAVE_DECL__SC_NPROCESSORS_CONF && _SC_NPROCESSORS_CONF */ /* Forward declarations */ static int mhd_tool_get_sys_cpu_count_sysctl_ (void); /** * Detect the number of logical CPU cores available for the process by * sched_getaffinity() (and related) function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_sched_getaffinity_ (void) { int ret = -1; #if defined(HAVE_SCHED_GETAFFINITY) && defined(HAVE_GETPID) /* Glibc style */ if (0 >= ret) { cpu_set_t cur_set; if (0 == sched_getaffinity (getpid (), sizeof (cur_set), &cur_set)) { #ifdef HAVE_CPU_COUNT ret = CPU_COUNT (&cur_set); #else /* ! HAVE_CPU_COUNT */ unsigned int i; ret = 0; for (i = 0; i < CPU_SETSIZE_SAFE; ++i) { if (CPU_ISSET (i, &cur_set)) ++ret; } if (0 == ret) ret = -1; #endif /* ! HAVE_CPU_COUNT */ } } #ifdef HAVE_CPU_COUNT_S if (0 >= ret) { /* Use 256 times larger size than size for default maximum CPU number. Hopefully it would be enough even for exotic situations. */ static const unsigned int set_size_cpus = 256 * CPU_SETSIZE; const size_t set_size_bytes = CPU_ALLOC_SIZE (set_size_cpus); cpu_set_t *p_set; p_set = CPU_ALLOC (set_size_cpus); if (NULL != p_set) { if (0 == sched_getaffinity (getpid (), set_size_bytes, p_set)) { #ifndef MHD_FUNC_CPU_COUNT_S_GETS_CPUS ret = CPU_COUNT_S (set_size_bytes, p_set); #else /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ ret = CPU_COUNT_S (set_size_cpus, p_set); #endif /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ } CPU_FREE (p_set); } } #endif /* HAVE_CPU_COUNT_S */ #endif /* HAVE_SCHED_GETAFFINITY && HAVE_GETPID */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * cpuset_getaffinity() function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (void) { int ret = -1; #if defined(HAVE_CPUSET_GETAFFINITY) /* FreeBSD style */ if (0 >= ret) { cpuset_t cur_mask; /* The should get "anonymous" mask/set. The anonymous mask is always a subset of the assigned set (which is a subset of the root set). */ if (0 == cpuset_getaffinity (CPU_LEVEL_WHICH, CPU_WHICH_PID, (id_t) -1, sizeof (cur_mask), &cur_mask)) { #ifdef HAVE_CPU_COUNT ret = CPU_COUNT (&cur_mask); #else /* ! HAVE_CPU_COUNT */ unsigned int i; ret = 0; for (i = 0; i < CPU_SETSIZE_SAFE; ++i) { if (CPU_ISSET (i, &cur_mask)) ++ret; } if (0 == ret) ret = -1; #endif /* ! HAVE_CPU_COUNT */ } } #ifdef HAVE_CPU_COUNT_S if (0 >= ret) { /* Use 256 times larger size than size for default maximum CPU number. Hopefully it would be enough even for exotic situations. */ static const unsigned int mask_size_cpus = 256 * CPU_SETSIZE; const size_t mask_size_bytes = CPU_ALLOC_SIZE (mask_size_cpus); cpuset_t *p_mask; p_mask = CPU_ALLOC (mask_size_cpus); if (NULL != p_mask) { if (0 == cpuset_getaffinity (CPU_LEVEL_WHICH, CPU_WHICH_PID, (id_t) -1, mask_size_bytes, p_mask)) { #ifndef MHD_FUNC_CPU_COUNT_S_GETS_CPUS ret = CPU_COUNT_S (mask_size_bytes, p_mask); #else /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ ret = CPU_COUNT_S (mask_size_cpus, p_mask); #endif /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ } CPU_FREE (p_mask); } } #endif /* HAVE_CPU_COUNT_S */ #endif /* HAVE_CPUSET_GETAFFINITY */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * sched_getaffinity_np() (and related) function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_sched_getaffinity_np_ (void) { int ret = -1; #if defined(HAVE_SCHED_GETAFFINITY_NP) && defined(HAVE_GETPID) /* NetBSD style */ cpuset_t *cpuset_ptr; cpuset_ptr = cpuset_create (); if (NULL != cpuset_ptr) { if (0 == sched_getaffinity_np (getpid (), cpuset_size (cpuset_ptr), cpuset_ptr)) { cpuid_t cpu_num; #if defined(HAVE_SYSCONF) && defined(HAVE_DECL__SC_NPROCESSORS_CONF) unsigned int max_num = 0; long sc_value; sc_value = sysconf (_SC_NPROCESSORS_ONLN); if (0 < sc_value) max_num = (unsigned int) sc_value; if (0 < max_num) { ret = 0; for (cpu_num = 0; cpu_num < max_num; ++cpu_num) if (0 < cpuset_isset (cpu_num, cpuset_ptr)) ++ret; } else /* Combined with the next 'if' */ #endif /* HAVE_SYSCONF && HAVE_DECL__SC_NPROCESSORS_CONF */ if (1) { int res; cpu_num = 0; ret = 0; do { res = cpuset_isset (cpu_num++, cpuset_ptr); if (0 < res) ++ret; } while (0 <= res); } #ifdef __NetBSD__ if (0 == ret) { /* On NetBSD "unset" affinity (exactly zero CPUs) means "all CPUs are available". */ ret = mhd_tool_get_sys_cpu_count_sysctl_ (); } #endif /* __NetBSD__ */ } cpuset_destroy (cpuset_ptr); } #endif /* HAVE_SCHED_GETAFFINITY_NP && HAVE_GETPID */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * W32 API functions. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_w32_ (void) { int ret = -1; #if defined(_WIN32) && ! defined(__CYGWIN__) /* W32 Native */ /** * Maximum used number of CPU groups. * Improvement: Implement dynamic allocation when it would be reasonable */ #define MHDT_MAX_GROUP_COUNT 128 /** * The count of logical CPUs as returned by GetProcessAffinityMask() */ int count_by_proc_aff_mask; count_by_proc_aff_mask = -1; if (1) { DWORD_PTR proc_aff; DWORD_PTR sys_aff; if (GetProcessAffinityMask (GetCurrentProcess (), &proc_aff, &sys_aff)) { /* Count all set bits */ for (count_by_proc_aff_mask = 0; 0 != proc_aff; proc_aff &= proc_aff - 1) ++count_by_proc_aff_mask; } } if (0 < count_by_proc_aff_mask) { HMODULE k32hndl; k32hndl = LoadLibraryA ("kernel32.dll"); if (NULL != k32hndl) { typedef BOOL (WINAPI *GPGA_PTR)(HANDLE hProcess, PUSHORT GroupCount, PUSHORT GroupArray); GPGA_PTR ptrGetProcessGroupAffinity; ptrGetProcessGroupAffinity = (GPGA_PTR) (void *) GetProcAddress (k32hndl, "GetProcessGroupAffinity"); if (NULL == ptrGetProcessGroupAffinity) { /* Windows version before Win7 */ /* No processor groups supported, the process affinity mask gives full picture */ ret = count_by_proc_aff_mask; } else { /* Windows version Win7 or later */ /* Processor groups are supported */ USHORT arr_elements = MHDT_MAX_GROUP_COUNT; USHORT groups_arr[MHDT_MAX_GROUP_COUNT]; /* Hopefully should be enough */ /* Improvement: Implement dynamic allocation when it would be reasonable */ /** * Exactly one processor group is assigned to the process */ bool single_cpu_group_assigned; /**< Exactly one processor group is assigned to the process */ struct mhdt_GR_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3]; }; typedef BOOL (WINAPI *GPDCSM_PTR)(HANDLE Process, struct mhdt_GR_AFFINITY *CpuSetMasks, USHORT CpuSetMaskCount, USHORT *RequiredMaskCount); GPDCSM_PTR ptrGetProcessDefaultCpuSetMasks; bool win_fe_or_later; bool cpu_set_mask_assigned; single_cpu_group_assigned = false; if (ptrGetProcessGroupAffinity (GetCurrentProcess (), &arr_elements, groups_arr)) { if (1 == arr_elements) { /* Exactly one processor group assigned to the process */ single_cpu_group_assigned = true; #if 0 /* Disabled code */ /* The value returned by GetThreadGroupAffinity() is not relevant as for the new threads the process affinity mask is used. */ ULONG_PTR proc_aff2; typedef BOOL (WINAPI *GTGA_PTR)(HANDLE hThread, struct mhdt_GR_AFFINITY * GroupAffinity); GTGA_PTR ptrGetThreadGroupAffinity; ptrGetThreadGroupAffinity = (GTGA_PTR) (void *) GetProcAddress (k32hndl, "GetThreadGroupAffinity"); if (NULL != ptrGetThreadGroupAffinity) { struct mhdt_GR_AFFINITY thr_gr_aff; if (ptrGetThreadGroupAffinity (GetCurrentThread (), &thr_gr_aff)) proc_aff2 = (ULONG_PTR) thr_gr_aff.Mask; } #endif /* Disabled code */ } } ptrGetProcessDefaultCpuSetMasks = (GPDCSM_PTR) (void *) GetProcAddress (k32hndl, "GetProcessDefaultCpuSetMasks"); if (NULL != ptrGetProcessDefaultCpuSetMasks) { /* This is Iron Release / Codename Fe (also know as Windows 11 and Windows Server 2022) or later version */ struct mhdt_GR_AFFINITY gr_affs[MHDT_MAX_GROUP_COUNT]; /* Hopefully should be enough */ /* Improvement: Implement dynamic allocation when it would be reasonable */ USHORT num_elm; win_fe_or_later = true; if (ptrGetProcessDefaultCpuSetMasks (GetCurrentProcess (), gr_affs, sizeof (gr_affs) / sizeof (gr_affs[0]), &num_elm)) { if (0 == num_elm) { /* No group mask set */ cpu_set_mask_assigned = false; } else cpu_set_mask_assigned = true; } else cpu_set_mask_assigned = true; /* Assume the worst case */ } else { win_fe_or_later = false; cpu_set_mask_assigned = false; } if (! win_fe_or_later) { /* The OS is not capable of distributing threads across different processor groups. Results reported by GetProcessAffinityMask() are relevant for the main processor group for the process. */ ret = count_by_proc_aff_mask; } else { /* The of is capable of automatic threads distribution across processor groups. */ if (cpu_set_mask_assigned) { /* Assigned Default CpuSet Masks combines with "classic" affinity in the not fully clear way. The combination is not documented and this functionality could be changed any moment. */ ret = -1; } else { if (! single_cpu_group_assigned) { /* This is a multi processor group process on Win11 (or later). Each processor group may have different affinity and the OS has not API to get it. For example, affinity to the main processor group could be assigned by SetProcessAffinityMask() function, which converts the process to the single-processor-group type, but if SetThreadGroupAffinity() is called later and bind the thread to another processor group, the process becomes multi-processor- group again, however the initial affinity mask is still used for the initial (main) processor group. There is no API to read it. It is also possible that processor groups have different number of processors. */ ret = -1; } else { /* Single-processor-group process on Win11 (or later) without assigned Default CpuSet Masks. */ ret = count_by_proc_aff_mask; } } } } FreeLibrary (k32hndl); } } #endif /* _WIN32 && ! __CYGWIN__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process. * The number of cores available for this process could be different from * value of cores available on the system. The OS may have limit on number * assigned/allowed cores for single process and process may have limited * CPU affinity. * @return the number of logical CPU cores available for the process or * -1 if failed to detect */ int mhd_tool_get_proc_cpu_count (void) { int res; #if defined(__linux__) || defined(__GLIBC__) /* On Linux kernel try first 'sched_getaffinity()' as it should be the native API. Also try it first on other kernels if Glibc is used. */ res = mhd_tool_get_proc_cpu_count_sched_getaffinity_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (); if (0 < res) return res; #else /* ! __linux__ && ! __GLIBC__ */ /* On non-Linux kernels 'cpuset_getaffinity()' could be the native API, while 'sched_getaffinity()' could be implemented in compatibility layer. */ res = mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_sched_getaffinity_ (); if (0 < res) return res; #endif /* ! __linux__ && ! __GLIBC__ */ res = mhd_tool_get_proc_cpu_count_sched_getaffinity_np_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_w32_ (); if (0 < res) return res; return -1; } /** * Detect the number of processors by special API functions * @return number of processors as returned by special API functions or * -1 in case of error or special API functions unavailable */ static int mhd_tool_get_sys_cpu_count_special_api_ (void) { int ret = -1; #ifdef HAVE_PSTAT_GETDYNAMIC if (0 >= ret) { /* HP-UX things */ struct pst_dynamic psd_data; memset ((void *) &psd_data, 0, sizeof (psd_data)); if (1 == pstat_getdynamic (&psd_data, sizeof (psd_data), (size_t) 1, 0)) { if (0 < psd_data.psd_proc_cnt) ret = (int) psd_data.psd_proc_cnt; } } #endif /* HAVE_PSTAT_GETDYNAMIC */ #ifdef HAVE_VXCPUENABLEDGET if (0 >= ret) { /* VxWorks */ cpuset_t enb_set; enb_set = vxCpuEnabledGet (); /* Count set bits */ for (ret = 0; 0 != enb_set; enb_set &= enb_set - 1) ++ret; } #endif /* HAVE_VXCPUENABLEDGET */ #if defined(_WIN32) && ! defined (__CYGWIN__) if (0 >= ret) { /* Native W32 */ HMODULE k32hndl; k32hndl = LoadLibraryA ("kernel32.dll"); if (NULL != k32hndl) { typedef DWORD (WINAPI *GAPC_PTR)(WORD GroupNumber); GAPC_PTR ptrGetActiveProcessorCount; /* Available on W7 or later */ ptrGetActiveProcessorCount = (GAPC_PTR) (void *) GetProcAddress (k32hndl, "GetActiveProcessorCount"); if (NULL != ptrGetActiveProcessorCount) { DWORD res; res = ptrGetActiveProcessorCount (ALL_PROCESSOR_GROUPS); ret = (int) res; if (res != (DWORD) ret) ret = -1; /* Overflow */ } } if ((0 >= ret) && (NULL != k32hndl)) { typedef void (WINAPI *GNSI_PTR)(SYSTEM_INFO *pSysInfo); GNSI_PTR ptrGetNativeSystemInfo; /* May give incorrect (low) result on versions from W7 to W11 when more then 64 CPUs are available */ ptrGetNativeSystemInfo = (GNSI_PTR) (void *) GetProcAddress (k32hndl, "GetNativeSystemInfo"); if (NULL != ptrGetNativeSystemInfo) { SYSTEM_INFO sysInfo; memset ((void *) &sysInfo, 0, sizeof (sysInfo)); ptrGetNativeSystemInfo (&sysInfo); ret = (int) sysInfo.dwNumberOfProcessors; if (sysInfo.dwNumberOfProcessors != (DWORD) ret) ret = -1; /* Overflow */ } } if (NULL != k32hndl) FreeLibrary (k32hndl); } if (0 >= ret) { /* May give incorrect (low) result on versions from W7 to W11 when more then 64 CPUs are available */ SYSTEM_INFO sysInfo; memset ((void *) &sysInfo, 0, sizeof (sysInfo)); GetSystemInfo (&sysInfo); ret = (int) sysInfo.dwNumberOfProcessors; if (sysInfo.dwNumberOfProcessors != (DWORD) ret) ret = -1; /* Overflow */ } #endif /* _WIN32 && ! __CYGWIN__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysctl*() functions in reliable way. * * This function uses reliable identificators that coreponds to actual * number of CPU cores online currently. * @return number of processors as returned by 'sysctl*' functions or * -1 in case of error or the number cannot be detected * by these functions */ static int mhd_tool_get_sys_cpu_count_sysctl_ (void) { int ret = -1; /* Do not use sysctl() function on GNU/Linux even if sysctl() is available */ #ifndef __linux__ #ifdef HAVE_SYSCTLBYNAME if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The number of available logical CPUs */ if ((0 != sysctlbyname ("hw.logicalcpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* FreeBSD: The number of online CPUs */ if ((0 != sysctlbyname ("kern.smp.cpus", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The current number of CPUs available to run threads */ if ((0 != sysctlbyname ("hw.activecpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* OpenBSD, NetBSD: The number of online CPUs */ if ((0 != sysctlbyname ("hw.ncpuonline", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The old/alternative name for "hw.activecpu" */ if ((0 != sysctlbyname ("hw.availcpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTLBYNAME */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_NCPUONLINE) if (0 >= ret) { /* OpenBSD, NetBSD: The number of online CPUs */ int mib[2] = {CTL_HW, HW_NCPUONLINE}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_NCPUONLINE */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_AVAILCPU) if (0 >= ret) { /* Darwin: The MIB name for "hw.activecpu" */ int mib[2] = {CTL_HW, HW_AVAILCPU}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_AVAILCPU */ #endif /* ! __linux__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysctl*() functions, using fallback way. * * This function uses less reliable (compared to * #mhd_tool_get_sys_cpu_count_sysctl_()) ways to detect the number of * available CPU cores and may return values corresponding to the number of * physically available (but possibly not used by the kernel) CPU logical cores. * @return number of processors as returned by 'sysctl*' functions or * -1 in case of error or the number cannot be detected * by these functions */ static int mhd_tool_get_sys_cpu_count_sysctl_fallback_ (void) { int ret = -1; /* Do not use sysctl() function on GNU/Linux even if sysctl() is available */ #ifndef __linux__ #ifdef HAVE_SYSCTLBYNAME if (0 >= ret) { size_t value_size = sizeof (ret); /* FreeBSD, OpenBSD, NetBSD, Darwin (and others?): The number of CPUs */ if ((0 != sysctlbyname ("hw.ncpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTLBYNAME */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_NCPU) if (0 >= ret) { /* FreeBSD, OpenBSD, NetBSD, Darwin (and others?): The number of CPUs */ int mib[2] = {CTL_HW, HW_NCPU}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_NCPU */ #endif /* ! __linux__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysconf() function in reliable way. * * This function uses reliable identificators that coreponds to actual * number of CPU cores online currently. * @return number of processors as returned by 'sysconf' function or * -1 in case of error or 'sysconf' unavailable */ static int mhd_tool_get_sys_cpu_count_sysconf_ (void) { int ret = -1; #if defined(HAVE_SYSCONF) && \ (defined(HAS_DECL__SC_NPROCESSORS_ONLN) || defined(HAS_DECL__SC_NPROC_ONLN)) long value = -1; #ifdef HAS_DECL__SC_NPROCESSORS_ONLN if (0 >= value) value = sysconf (_SC_NPROCESSORS_ONLN); #endif /* HAS_DECL__SC_NPROCESSORS_ONLN */ #ifdef HAS_DECL__SC_NPROC_ONLN if (0 >= value) value = sysconf (_SC_NPROC_ONLN); #endif /* HAS_DECL__SC_NPROC_ONLN */ if (0 >= value) return -1; ret = (int) value; if ((long) ret != value) return -1; /* Overflow */ #endif /* HAVE_SYSCONF && (HAS_DECL__SC_NPROCESSORS_ONLN || HAS_DECL__SC_NPROC_ONLN) */ return ret; } /** * Detect the number of processors by sysconf() function, using fallback way. * * This function uses less reliable (compared to * #mhd_tool_get_sys_cpu_count_sysconf_()) ways to detect the number of * available CPU cores and may return values corresponding to the number of * physically available (but possibly not used by the kernel) CPU logical cores. * @return number of processors as returned by 'sysconf' function or * -1 in case of error or 'sysconf' unavailable */ static int mhd_tool_get_sys_cpu_count_sysconf_fallback_ (void) { int ret = -1; #if defined(HAVE_SYSCONF) && \ (defined(HAS_DECL__SC_CRAY_NCPU) || defined(HAS_DECL__SC_NPROCESSORS_CONF)) long value = -1; #ifdef HAS_DECL__SC_CRAY_NCPU if (0 >= value) value = sysconf (_SC_CRAY_NCPU); #endif /* HAS_DECL__SC_CRAY_NCPU */ #ifdef HAS_DECL__SC_NPROCESSORS_CONF if (0 >= value) value = sysconf (_SC_NPROCESSORS_CONF); #endif /* HAS_DECL__SC_NPROCESSORS_CONF */ if (0 >= value) return -1; ret = (int) value; if ((long) ret != value) return -1; /* Overflow */ #endif /* HAVE_SYSCONF && (HAS_DECL__SC_CRAY_NCPU || HAS_DECL__SC_NPROCESSORS_CONF) */ return ret; } /** * Try to detect the number of logical CPU cores available for the system. * The number of available logical CPU cores could be changed any time due to * CPU hotplug. * @return the number of logical CPU cores available, * -1 if failed to detect. */ int mhd_tool_get_system_cpu_count (void) { int res; /* Try specialised APIs first */ res = mhd_tool_get_sys_cpu_count_special_api_ (); if (0 < res) return res; /* Try sysctl*(). This is typically a direct interface to kernel values. */ res = mhd_tool_get_sys_cpu_count_sysctl_ (); if (0 < res) return res; /* Try sysconf() as the last resort as this is a generic interface which can be implemented by parsing system files. */ res = mhd_tool_get_sys_cpu_count_sysconf_ (); #if ! defined(__linux__) && ! defined(__GLIBC__) if (0 < res) return res; #else /* __linux__ || __GLIBC__ */ if (2 < res) return res; if (0 < res) { /* '1' or '2' could a be fallback number. * See get_nprocs_fallback() in glibc sysdeps/unix/sysv/linux/getsysstats.c */ int proc_cpu_count; proc_cpu_count = mhd_tool_get_proc_cpu_count (); if (proc_cpu_count == res) { /* The detected number of CPUs available for the process is equal to the detected number of system CPUs. Assume detected number is correct. */ return res; } } #endif /* __linux__ || __GLIBC__ */ /* Try available fallbacks */ res = mhd_tool_get_sys_cpu_count_sysctl_fallback_ (); if (0 < res) return res; res = mhd_tool_get_sys_cpu_count_sysconf_fallback_ (); #if ! defined(__linux__) && ! defined(__GLIBC__) if (0 < res) return res; #else /* __linux__ || __GLIBC__ */ if (2 < res) return res; #endif /* __linux__ || __GLIBC__ */ return -1; /* Cannot detect */ } libmicrohttpd-1.0.2/src/tools/Makefile.in0000644000175000017500000006441015035216310015274 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage noinst_PROGRAMS = $(am__EXEEXT_1) @USE_THREADS_TRUE@am__append_2 = \ @USE_THREADS_TRUE@ perf_replies subdir = src/tools ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @USE_THREADS_TRUE@am__EXEEXT_1 = perf_replies$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) am_perf_replies_OBJECTS = perf_replies.$(OBJEXT) \ mhd_tool_get_cpu_count.$(OBJEXT) perf_replies_OBJECTS = $(am_perf_replies_OBJECTS) perf_replies_LDADD = $(LDADD) perf_replies_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/mhd_tool_get_cpu_count.Po \ ./$(DEPDIR)/perf_replies.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(perf_replies_SOURCES) DIST_SOURCES = $(perf_replies_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -DMHD_REAL_CPU_COUNT=@MHD_REAL_CPU_COUNT@ \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la perf_replies_SOURCES = \ perf_replies.c mhd_tool_str_to_uint.h \ mhd_tool_get_cpu_count.h mhd_tool_get_cpu_count.c all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/tools/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/tools/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list perf_replies$(EXEEXT): $(perf_replies_OBJECTS) $(perf_replies_DEPENDENCIES) $(EXTRA_perf_replies_DEPENDENCIES) @rm -f perf_replies$(EXEEXT) $(AM_V_CCLD)$(LINK) $(perf_replies_OBJECTS) $(perf_replies_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_tool_get_cpu_count.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_replies.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(PROGRAMS) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/mhd_tool_get_cpu_count.Po -rm -f ./$(DEPDIR)/perf_replies.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/mhd_tool_get_cpu_count.Po -rm -f ./$(DEPDIR)/perf_replies.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-am clean clean-generic clean-libtool \ clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/tools/mhd_tool_str_to_uint.h0000644000175000017500000000370614760713577017664 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_str_to_uint.h * @brief Function to decode the value of decimal string number. * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_TOOL_STR_TO_UINT_H_ #define MHD_TOOL_STR_TO_UINT_H_ 1 #include /** * Convert decimal string to unsigned int. * Function stops at the end of the string or on first non-digit character. * @param str the string to convert * @param[out] value the pointer to put the result * @return return the number of digits converted or * zero if no digits found or result would overflow the output * variable (the output set to UINT_MAX in this case). */ static size_t mhd_tool_str_to_uint (const char *str, unsigned int *value) { size_t i; unsigned int v = 0; *value = 0; for (i = 0; 0 != str[i]; ++i) { const char chr = str[i]; unsigned int digit; if (('0' > chr) || ('9' < chr)) break; digit = (unsigned char) (chr - '0'); if ((((0U - 1) / 10) < v) || ((v * 10 + digit) < v)) { /* Overflow */ *value = 0U - 1; return 0; } v *= 10; v += digit; } *value = v; return i; } #endif /* MHD_TOOL_STR_TO_UINT_H_ */ libmicrohttpd-1.0.2/src/tools/Makefile.am0000644000175000017500000000167615035214301015266 00000000000000# This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -DMHD_REAL_CPU_COUNT=@MHD_REAL_CPU_COUNT@ \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tools noinst_PROGRAMS = if USE_THREADS noinst_PROGRAMS += \ perf_replies endif perf_replies_SOURCES = \ perf_replies.c mhd_tool_str_to_uint.h \ mhd_tool_get_cpu_count.h mhd_tool_get_cpu_count.c libmicrohttpd-1.0.2/src/include/0000755000175000017500000000000015035216652013576 500000000000000libmicrohttpd-1.0.2/src/include/autoinit_funcs.h0000644000175000017500000003021415035214301016706 00000000000000/* * AutoinitFuncs: Automatic Initialization and Deinitialization Functions * Copyright(C) 2014-2023 Karlson2k (Evgeny Grin) * * This header is free software; you can redistribute it and / or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This header is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this header; if not, see * . */ /* General usage is simple: include this header, declare or define two functions with zero parameters (void) and any return type: one for initialisation and one for deinitialisation, add _SET_INIT_AND_DEINIT_FUNCS(FuncInitName, FuncDeInitName) to the code and functions will be automatically called during application startup and shutdown. This is useful for libraries as libraries don't have direct access to main() functions. Example: ------------------------------------------------- #include #include "autoinit_funcs.h" int someVar; void* somePtr; void libInit(void) { someVar = 3; somePtr = malloc(100); } void libDeinit(void) { free(somePtr); } _SET_INIT_AND_DEINIT_FUNCS(libInit,libDeinit); ------------------------------------------------- If initialiser or deinitialiser function is not needed, just define it as empty function. This header should work with GCC, clang, MSVC (2010 or later) and SunPro / Sun Studio / Oracle Solaris Studio / Oracle Developer Studio compiler. Supported C and C++ languages; application, static and dynamic (DLL) libraries; non-optimized (Debug) and optimised (Release) compilation and linking. For more information see header code and comments in code. */ #ifndef AUTOINIT_FUNCS_INCLUDED #define AUTOINIT_FUNCS_INCLUDED 1 /** * Current version of the header in packed BCD form. * 0x01093001 = 1.9.30-1. */ #define AUTOINIT_FUNCS_VERSION 0x01001000 #if defined(__GNUC__) || defined(__clang__) /* if possible - check for supported attribute */ #ifdef __has_attribute #if ! __has_attribute (constructor) || ! __has_attribute (destructor) #define _GNUC_ATTR_CONSTR_NOT_SUPPORTED 1 #endif /* !__has_attribute(constructor) || !__has_attribute(destructor) */ #endif /* __has_attribute */ #endif /* __GNUC__ */ /* "__has_attribute__ ((constructor))" is supported by GCC, clang and Sun/Oracle compiler starting from version 12.1. */ #if ((defined(__GNUC__) || defined(__clang__)) && \ ! defined(_GNUC_ATTR_CONSTR_NOT_SUPPORTED)) || \ (defined(__SUNPRO_C) && __SUNPRO_C + 0 >= 0x5100) #define GNUC_SET_INIT_AND_DEINIT(FI,FD) \ void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void); \ void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void); \ void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void) \ { (void) (FI) (); } \ void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void) \ { (void) (FD) (); } \ struct _GNUC_dummy_str_ ## FI {int i;} #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) GNUC_SET_INIT_AND_DEINIT (FI,FD) #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1 #elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1600 /* Make sure that your project/sources define: _LIB if building a static library (_LIB is ignored if _CONSOLE is defined); _USRDLL if building DLL-library; not defined both _LIB and _USRDLL if building an application */ /* Define AUTOINIT_FUNCS_DECLARE_STATIC_REG if you need macro declaration for registering static initialisation functions even if you building DLL */ /* Define AUTOINIT_FUNCS_FORCE_STATIC_REG if you want to set main macro _SET_INIT_AND_DEINIT_FUNCS to static version even if building a DLL */ /* Stringify macros */ #define _INSTRMACRO(a) #a #define _STRMACRO(a) _INSTRMACRO (a) #if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_DECLARE_STATIC_REG) \ || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG) /* Use "C" linkage for variable to simplify variable decoration */ #ifdef __cplusplus #define W32_INITVARDECL extern "C" #else #define W32_INITVARDECL extern #endif /* How variable is decorated by compiler */ #if (defined(_WIN32) || defined(_WIN64)) \ && ! defined(_M_IX86) && ! defined(_X86_) #if ! defined(_M_X64) && ! defined(_M_AMD64) && ! defined(_x86_64_) \ && ! defined(_M_ARM) && ! defined(_M_ARM64) #pragma message(__FILE__ "(" _STRMACRO(__LINE__) ") : warning AIFW001 : " \ "Untested architecture, linker may fail with unresolved symbol") #endif /* ! _M_X64 && ! _M_AMD64 && ! _x86_64_ && ! _M_ARM && ! _M_ARM64 */ #define W32_VARDECORPREFIX #define W32_DECORVARNAME(v) v #define W32_VARDECORPREFIXSTR "" #elif defined(_WIN32) && (defined(_M_IX86) || defined(_X86_)) #define W32_VARDECORPREFIX _ #define W32_DECORVARNAME(v) _ ## v #define W32_VARDECORPREFIXSTR "_" #else #error Do not know how to decorate symbols for this architecture #endif /* Internal variable prefix (can be any) */ #define W32_INITHELPERVARNAME(f) _initHelperDummy_ ## f #define W32_INITHELPERVARNAMEDECORSTR(f) \ W32_VARDECORPREFIXSTR _STRMACRO (W32_INITHELPERVARNAME (f)) /* Declare section (segment), put variable pointing to init function to chosen segment, force linker to always include variable to avoid omitting by optimiser */ /* Initialisation function must be declared as void __cdecl FuncName(void) */ /* "extern" with initialisation value means that variable is declared AND defined. */ #define W32_VFPTR_IN_SEG(S,F) \ __pragma (section (S,long,read)) \ __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \ W32_INITVARDECL __declspec(allocate (S))void \ (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F /* Sections (segments) for pointers to initialisers/deinitialisers */ /* Semi-officially suggested section for early initialisers (called before C++ objects initialisers), "void" return type */ #define W32_SEG_INIT_EARLY ".CRT$XCT" /* Semi-officially suggested section for late initialisers (called after C++ objects initialisers), "void" return type */ #define W32_SEG_INIT_LATE ".CRT$XCV" /* Unsafe sections (segments) for pointers to initialisers/deinitialisers */ /* C++ lib initialisers, "void" return type (reserved by the system!) */ #define W32_SEG_INIT_CXX_LIB ".CRT$XCL" /* C++ user initialisers, "void" return type (reserved by the system!) */ #define W32_SEG_INIT_CXX_USER ".CRT$XCU" /* Declare section (segment), put variable pointing to init function to chosen segment, force linker to always include variable to avoid omitting by optimiser */ /* Initialisation function must be declared as int __cdecl FuncName(void) */ /* Startup process is aborted if initialiser returns non-zero */ /* "extern" with initialisation value means that variable is declared AND defined. */ #define W32_IFPTR_IN_SEG(S,F) \ __pragma (section (S,long,read)) \ __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \ W32_INITVARDECL __declspec(allocate (S))int \ (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F /* Unsafe sections (segments) for pointers to initialisers with "int" return type */ /* C lib initialisers, "int" return type (reserved by the system!). These initialisers are called before others. */ #define W32_SEG_INIT_C_LIB ".CRT$XIL" /* C user initialisers, "int" return type (reserved by the system!). These initialisers are called before others. */ #define W32_SEG_INIT_C_USER ".CRT$XIU" /* Declare macro for different initialisers sections */ /* Macro can be used several times to register several initialisers */ /* Once function is registered as initialiser, it will be called automatically during application startup */ #define W32_REG_INIT_EARLY(F) W32_VFPTR_IN_SEG (W32_SEG_INIT_EARLY,F) #define W32_REG_INIT_LATE(F) W32_VFPTR_IN_SEG (W32_SEG_INIT_LATE,F) /* Not recommended / unsafe */ /* "lib" initialisers are called before "user" initialisers */ /* "C" initialisers are called before "C++" initialisers */ #define W32_REG_INIT_C_USER(F) W32_FPTR_IN_SEG (W32_SEG_INIT_C_USER,F) #define W32_REG_INIT_C_LIB(F) W32_FPTR_IN_SEG (W32_SEG_INIT_C_LIB,F) #define W32_REG_INIT_CXX_USER(F) W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_USER,F) #define W32_REG_INIT_CXX_LIB(F) W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_LIB,F) /* Choose main register macro based on language and program type */ /* Assuming that _LIB or _USRDLL is defined for static or DLL-library */ /* Macro can be used several times to register several initialisers */ /* Once function is registered as initialiser, it will be called automatically during application startup */ /* Define AUTOINIT_FUNCS_FORCE_EARLY_INIT to force register as early initialiser */ /* Define AUTOINIT_FUNCS_FORCE_LATE_INIT to force register as late initialiser */ /* By default C++ static or DLL-library code and any C code and will be registered as early initialiser, while C++ non-library code will be registered as late initialiser */ #if (! defined(__cplusplus) || \ ((defined(_LIB) && ! defined(_CONSOLE)) || defined(_USRDLL)) || \ defined(AUTOINIT_FUNCS_FORCE_EARLY_INIT)) && \ ! defined(AUTOINIT_FUNCS_FORCE_LATE_INIT) #define W32_REGISTER_INIT(F) W32_REG_INIT_EARLY(F) #else #define W32_REGISTER_INIT(F) W32_REG_INIT_LATE(F) #endif #endif /* ! _USRDLL || ! AUTOINIT_FUNCS_DECLARE_STATIC_REG || AUTOINIT_FUNCS_FORCE_STATIC_REG */ #if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG) #include /* required for atexit() */ #define W32_SET_INIT_AND_DEINIT(FI,FD) \ void __cdecl _W32_init_helper_ ## FI (void); \ void __cdecl _W32_deinit_helper_ ## FD (void); \ void __cdecl _W32_init_helper_ ## FI (void) \ { (void) (FI) (); atexit (_W32_deinit_helper_ ## FD); } \ void __cdecl _W32_deinit_helper_ ## FD (void) \ { (void) (FD) (); } \ W32_REGISTER_INIT (_W32_init_helper_ ## FI) #else /* _USRDLL */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* WIN32_LEAN_AND_MEAN */ #include /* Required for DllMain */ /* If DllMain is already present in code, define AUTOINIT_FUNCS_CALL_USR_DLLMAIN and rename DllMain to usr_DllMain */ #ifndef AUTOINIT_FUNCS_CALL_USR_DLLMAIN #define W32_SET_INIT_AND_DEINIT(FI,FD) \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused) \ { (void) hinst; (void) unused; \ if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \ else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \ return TRUE; \ } struct _W32_dummy_strc_ ## FI {int i;} #else /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */ #define W32_SET_INIT_AND_DEINIT(FI,FD) \ BOOL WINAPI usr_DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused) \ { if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \ else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \ return usr_DllMain (hinst,reason,unused); \ } struct _W32_dummy_strc_ ## FI {int i;} #endif /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */ #endif /* _USRDLL */ #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) W32_SET_INIT_AND_DEINIT (FI,FD) /* Indicate that automatic initialisers/deinitialisers are supported */ #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1 #else /* !__GNUC__ && !_MSC_FULL_VER */ /* Define EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED before inclusion of header to abort compilation if automatic initialisers/deinitialisers are not supported */ #ifdef EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED #error \ Compiler/platform does not support automatic calls of user-defined initializer and deinitializer #endif /* EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED */ /* Do nothing */ #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) /* Indicate that automatic initialisers/deinitialisers are not supported */ #define _AUTOINIT_FUNCS_ARE_NOT_SUPPORTED 1 #endif /* !__GNUC__ && !_MSC_FULL_VER */ #endif /* !AUTOINIT_FUNCS_INCLUDED */ libmicrohttpd-1.0.2/src/include/microhttpd2.h0000644000175000017500000041454715035214301016132 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2006-2018 Christian Grothoff, Karlson2k (Evgeny Grin) (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Just includes the NEW definitions for the NG-API. * Note that we do not indicate which of the OLD APIs * simply need to be kept vs. deprecated. * * * The goal is to provide a basis for discussion! * Little of this is implemented yet. * * Main goals: * - simplify application callbacks by splitting header/upload/post * functionality currently provided by calling the same * MHD_AccessHandlerCallback 3+ times into separate callbacks. * - keep the API very simple for simple requests, but allow * more complex logic to be incrementally introduced * (via new struct MHD_Action construction) * - avoid repeated scans for URL matches via the new * struct MHD_Action construction * - provide default logarithmic implementation of URL scan * => reduce strcmp(url) from >= 3n operations to "log n" * per request. * - better types, in particular avoid varargs for options * - make it harder to pass inconsistent options * - combine options and flags into more uniform API (at least * exterally!) * - simplify API use by using sane defaults (benefiting from * breaking backwards compatibility) and making all options * really optional, and where applicable avoid having options * where the default works if nothing is specified * - simplify API by moving rarely used http_version into * MHD_request_get_information() * - avoid 'int' for MHD_YES/MHD_NO by introducing `enum MHD_Bool` * - improve terminology by eliminating confusion between * 'request' and 'connection' * - prepare API for having multiple TLS backends * - use more consistent prefixes for related functions * by using MHD_subject_verb_object naming convention, also * at the same time avoid symbol conflict with legacy names * (so we can have one binary implementing old and new * library API at the same time via compatibility layer). * - make it impossible to queue a response at the wrong time * - make it impossible to suspend a connection/request at the * wrong time (improves thread-safety) * - make it clear which response status codes are "properly" * supported (include the descriptive string) by using an enum; * - simplify API for common-case of one-shot responses by * eliminating need for destroy response in most cases; * * NEW-EG: * - avoid fixed types, like uint32_t. They may not exist on some * platforms. Instead use uint_fast32_t. * It is also better for future-proof. * - check portability for embedded platforms. Some of them support * 64 bits, but 'int' could be just 16 bits resulting of silently * dropping enum values higher than 65535. * => in general, more functions, fewer enums for setup * * - Avoid returning pointers to internal members. It is not thread-safe and * even in single thread the value could change over the time. Prefer pointers to * app-allocated memory with the size, like MHD_daemon_get_static_info(enum * MHD_enum_name info_type, void *buf, size_t buf_size). * => Except in cases where zero-copy matters. * * - Use separate app calls/functions for data the will not change for the * lifetime of the object and dynamic data. The only difference should be the * name. Like MHD_daemon_get_static_info(enum MHD_enum_name info_type, void *buf, * size_t buf_size) MHD_daemon_get_dynamic_info(enum MHD_enum_name info_type, * void *buf, size_t buf_size) Examples of static data: listen socket, number of * workers, daemon flags. Examples of dynamic data: number of connections, * quiesce status. It should give a clear idea whether the data could be changed * over the time (could be not obvious for some data) and thus may change the * approach how to use the data in app. The same for: library, daemon, * connection, request. Not sure that dynamic data makes sense for the library. * * - Use clear separation between connection and request. Do not mix the kind * data in the callbacks. Currently we are mixing things in * MHD_AccessHandlerCallback and MHD_RequestCompletedCallback. Instead of * pointers to struct MHD_Connection we should use pointers to (new) struct * MHD_Request. Probably some other functions are mixing the things as well, to * be re-checked. * * - Define default response code in response object. There are a very little * chance that response body designed for 404 or 403 codes will be used with * 200 code. However, the responses body for 307 and 308 could be the same. So: * * add default response code in response object. Use zero for default 200. * * When app sending the response use zero for response's default code or * use specific code to override response's default value. * * - Make responses unmodifiable after first use. It is not thread-safe. * MHD-generated headers (Date, Connection/Keep-Alive) are again * part of the *request* and do not count as part of the "response" here. * * - Remove "footers" from responses. With unmodifiable responses everything should be "headers". * Add footers to *requests* instead. * * - Add API for adding request-specific response headers and footers. To * simplify the things it should just copy the strings (to avoid dealing with * complicated deinit of possible dynamic strings). After this change it should * be possible to simplify DAuth handling as response could be reused (currently * 403 responses are modified for each reply). * * - Control response behaviour mainly by response flags, not by additional * headers (like MHD_RF_FORCE_CLOSE instead of "Connection: close"). * It is easier for both: app and MHD. * * - Move response codes from MHD_HTTP_xxx namespace to MHD_HTTP_CODE_xxx * namespace. It already may clash with other HTTP values. * * - plus other things that was discussed already, like avoiding extra calls * for body-less requests. I assume it should be resolved with fundamental * re-design of request/response cycle handling. * * - Internals: carefully check where locking is really required. Probably * separate locks. Check out-of-thread value reading. Currently code assumes * atomic reading of values used in other threads, which mostly true on x86, * but not OK on other arches. Probably use read/write locking to minimize * the threads interference. * * - figure out how to do portable variant of cork/uncork * * NEW-CG: * - Postprocessor is unusable night-mare when doing "stream processing" * for tiny values where the application basically has to copy together * the stream back into a single compact heap value, just making the * parsing highly more complicated (see examples in Challenger) * * - non-stream processing variant for request bodies, give apps a * way to request the full body in one buffer; give apps a way * to request a 'large new allocation' for such buffers; give apps * a way to specify a global quota for large allocations to ensure * memory usage has a hard bound * * - remove request data from memory pool when response is queued * (IF no callbacks and thus data cannot be used anymore, or IF * application permits explictly per daemon) to get more space * for building response; * * * TODO: * - varargs in upgrade is still there and ugly (and not even used!) * - migrate event loop apis (get fdset, timeout, MHD_run(), etc.) */ #ifndef MICROHTTPD2_H #define MICROHTTPD2_H #ifdef __cplusplus extern "C" { #if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif /* While we generally would like users to use a configure-driven build process which detects which headers are present and hence works on any platform, we use "standard" includes here to build out-of-the-box for beginning users on common systems. If generic headers don't work on your platform, include headers which define 'va_list', 'size_t', 'ssize_t', 'intptr_t', 'uint16_t', 'uint32_t', 'uint64_t', 'off_t', 'struct sockaddr', 'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before including "microhttpd.h". Then the following "standard" includes won't be used (which might be a good idea, especially on platforms where they do not exist). */ #ifndef MHD_PLATFORM_H #include #include #include #if defined(_WIN32) && ! defined(__CYGWIN__) #include #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #else #include #include #include #endif #endif #if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET) /* Do not define __USE_W32_SOCKETS under Cygwin! */ #error Cygwin with winsock fd_set is not supported #endif /** * Current version of the library. * 0x01093001 = 1.9.30-1. */ #define MHD_VERSION 0x01000000 /** * Representation of 'bool' in the public API as stdbool.h may not * always be available. */ enum MHD_Bool { /** * MHD-internal return code for "NO". */ MHD_NO = 0, /** * MHD-internal return code for "YES". All non-zero values * will be interpreted as "YES", but MHD will only ever * return #MHD_YES or #MHD_NO. */ MHD_YES = 1 }; /** * Constant used to indicate unknown size (use when * creating a response). */ #ifdef UINT64_MAX #define MHD_SIZE_UNKNOWN UINT64_MAX #else #define MHD_SIZE_UNKNOWN ((uint64_t) -1LL) #endif #ifdef SIZE_MAX #define MHD_CONTENT_READER_END_OF_STREAM SIZE_MAX #define MHD_CONTENT_READER_END_WITH_ERROR (SIZE_MAX - 1) #else #define MHD_CONTENT_READER_END_OF_STREAM ((size_t) -1LL) #define MHD_CONTENT_READER_END_WITH_ERROR (((size_t) -1LL) - 1) #endif #ifndef _MHD_EXTERN #if defined(_WIN32) && defined(MHD_W32LIB) #define _MHD_EXTERN extern #elif defined(_WIN32) && defined(MHD_W32DLL) /* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */ #define _MHD_EXTERN __declspec(dllimport) #else #define _MHD_EXTERN extern #endif #endif #ifndef MHD_SOCKET_DEFINED /** * MHD_socket is type for socket FDs */ #if ! defined(_WIN32) || defined(_SYS_TYPES_FD_SET) #define MHD_POSIX_SOCKETS 1 typedef int MHD_socket; #define MHD_INVALID_SOCKET (-1) #else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_WINSOCK_SOCKETS 1 #include typedef SOCKET MHD_socket; #define MHD_INVALID_SOCKET (INVALID_SOCKET) #endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_SOCKET_DEFINED 1 #endif /* MHD_SOCKET_DEFINED */ /** * Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages */ #ifdef MHD_NO_DEPRECATION #define _MHD_DEPR_MACRO(msg) #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* MHD_NO_DEPRECATION */ #ifndef _MHD_DEPR_MACRO #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1500 /* VS 2008 or later */ /* Stringify macros */ #define _MHD_INSTRMACRO(a) #a #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) /* deprecation message */ #define _MHD_DEPR_MACRO(msg) __pragma(message (__FILE__ "(" _MHD_STRMACRO ( \ __LINE__) "): warning: " msg)) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #elif defined(__clang__) || defined(__GNUC_PATCHLEVEL__) /* clang or GCC since 3.0 */ #define _MHD_GCC_PRAG(x) _Pragma(#x) #if (defined(__clang__) && (__clang_major__ + 0 >= 5 || \ (! defined(__apple_build_version__) && \ (__clang_major__ + 0 > 3 || (__clang_major__ + 0 == 3 && __clang_minor__ >= \ 3))))) || \ __GNUC__ + 0 > 4 || (__GNUC__ + 0 == 4 && __GNUC_MINOR__ + 0 >= 8) /* clang >= 3.3 (or XCode's clang >= 5.0) or GCC >= 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (GCC warning msg) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #else /* older clang or GCC */ /* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (message msg) #if (defined(__clang__) && (__clang_major__ + 0 > 2 || (__clang_major__ + 0 == \ 2 && __clang_minor__ >= \ 9))) /* FIXME: clang >= 2.9, earlier versions not tested */ /* clang handles inline pragmas better than GCC */ #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #endif /* clang >= 2.9 */ #endif /* older clang or GCC */ /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang || GCC >= 3.0 */ #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_MACRO #define _MHD_DEPR_MACRO(msg) #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_IN_MACRO #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #endif /* !_MHD_DEPR_IN_MACRO */ #ifndef _MHD_DEPR_FUNC #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1400 /* VS 2005 or later */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated (msg)) #elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1310 /* VS .NET 2003 deprecation do not support custom messages */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated) #elif (__GNUC__ + 0 >= 5) || (defined(__clang__) && \ (__clang_major__ + 0 > 2 || (__clang_major__ + 0 == 2 && __clang_minor__ >= \ 9))) /* FIXME: earlier versions not tested */ /* GCC >= 5.0 or clang >= 2.9 */ #define _MHD_DEPR_FUNC(msg) __attribute__((deprecated (msg))) #elif defined(__clang__) || __GNUC__ + 0 > 3 || (__GNUC__ + 0 == 3 && \ __GNUC_MINOR__ + 0 >= 1) /* 3.1 <= GCC < 5.0 or clang < 2.9 */ /* old GCC-style deprecation do not support custom messages */ #define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__)) /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang < 2.9 || GCC >= 3.1 */ #endif /* !_MHD_DEPR_FUNC */ #ifndef _MHD_DEPR_FUNC #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* !_MHD_DEPR_FUNC */ /* Define MHD_NONNULL attribute */ /** * Macro to indicate that certain parameters must be * non-null. Todo: port to non-gcc platforms. */ #if defined(__CYGWIN__) || defined(_WIN32) || defined(MHD_W32LIB) || \ defined(__clang__) || ! defined(__GNUC__) #define MHD_NONNULL(...) /* empty */ #else #define MHD_NONNULL(...) __THROW __nonnull ((__VA_ARGS__)) #endif /** * Not all architectures and `printf()`'s support the `long long` type. * This gives the ability to replace `long long` with just a `long`, * standard `int` or a `short`. */ #ifndef MHD_UNSIGNED_LONG_LONG #define MHD_UNSIGNED_LONG_LONG unsigned long long #endif /** * Format string for printing a variable of type #MHD_LONG_LONG. * You should only redefine this if you also define #MHD_LONG_LONG. */ #ifndef MHD_UNSIGNED_LONG_LONG_PRINTF #define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu" #endif /** * @brief Handle for a connection / HTTP request. * * With HTTP/1.1, multiple requests can be run over the same * connection. However, MHD will only show one request per TCP * connection to the client at any given time. * * Replaces `struct MHD_Connection`, renamed to better reflect * what this object truly represents to the application using * MHD. * * @ingroup request */ struct MHD_Request; /** * A connection corresponds to the network/stream abstraction. * A single network (i.e. TCP) stream may be used for multiple * requests, which in HTTP/1.1 must be processed sequentially. */ struct MHD_Connection; /** * Return values for reporting errors, also used * for logging. * * A value of 0 indicates success (as a return value). * Values between 0 and 10000 must be handled explicitly by the app. * Values from 10000-19999 are informational. * Values from 20000-29999 indicate successful operations. * Values from 30000-39999 indicate unsuccessful (normal) operations. * Values from 40000-49999 indicate client errors. * Values from 50000-59999 indicate MHD server errors. * Values from 60000-69999 indicate application errors. */ enum MHD_StatusCode { /* 00000-level status codes indicate return values the application must act on. */ /** * Successful operation (not used for logging). */ MHD_SC_OK = 0, /** * We were asked to return a timeout, but, there is no timeout. */ MHD_SC_NO_TIMEOUT = 1, /* 10000-level status codes indicate intermediate results of some kind. */ /** * Informational event, MHD started. */ MHD_SC_DAEMON_STARTED = 10000, /** * Informational event, we accepted a connection. */ MHD_SC_CONNECTION_ACCEPTED = 10001, /** * Informational event, thread processing connection termiantes. */ MHD_SC_THREAD_TERMINATING = 10002, /** * Informational event, state machine status for a connection. */ MHD_SC_STATE_MACHINE_STATUS_REPORT = 10003, /** * accept() returned transient error. */ MHD_SC_ACCEPT_FAILED_EAGAIN = 10004, /* 20000-level status codes indicate success of some kind. */ /** * MHD is closing a connection after the client closed it * (perfectly normal end). */ MHD_SC_CONNECTION_CLOSED = 20000, /** * MHD is closing a connection because the application * logic to generate the response data completed. */ MHD_SC_APPLICATION_DATA_GENERATION_FINISHED = 20001, /* 30000-level status codes indicate transient failures that might go away if the client tries again. */ /** * Resource limit in terms of number of parallel connections * hit. */ MHD_SC_LIMIT_CONNECTIONS_REACHED = 30000, /** * We failed to allocate memory for poll() syscall. * (May be transient.) */ MHD_SC_POLL_MALLOC_FAILURE = 30001, /** * The operation failed because the respective * daemon is already too deep inside of the shutdown * activity. */ MHD_SC_DAEMON_ALREADY_SHUTDOWN = 30002, /** * We failed to start a thread. */ MHD_SC_THREAD_LAUNCH_FAILURE = 30003, /** * The operation failed because we either have no * listen socket or were already quiesced. */ MHD_SC_DAEMON_ALREADY_QUIESCED = 30004, /** * The operation failed because client disconnected * faster than we could accept(). */ MHD_SC_ACCEPT_FAST_DISCONNECT = 30005, /** * Operating resource limits hit on accept(). */ MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED = 30006, /** * Connection was refused by accept policy callback. */ MHD_SC_ACCEPT_POLICY_REJECTED = 30007, /** * We failed to allocate memory for the connection. * (May be transient.) */ MHD_SC_CONNECTION_MALLOC_FAILURE = 30008, /** * We failed to allocate memory for the connection's memory pool. * (May be transient.) */ MHD_SC_POOL_MALLOC_FAILURE = 30009, /** * We failed to forward data from a Web socket to the * application to the remote side due to the socket * being closed prematurely. (May be transient.) */ MHD_SC_UPGRADE_FORWARD_INCOMPLETE = 30010, /** * We failed to allocate memory for generating the response from our * memory pool. Likely the request header was too large to leave * enough room. */ MHD_SC_CONNECTION_POOL_MALLOC_FAILURE = 30011, /* 40000-level errors are caused by the HTTP client (or the network) */ /** * MHD is closing a connection because parsing the * request failed. */ MHD_SC_CONNECTION_PARSE_FAIL_CLOSED = 40000, /** * MHD is closing a connection because it was reset. */ MHD_SC_CONNECTION_RESET_CLOSED = 40001, /** * MHD is closing a connection because reading the * request failed. */ MHD_SC_CONNECTION_READ_FAIL_CLOSED = 40002, /** * MHD is closing a connection because writing the response failed. */ MHD_SC_CONNECTION_WRITE_FAIL_CLOSED = 40003, /** * MHD is returning an error because the header provided * by the client is too big. */ MHD_SC_CLIENT_HEADER_TOO_BIG = 40004, /** * An HTTP/1.1 request was sent without the "Host:" header. */ MHD_SC_HOST_HEADER_MISSING = 40005, /** * The given content length was not a number. */ MHD_SC_CONTENT_LENGTH_MALFORMED = 40006, /** * The given uploaded, chunked-encoded body was malformed. */ MHD_SC_CHUNKED_ENCODING_MALFORMED = 40007, /* 50000-level errors are because of an error internal to the MHD logic, possibly including our interaction with the operating system (but not the application) */ /** * This build of MHD does not support TLS, but the application * requested TLS. */ MHD_SC_TLS_DISABLED = 50000, /** * The application attempted to setup TLS parameters before * enabling TLS. */ MHD_SC_TLS_BACKEND_UNINITIALIZED = 50003, /** * The selected TLS backend does not yet support this operation. */ MHD_SC_TLS_BACKEND_OPERATION_UNSUPPORTED = 50004, /** * Failed to setup ITC channel. */ MHD_SC_ITC_INITIALIZATION_FAILED = 50005, /** * File descriptor for ITC channel too large. */ MHD_SC_ITC_DESCRIPTOR_TOO_LARGE = 50006, /** * The specified value for the NC length is way too large * for this platform (integer overflow on `size_t`). */ MHD_SC_DIGEST_AUTH_NC_LENGTH_TOO_BIG = 50007, /** * We failed to allocate memory for the specified nonce * counter array. The option was not set. */ MHD_SC_DIGEST_AUTH_NC_ALLOCATION_FAILURE = 50008, /** * This build of the library does not support * digest authentication. */ MHD_SC_DIGEST_AUTH_NOT_SUPPORTED_BY_BUILD = 50009, /** * IPv6 requested but not supported by this build. */ MHD_SC_IPV6_NOT_SUPPORTED_BY_BUILD = 50010, /** * We failed to open the listen socket. Maybe the build * supports IPv6, but your kernel does not? */ MHD_SC_FAILED_TO_OPEN_LISTEN_SOCKET = 50011, /** * Specified address family is not supported by this build. */ MHD_SC_AF_NOT_SUPPORTED_BY_BUILD = 50012, /** * Failed to enable listen address reuse. */ MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED = 50013, /** * Enabling listen address reuse is not supported by this platform. */ MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_NOT_SUPPORTED = 50014, /** * Failed to disable listen address reuse. */ MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_FAILED = 50015, /** * Disabling listen address reuse is not supported by this platform. */ MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_NOT_SUPPORTED = 50016, /** * We failed to explicitly enable or disable dual stack for * the IPv6 listen socket. The socket will be used in whatever * the default is the OS gives us. */ MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_FAILED = 50017, /** * On this platform, MHD does not support explicitly configuring * dual stack behavior. */ MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_NOT_SUPPORTED = 50018, /** * Failed to enable TCP FAST OPEN option. */ MHD_SC_FAST_OPEN_FAILURE = 50020, /** * Failed to start listening on listen socket. */ MHD_SC_LISTEN_FAILURE = 50021, /** * Failed to obtain our listen port via introspection. */ MHD_SC_LISTEN_PORT_INTROSPECTION_FAILURE = 50022, /** * Failed to obtain our listen port via introspection * due to unsupported address family being used. */ MHD_SC_LISTEN_PORT_INTROSPECTION_UNKNOWN_AF = 50023, /** * We failed to set the listen socket to non-blocking. */ MHD_SC_LISTEN_SOCKET_NONBLOCKING_FAILURE = 50024, /** * Listen socket value is too large (for use with select()). */ MHD_SC_LISTEN_SOCKET_TOO_LARGE = 50025, /** * We failed to allocate memory for the thread pool. */ MHD_SC_THREAD_POOL_MALLOC_FAILURE = 50026, /** * We failed to allocate mutex for thread pool worker. */ MHD_SC_THREAD_POOL_CREATE_MUTEX_FAILURE = 50027, /** * There was an attempt to upgrade a connection on * a daemon where upgrades are disallowed. */ MHD_SC_UPGRADE_ON_DAEMON_WITH_UPGRADE_DISALLOWED = 50028, /** * Failed to signal via ITC channel. */ MHD_SC_ITC_USE_FAILED = 50029, /** * We failed to initialize the main thread for listening. */ MHD_SC_THREAD_MAIN_LAUNCH_FAILURE = 50030, /** * We failed to initialize the threads for the worker pool. */ MHD_SC_THREAD_POOL_LAUNCH_FAILURE = 50031, /** * We failed to add a socket to the epoll() set. */ MHD_SC_EPOLL_CTL_ADD_FAILED = 50032, /** * We failed to create control socket for the epoll(). */ MHD_SC_EPOLL_CTL_CREATE_FAILED = 50034, /** * We failed to configure control socket for the epoll() * to be non-inheritable. */ MHD_SC_EPOLL_CTL_CONFIGURE_NOINHERIT_FAILED = 50035, /** * We failed to build the FD set because a socket was * outside of the permitted range. */ MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE = 50036, /** * This daemon was not configured with options that * would allow us to build an FD set for select(). */ MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_FDSET = 50037, /** * This daemon was not configured with options that * would allow us to obtain a meaningful timeout. */ MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_TIMEOUT = 50038, /** * This daemon was not configured with options that * would allow us to run with select() data. */ MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_SELECT = 50039, /** * This daemon was not configured to run with an * external event loop. */ MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_EXTERNAL = 50040, /** * Encountered an unexpected event loop style * (should never happen). */ MHD_SC_CONFIGURATION_UNEXPECTED_ELS = 50041, /** * Encountered an unexpected error from select() * (should never happen). */ MHD_SC_UNEXPECTED_SELECT_ERROR = 50042, /** * poll() is not supported. */ MHD_SC_POLL_NOT_SUPPORTED = 50043, /** * Encountered an unexpected error from poll() * (should never happen). */ MHD_SC_UNEXPECTED_POLL_ERROR = 50044, /** * We failed to configure accepted socket * to not use a signal pipe. */ MHD_SC_ACCEPT_CONFIGURE_NOSIGPIPE_FAILED = 50045, /** * Encountered an unexpected error from epoll_wait() * (should never happen). */ MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR = 50046, /** * epoll file descriptor is invalid (strange) */ MHD_SC_EPOLL_FD_INVALID = 50047, /** * We failed to configure accepted socket * to be non-inheritable. */ MHD_SC_ACCEPT_CONFIGURE_NOINHERIT_FAILED = 50048, /** * We failed to configure accepted socket * to be non-blocking. */ MHD_SC_ACCEPT_CONFIGURE_NONBLOCKING_FAILED = 50049, /** * accept() returned non-transient error. */ MHD_SC_ACCEPT_FAILED_UNEXPECTEDLY = 50050, /** * Operating resource limits hit on accept() while * zero connections are active. Oopsie. */ MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED_INSTANTLY = 50051, /** * Failed to add IP address to per-IP counter for * some reason. */ MHD_SC_IP_COUNTER_FAILURE = 50052, /** * Application violated our API by calling shutdown * while having an upgrade connection still open. */ MHD_SC_SHUTDOWN_WITH_OPEN_UPGRADED_CONNECTION = 50053, /** * Due to an unexpected internal error with the * state machine, we closed the connection. */ MHD_SC_STATEMACHINE_FAILURE_CONNECTION_CLOSED = 50054, /** * Failed to allocate memory in connection's pool * to parse the cookie header. */ MHD_SC_COOKIE_POOL_ALLOCATION_FAILURE = 50055, /** * MHD failed to build the response header. */ MHD_SC_FAILED_RESPONSE_HEADER_GENERATION = 50056, /* 60000-level errors are because the application logic did something wrong or generated an error. */ /** * MHD does not support the requested combination of * EPOLL with thread-per-connection mode. */ MHD_SC_SYSCALL_THREAD_COMBINATION_INVALID = 60000, /** * MHD does not support quiescing if ITC was disabled * and threads are used. */ MHD_SC_SYSCALL_QUIESCE_REQUIRES_ITC = 60001, /** * We failed to bind the listen socket. */ MHD_SC_LISTEN_SOCKET_BIND_FAILED = 60002, /** * The application requested an unsupported TLS backend to be used. */ MHD_SC_TLS_BACKEND_UNSUPPORTED = 60003, /** * The application requested a TLS cipher suite which is not * supported by the selected backend. */ MHD_SC_TLS_CIPHERS_INVALID = 60004, /** * MHD is closing a connection because the application * logic to generate the response data failed. */ MHD_SC_APPLICATION_DATA_GENERATION_FAILURE_CLOSED = 60005, /** * MHD is closing a connection because the application * callback told it to do so. */ MHD_SC_APPLICATION_CALLBACK_FAILURE_CLOSED = 60006, /** * Application only partially processed upload and did * not suspend connection. This may result in a hung * connection. */ MHD_SC_APPLICATION_HUNG_CONNECTION = 60007, /** * Application only partially processed upload and did * not suspend connection and the read buffer was maxxed * out, so MHD closed the connection. */ MHD_SC_APPLICATION_HUNG_CONNECTION_CLOSED = 60008, }; /** * Actions are returned by the application to drive the request * handling of MHD. */ struct MHD_Action; /** * HTTP methods explicitly supported by MHD. Note that for * non-canonical methods, MHD will return #MHD_METHOD_UNKNOWN * and you can use #MHD_REQUEST_INFORMATION_HTTP_METHOD to get * the original string. * * However, applications must check for "#MHD_METHOD_UNKNOWN" *or* any * enum-value above those in this list, as future versions of MHD may * add additional methods (as per IANA registry), thus even if the API * returns "unknown" today, it may return a method-specific header in * the future! * * @defgroup methods HTTP methods * HTTP methods (as strings). * See: http://www.iana.org/assignments/http-methods/http-methods.xml * Registry Version 2015-05-19 * @{ */ enum MHD_Method { /** * Method did not match any of the methods given below. */ MHD_METHOD_UNKNOWN = 0, /** * "OPTIONS" method. * Safe. Idempotent. RFC7231, Section 4.3.7. */ MHD_METHOD_OPTIONS = 1, /** * "GET" method. * Safe. Idempotent. RFC7231, Section 4.3.1. */ MHD_METHOD_GET = 2, /** * "HEAD" method. * Safe. Idempotent. RFC7231, Section 4.3.2. */ MHD_METHOD_HEAD = 3, /** * "POST" method. * Not safe. Not idempotent. RFC7231, Section 4.3.3. */ MHD_METHOD_POST = 4, /** * "PUT" method. * Not safe. Idempotent. RFC7231, Section 4.3.4. */ MHD_METHOD_PUT = 5, /** * "DELETE" method. * Not safe. Idempotent. RFC7231, Section 4.3.5. */ MHD_METHOD_DELETE = 6, /** * "TRACE" method. */ MHD_METHOD_TRACE = 7, /** * "CONNECT" method. */ MHD_METHOD_CONNECT = 8, /** * "ACL" method. */ MHD_METHOD_ACL = 9, /** * "BASELINE-CONTROL" method. */ MHD_METHOD_BASELINE_CONTROL = 10, /** * "BIND" method. */ MHD_METHOD_BIND = 11, /** * "CHECKIN" method. */ MHD_METHOD_CHECKIN = 12, /** * "CHECKOUT" method. */ MHD_METHOD_CHECKOUT = 13, /** * "COPY" method. */ MHD_METHOD_COPY = 14, /** * "LABEL" method. */ MHD_METHOD_LABEL = 15, /** * "LINK" method. */ MHD_METHOD_LINK = 16, /** * "LOCK" method. */ MHD_METHOD_LOCK = 17, /** * "MERGE" method. */ MHD_METHOD_MERGE = 18, /** * "MKACTIVITY" method. */ MHD_METHOD_MKACTIVITY = 19, /** * "MKCOL" method. */ MHD_METHOD_MKCOL = 20, /** * "MKREDIRECTREF" method. */ MHD_METHOD_MKREDIRECTREF = 21, /** * "MKWORKSPACE" method. */ MHD_METHOD_MKWORKSPACE = 22, /** * "MOVE" method. */ MHD_METHOD_MOVE = 23, /** * "ORDERPATCH" method. */ MHD_METHOD_ORDERPATCH = 24, /** * "PATCH" method. */ MHD_METHOD_PATH = 25, /** * "PRI" method. */ MHD_METHOD_PRI = 26, /** * "PROPFIND" method. */ MHD_METHOD_PROPFIND = 27, /** * "PROPPATCH" method. */ MHD_METHOD_PROPPATCH = 28, /** * "REBIND" method. */ MHD_METHOD_REBIND = 29, /** * "REPORT" method. */ MHD_METHOD_REPORT = 30, /** * "SEARCH" method. */ MHD_METHOD_SEARCH = 31, /** * "UNBIND" method. */ MHD_METHOD_UNBIND = 32, /** * "UNCHECKOUT" method. */ MHD_METHOD_UNCHECKOUT = 33, /** * "UNLINK" method. */ MHD_METHOD_UNLINK = 34, /** * "UNLOCK" method. */ MHD_METHOD_UNLOCK = 35, /** * "UPDATE" method. */ MHD_METHOD_UPDATE = 36, /** * "UPDATEDIRECTREF" method. */ MHD_METHOD_UPDATEDIRECTREF = 37, /** * "VERSION-CONTROL" method. */ MHD_METHOD_VERSION_CONTROL = 38 /* For more, check: https://www.iana.org/assignments/http-methods/http-methods.xhtml */ }; /** @} */ /* end of group methods */ /** * @defgroup postenc HTTP POST encodings * See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 * @{ */ #define MHD_HTTP_POST_ENCODING_FORM_URLENCODED \ "application/x-www-form-urlencoded" #define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data" /** @} */ /* end of group postenc */ /** * @defgroup headers HTTP headers * These are the standard headers found in HTTP requests and responses. * See: http://www.iana.org/assignments/message-headers/message-headers.xml * Registry Version 2017-01-27 * @{ */ /* Main HTTP headers. */ /* Standard. RFC7231, Section 5.3.2 */ #define MHD_HTTP_HEADER_ACCEPT "Accept" /* Standard. RFC7231, Section 5.3.3 */ #define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset" /* Standard. RFC7231, Section 5.3.4; RFC7694, Section 3 */ #define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding" /* Standard. RFC7231, Section 5.3.5 */ #define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language" /* Standard. RFC7233, Section 2.3 */ #define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges" /* Standard. RFC7234, Section 5.1 */ #define MHD_HTTP_HEADER_AGE "Age" /* Standard. RFC7231, Section 7.4.1 */ #define MHD_HTTP_HEADER_ALLOW "Allow" /* Standard. RFC7235, Section 4.2 */ #define MHD_HTTP_HEADER_AUTHORIZATION "Authorization" /* Standard. RFC7234, Section 5.2 */ #define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control" /* Reserved. RFC7230, Section 8.1 */ #define MHD_HTTP_HEADER_CLOSE "Close" /* Standard. RFC7230, Section 6.1 */ #define MHD_HTTP_HEADER_CONNECTION "Connection" /* Standard. RFC7231, Section 3.1.2.2 */ #define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding" /* Standard. RFC7231, Section 3.1.3.2 */ #define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language" /* Standard. RFC7230, Section 3.3.2 */ #define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length" /* Standard. RFC7231, Section 3.1.4.2 */ #define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location" /* Standard. RFC7233, Section 4.2 */ #define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range" /* Standard. RFC7231, Section 3.1.1.5 */ #define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type" /* Standard. RFC7231, Section 7.1.1.2 */ #define MHD_HTTP_HEADER_DATE "Date" /* Standard. RFC7232, Section 2.3 */ #define MHD_HTTP_HEADER_ETAG "ETag" /* Standard. RFC7231, Section 5.1.1 */ #define MHD_HTTP_HEADER_EXPECT "Expect" /* Standard. RFC7234, Section 5.3 */ #define MHD_HTTP_HEADER_EXPIRES "Expires" /* Standard. RFC7231, Section 5.5.1 */ #define MHD_HTTP_HEADER_FROM "From" /* Standard. RFC7230, Section 5.4 */ #define MHD_HTTP_HEADER_HOST "Host" /* Standard. RFC7232, Section 3.1 */ #define MHD_HTTP_HEADER_IF_MATCH "If-Match" /* Standard. RFC7232, Section 3.3 */ #define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since" /* Standard. RFC7232, Section 3.2 */ #define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match" /* Standard. RFC7233, Section 3.2 */ #define MHD_HTTP_HEADER_IF_RANGE "If-Range" /* Standard. RFC7232, Section 3.4 */ #define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since" /* Standard. RFC7232, Section 2.2 */ #define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified" /* Standard. RFC7231, Section 7.1.2 */ #define MHD_HTTP_HEADER_LOCATION "Location" /* Standard. RFC7231, Section 5.1.2 */ #define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards" /* Standard. RFC7231, Appendix A.1 */ #define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version" /* Standard. RFC7234, Section 5.4 */ #define MHD_HTTP_HEADER_PRAGMA "Pragma" /* Standard. RFC7235, Section 4.3 */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate" /* Standard. RFC7235, Section 4.4 */ #define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization" /* Standard. RFC7233, Section 3.1 */ #define MHD_HTTP_HEADER_RANGE "Range" /* Standard. RFC7231, Section 5.5.2 */ #define MHD_HTTP_HEADER_REFERER "Referer" /* Standard. RFC7231, Section 7.1.3 */ #define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After" /* Standard. RFC7231, Section 7.4.2 */ #define MHD_HTTP_HEADER_SERVER "Server" /* Standard. RFC7230, Section 4.3 */ #define MHD_HTTP_HEADER_TE "TE" /* Standard. RFC7230, Section 4.4 */ #define MHD_HTTP_HEADER_TRAILER "Trailer" /* Standard. RFC7230, Section 3.3.1 */ #define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" /* Standard. RFC7230, Section 6.7 */ #define MHD_HTTP_HEADER_UPGRADE "Upgrade" /* Standard. RFC7231, Section 5.5.3 */ #define MHD_HTTP_HEADER_USER_AGENT "User-Agent" /* Standard. RFC7231, Section 7.1.4 */ #define MHD_HTTP_HEADER_VARY "Vary" /* Standard. RFC7230, Section 5.7.1 */ #define MHD_HTTP_HEADER_VIA "Via" /* Standard. RFC7235, Section 4.1 */ #define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate" /* Standard. RFC7234, Section 5.5 */ #define MHD_HTTP_HEADER_WARNING "Warning" /* Additional HTTP headers. */ /* No category. RFC4229 */ #define MHD_HTTP_HEADER_A_IM "A-IM" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions" /* Informational. RFC7089 */ #define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features" /* No category. RFC5789 */ #define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch" /* Standard. RFC7639, Section 2 */ #define MHD_HTTP_HEADER_ALPN "ALPN" /* Standard. RFC7838 */ #define MHD_HTTP_HEADER_ALT_SVC "Alt-Svc" /* Standard. RFC7838 */ #define MHD_HTTP_HEADER_ALT_USED "Alt-Used" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_ALTERNATES "Alternates" /* No category. RFC4437 */ #define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref" /* Experimental. RFC8053, Section 4 */ #define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control" /* Standard. RFC7615, Section 3 */ #define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_C_EXT "C-Ext" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_C_MAN "C-Man" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_C_OPT "C-Opt" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_C_PEP "C-PEP" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_C_PEP_INFO "C-PEP-Info" /* Standard. RFC7809, Section 7.1 */ #define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones" /* Obsoleted. RFC2068; RFC2616 */ #define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base" /* Standard. RFC6266 */ #define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_ID "Content-ID" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version" /* Standard. RFC6265 */ #define MHD_HTTP_HEADER_COOKIE "Cookie" /* Obsoleted. RFC2965; RFC6265 */ #define MHD_HTTP_HEADER_COOKIE2 "Cookie2" /* Standard. RFC5323 */ #define MHD_HTTP_HEADER_DASL "DASL" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_DAV "DAV" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_DELTA_BASE "Delta-Base" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_DEPTH "Depth" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_DESTINATION "Destination" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_DIGEST "Digest" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_EXT "Ext" /* Standard. RFC7239 */ #define MHD_HTTP_HEADER_FORWARDED "Forwarded" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_GETPROFILE "GetProfile" /* Experimental. RFC7486, Section 6.1.1 */ #define MHD_HTTP_HEADER_HOBAREG "Hobareg" /* Standard. RFC7540, Section 3.2.1 */ #define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_IM "IM" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_IF "If" /* Standard. RFC6638 */ #define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_KEEP_ALIVE "Keep-Alive" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_LABEL "Label" /* No category. RFC5988 */ #define MHD_HTTP_HEADER_LINK "Link" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_LOCK_TOKEN "Lock-Token" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_MAN "Man" /* Informational. RFC7089 */ #define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_METER "Meter" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_NEGOTIATE "Negotiate" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_OPT "Opt" /* Experimental. RFC8053, Section 3 */ #define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate" /* Standard. RFC4229 */ #define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type" /* Standard. RFC6454 */ #define MHD_HTTP_HEADER_ORIGIN "Origin" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_OVERWRITE "Overwrite" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_P3P "P3P" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PEP "PEP" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PICS_LABEL "PICS-Label" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PEP_INFO "Pep-Info" /* Standard. RFC4229 */ #define MHD_HTTP_HEADER_POSITION "Position" /* Standard. RFC7240 */ #define MHD_HTTP_HEADER_PREFER "Prefer" /* Standard. RFC7240 */ #define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROTOCOL "Protocol" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request" /* Standard. RFC7615, Section 4 */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_PUBLIC "Public" /* Standard. RFC7469 */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins" /* Standard. RFC7469 */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY \ "Public-Key-Pins-Report-Only" /* No category. RFC4437 */ #define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SAFE "Safe" /* Standard. RFC6638 */ #define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply" /* Standard. RFC6638 */ #define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag" /* Standard. RFC6455 */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept" /* Standard. RFC6455 */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions" /* Standard. RFC6455 */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key" /* Standard. RFC6455 */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol" /* Standard. RFC6455 */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme" /* Standard. RFC6265 */ #define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie" /* Obsoleted. RFC2965; RFC6265 */ #define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SETPROFILE "SetProfile" /* Standard. RFC5023 */ #define MHD_HTTP_HEADER_SLUG "SLUG" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SOAPACTION "SoapAction" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_STATUS_URI "Status-URI" /* Standard. RFC6797 */ #define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_TCN "TCN" /* Standard. RFC4918 */ #define MHD_HTTP_HEADER_TIMEOUT "Timeout" /* Standard. RFC8030, Section 5.4 */ #define MHD_HTTP_HEADER_TOPIC "Topic" /* Standard. RFC8030, Section 5.2 */ #define MHD_HTTP_HEADER_TTL "TTL" /* Standard. RFC8030, Section 5.3 */ #define MHD_HTTP_HEADER_URGENCY "Urgency" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_URI "URI" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary" /* No category. RFC4229 */ #define MHD_HTTP_HEADER_WANT_DIGEST "Want-Digest" /* Informational. RFC7034 */ #define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options" /* Some provisional headers. */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \ "Access-Control-Allow-Origin" /** @} */ /* end of group headers */ /** * A client has requested the given url using the given method * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc). The callback * must initialize @a rhp to provide further callbacks which will * process the request further and ultimately to provide the response * to give back to the client, or return #MHD_NO. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param url the requested url (without arguments after "?") * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @return action how to proceed, NULL * if the socket must be closed due to a serious * error while handling the request */ typedef const struct MHD_Action * (*MHD_RequestCallback) (void *cls, struct MHD_Request *request, const char *url, enum MHD_Method method); /** * Create (but do not yet start) an MHD daemon. * Usually, you will want to set various options before * starting the daemon with #MHD_daemon_start(). * * @param cb function to be called for incoming requests * @param cb_cls closure for @a cb * @return NULL on error */ _MHD_EXTERN struct MHD_Daemon * MHD_daemon_create (MHD_RequestCallback cb, void *cb_cls) MHD_NONNULL (1); /** * Start a webserver. * * @param daemon daemon to start; you can no longer set * options on this daemon after this call! * @return #MHD_SC_OK on success * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_start (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Stop accepting connections from the listening socket. Allows * clients to continue processing, but stops accepting new * connections. Note that the caller is responsible for closing the * returned socket; however, if MHD is run using threads (anything but * external select mode), it must not be closed until AFTER * #MHD_stop_daemon has been called (as it is theoretically possible * that an existing thread is still using it). * * Note that some thread modes require the caller to have passed * #MHD_USE_ITC when using this API. If this daemon is * in one of those modes and this option was not given to * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. * * @param daemon daemon to stop accepting new connections for * @return old listen socket on success, #MHD_INVALID_SOCKET if * the daemon was already not listening anymore, or * was never started * @ingroup specialized */ _MHD_EXTERN MHD_socket MHD_daemon_quiesce (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Shutdown and destroy an HTTP daemon. * * @param daemon daemon to stop * @ingroup event */ _MHD_EXTERN void MHD_daemon_destroy (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Add another client connection to the set of connections managed by * MHD. This API is usually not needed (since MHD will accept inbound * connections on the server socket). Use this API in special cases, * for example if your HTTP server is behind NAT and needs to connect * out to the HTTP client, or if you are building a proxy. * * If you use this API in conjunction with a internal select or a * thread pool, you must set the option #MHD_USE_ITC to ensure that * the freshly added connection is immediately processed by MHD. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @return #MHD_SC_OK on success * The socket will be closed in any case; `errno` is * set to indicate further details about the error. * @ingroup specialized */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen) MHD_NONNULL (1); /** * Obtain the `select()` sets for this daemon. Daemon's FDs will be * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO * for each fd_set before calling this function. FD_SETSIZE is assumed * to be platform's default. * * This function should only be called in when MHD is configured to * use external select with 'select()' or with 'epoll'. In the latter * case, it will only add the single 'epoll()' file descriptor used by * MHD to the sets. It's necessary to use #MHD_get_timeout() in * combination with this function. * * This function must be called only for daemon started without * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_SC_OK on success, otherwise error code * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_get_fdset (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd) MHD_NONNULL (1,2,3,4); /** * Obtain the `select()` sets for this daemon. Daemon's FDs will be * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO * for each fd_set before calling this function. * * Passing custom FD_SETSIZE as @a fd_setsize allow usage of * larger/smaller than platform's default fd_sets. * * This function should only be called in when MHD is configured to * use external select with 'select()' or with 'epoll'. In the latter * case, it will only add the single 'epoll' file descriptor used by * MHD to the sets. It's necessary to use #MHD_get_timeout() in * combination with this function. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_SC_OK on success, otherwise error code * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize) MHD_NONNULL (1,2,3,4); /** * Obtain the `select()` sets for this daemon. Daemon's FDs will be * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO * for each fd_set before calling this function. Size of fd_set is * determined by current value of FD_SETSIZE. It's necessary to use * #MHD_get_timeout() in combination with this function. * * This function could be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ #define MHD_daemon_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set, \ max_fd) \ MHD_get_fdset2 ((daemon),(read_fd_set),(write_fd_set),(except_fd_set), \ (max_fd),FD_SETSIZE) /** * Obtain timeout value for polling function for this daemon. * This function set value to amount of milliseconds for which polling * function (`select()` or `poll()`) should at most block, not the * timeout value set for connections. * It is important to always use this function, even if connection * timeout is not set, as in some cases MHD may already have more * data to process on next turn (data pending in TLS buffers, * connections are already ready with epoll etc.) and returned timeout * will be zero. * * @param daemon daemon to query for timeout * @param timeout set to the timeout (in milliseconds) * @return #MHD_SC_OK on success, #MHD_SC_NO_TIMEOUT if timeouts are * not used (or no connections exist that would * necessitate the use of a timeout right now), otherwise * an error code * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_get_timeout (struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout) MHD_NONNULL (1,2); /** * Run webserver operations (without blocking unless in client * callbacks). This method should be called by clients in combination * with #MHD_get_fdset if the client-controlled select method is used * and #MHD_get_timeout(). * * This function is a convenience method, which is useful if the * fd_sets from #MHD_get_fdset were not directly passed to `select()`; * with this function, MHD will internally do the appropriate `select()` * call itself again. While it is always safe to call #MHD_run (if * #MHD_USE_INTERNAL_POLLING_THREAD is not set), you should call * #MHD_run_from_select if performance is important (as it saves an * expensive call to `select()`). * * @param daemon daemon to run * @return #MHD_SC_OK on success * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_run (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * * You can use this function instead of #MHD_run if you called * `select()` on the result from #MHD_get_fdset. File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run is more efficient as MHD will not * have to call `select()` again to determine which operations are * ready. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @return #MHD_SC_OK on success * @ingroup event */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) MHD_NONNULL (1,2,3,4); /* ********************* daemon options ************** */ /** * Type of a callback function used for logging by MHD. * * @param cls closure * @param sc status code of the event * @param fm format string (`printf()`-style) * @param ap arguments to @a fm * @ingroup logging */ typedef void (*MHD_LoggingCallback)(void *cls, enum MHD_StatusCode sc, const char *fm, va_list ap); /** * Set logging method. Specify NULL to disable logging entirely. By * default (if this option is not given), we log error messages to * stderr. * * @param daemon which instance to setup logging for * @param logger function to invoke * @param logger_cls closure for @a logger */ _MHD_EXTERN void MHD_daemon_set_logger (struct MHD_Daemon *daemon, MHD_LoggingCallback logger, void *logger_cls) MHD_NONNULL (1); /** * Convenience macro used to disable logging. * * @param daemon which instance to disable logging for */ #define MHD_daemon_disable_logging(daemon) MHD_daemon_set_logger (daemon, NULL, \ NULL) /** * Suppress use of "Date" header as this system has no RTC. * * @param daemon which instance to disable clock for. */ _MHD_EXTERN void MHD_daemon_suppress_date_no_clock (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Disable use of inter-thread communication channel. * #MHD_daemon_disable_itc() can be used with * #MHD_daemon_thread_internal() to perform some additional * optimizations (in particular, not creating a pipe for IPC * signalling). If it is used, certain functions like * #MHD_daemon_quiesce() or #MHD_connection_add() or * #MHD_action_suspend() cannot be used anymore. * #MHD_daemon_disable_itc() is not beneficial on platforms where * select()/poll()/other signal shutdown() of a listen socket. * * You should only use this function if you are sure you do * satisfy all of its requirements and need a generally minor * boost in performance. * * @param daemon which instance to disable itc for */ _MHD_EXTERN void MHD_daemon_disable_itc (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Enable `turbo`. Disables certain calls to `shutdown()`, * enables aggressive non-blocking optimistic reads and * other potentially unsafe optimizations. * Most effects only happen with #MHD_ELS_EPOLL. * * @param daemon which instance to enable turbo for */ _MHD_EXTERN void MHD_daemon_enable_turbo (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Disable #MHD_action_suspend() functionality. * * You should only use this function if you are sure you do * satisfy all of its requirements and need a generally minor * boost in performance. * * @param daemon which instance to disable suspend for */ _MHD_EXTERN void MHD_daemon_disallow_suspend_resume (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * You need to set this option if you want to disable use of HTTP "Upgrade". * "Upgrade" may require usage of additional internal resources, * which we can avoid providing if they will not be used. * * You should only use this function if you are sure you do * satisfy all of its requirements and need a generally minor * boost in performance. * * @param daemon which instance to enable suspend/resume for */ _MHD_EXTERN void MHD_daemon_disallow_upgrade (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Possible levels of enforcement for TCP_FASTOPEN. */ enum MHD_FastOpenMethod { /** * Disable use of TCP_FASTOPEN. */ MHD_FOM_DISABLE = -1, /** * Enable TCP_FASTOPEN where supported (Linux with a kernel >= 3.6). * This is the default. */ MHD_FOM_AUTO = 0, /** * If TCP_FASTOPEN is not available, return #MHD_NO. * Also causes #MHD_daemon_start() to fail if setting * the option fails later. */ MHD_FOM_REQUIRE = 1 }; /** * Configure TCP_FASTOPEN option, including setting a * custom @a queue_length. * * Note that having a larger queue size can cause resource exhaustion * attack as the TCP stack has to now allocate resources for the SYN * packet along with its DATA. * * @param daemon which instance to configure TCP_FASTOPEN for * @param fom under which conditions should we use TCP_FASTOPEN? * @param queue_length queue length to use, default is 50 if this * option is never given. * @return #MHD_YES upon success, #MHD_NO if #MHD_FOM_REQUIRE was * given, but TCP_FASTOPEN is not available on the platform */ _MHD_EXTERN enum MHD_Bool MHD_daemon_tcp_fastopen (struct MHD_Daemon *daemon, enum MHD_FastOpenMethod fom, unsigned int queue_length) MHD_NONNULL (1); /** * Address family to be used by MHD. */ enum MHD_AddressFamily { /** * Option not given, do not listen at all * (unless listen socket or address specified by * other means). */ MHD_AF_NONE = 0, /** * Pick "best" available method automatically. */ MHD_AF_AUTO, /** * Use IPv4. */ MHD_AF_INET4, /** * Use IPv6. */ MHD_AF_INET6, /** * Use dual stack. */ MHD_AF_DUAL }; /** * Bind to the given TCP port and address family. * * Ineffective in conjunction with #MHD_daemon_listen_socket(). * Ineffective in conjunction with #MHD_daemon_bind_sa(). * * If neither this option nor the other two mentioned above * is specified, MHD will simply not listen on any socket! * * @param daemon which instance to configure the TCP port for * @param af address family to use * @param port port to use, 0 to bind to a random (free) port */ _MHD_EXTERN void MHD_daemon_bind_port (struct MHD_Daemon *daemon, enum MHD_AddressFamily af, uint16_t port) MHD_NONNULL (1); /** * Bind to the given socket address. * Ineffective in conjunction with #MHD_daemon_listen_socket(). * * @param daemon which instance to configure the binding address for * @param sa address to bind to; can be IPv4 (AF_INET), IPv6 (AF_INET6) * or even a UNIX domain socket (AF_UNIX) * @param sa_len number of bytes in @a sa */ _MHD_EXTERN void MHD_daemon_bind_socket_address (struct MHD_Daemon *daemon, const struct sockaddr *sa, size_t sa_len) MHD_NONNULL (1); /** * Use the given backlog for the listen() call. * Ineffective in conjunction with #MHD_daemon_listen_socket(). * * @param daemon which instance to configure the backlog for * @param listen_backlog backlog to use */ _MHD_EXTERN void MHD_daemon_listen_backlog (struct MHD_Daemon *daemon, int listen_backlog) MHD_NONNULL (1); /** * If present true, allow reusing address:port socket (by using * SO_REUSEPORT on most platform, or platform-specific ways). If * present and set to false, disallow reusing address:port socket * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on * Windows). * Ineffective in conjunction with #MHD_daemon_listen_socket(). * * @param daemon daemon to configure address reuse for */ _MHD_EXTERN void MHD_daemon_listen_allow_address_reuse (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Accept connections from the given socket. Socket * must be a TCP or UNIX domain (stream) socket. * * Unless -1 is given, this disables other listen options, including * #MHD_daemon_bind_sa(), #MHD_daemon_bind_port(), * #MHD_daemon_listen_queue() and * #MHD_daemon_listen_allow_address_reuse(). * * @param daemon daemon to set listen socket for * @param listen_socket listen socket to use, * MHD_INVALID_SOCKET value will cause this call to be * ignored (other binding options may still be effective) */ _MHD_EXTERN void MHD_daemon_listen_socket (struct MHD_Daemon *daemon, MHD_socket listen_socket) MHD_NONNULL (1); /** * Event loop syscalls supported by MHD. */ enum MHD_EventLoopSyscall { /** * Automatic selection of best-available method. This is also the * default. */ MHD_ELS_AUTO = 0, /** * Use select(). */ MHD_ELS_SELECT = 1, /** * Use poll(). */ MHD_ELS_POLL = 2, /** * Use epoll(). */ MHD_ELS_EPOLL = 3 }; /** * Force use of a particular event loop system call. * * @param daemon daemon to set event loop style for * @param els event loop syscall to use * @return #MHD_NO on failure, #MHD_YES on success */ _MHD_EXTERN enum MHD_Bool MHD_daemon_event_loop (struct MHD_Daemon *daemon, enum MHD_EventLoopSyscall els) MHD_NONNULL (1); /** * Protocol strictness enforced by MHD on clients. */ enum MHD_ProtocolStrictLevel { /** * Be particularly permissive about the protocol, allowing slight * deviations that are technically not allowed by the * RFC. Specifically, at the moment, this flag causes MHD to allow * spaces in header field names. This is disallowed by the standard. * It is not recommended to set this value on publicly available * servers as it may potentially lower level of protection. */ MHD_PSL_PERMISSIVE = -1, /** * Sane level of protocol enforcement for production use. */ MHD_PSL_DEFAULT = 0, /** * Be strict about the protocol (as opposed to as tolerant as * possible). Specifically, at the moment, this flag causes MHD to * reject HTTP 1.1 connections without a "Host" header. This is * required by the standard, but of course in violation of the "be * as liberal as possible in what you accept" norm. It is * recommended to set this if you are testing clients against * MHD, and to use default in production. */ MHD_PSL_STRICT = 1 }; /** * Set how strictly MHD will enforce the HTTP protocol. * * @param daemon daemon to configure strictness for * @param sl how strict should we be */ _MHD_EXTERN void MHD_daemon_protocol_strict_level (struct MHD_Daemon *daemon, enum MHD_ProtocolStrictLevel sl) MHD_NONNULL (1); /** * Use SHOUTcast. This will cause the response to begin * with the SHOUTcast "ICY" line instead of "HTTP". * * @param daemon daemon to set SHOUTcast option for */ _MHD_EXTERN void MHD_daemon_enable_shoutcast (struct MHD_Daemon *daemon) MHD_NONNULL (1); /** * Enable and configure TLS. * * @param daemon which instance should be configured * @param tls_backend which TLS backend should be used, * currently only "gnutls" is supported. You can * also specify NULL for best-available (which is the default). * @param ciphers which ciphers should be used by TLS, default is * "NORMAL" * @return status code, #MHD_SC_OK upon success * #MHD_TLS_BACKEND_UNSUPPORTED if the @a backend is unknown * #MHD_TLS_DISABLED if this build of MHD does not support TLS * #MHD_TLS_CIPHERS_INVALID if the given @a ciphers are not supported * by this backend */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_set_tls_backend (struct MHD_Daemon *daemon, const char *tls_backend, const char *ciphers) MHD_NONNULL (1); /** * Provide TLS key and certificate data in-memory. * * @param daemon which instance should be configured * @param mem_key private key (key.pem) to be used by the * HTTPS daemon. Must be the actual data in-memory, not a filename. * @param mem_cert certificate (cert.pem) to be used by the * HTTPS daemon. Must be the actual data in-memory, not a filename. * @param pass passphrase phrase to decrypt 'key.pem', NULL * if @param mem_key is in cleartext already * @return #MHD_SC_OK upon success; TODO: define failure modes */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_tls_key_and_cert_from_memory (struct MHD_Daemon *daemon, const char *mem_key, const char *mem_cert, const char *pass) MHD_NONNULL (1,2,3); /** * Configure DH parameters (dh.pem) to use for the TLS key * exchange. * * @param daemon daemon to configure tls for * @param dh parameters to use * @return #MHD_SC_OK upon success; TODO: define failure modes */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_tls_mem_dhparams (struct MHD_Daemon *daemon, const char *dh) MHD_NONNULL (1); /** * Function called to lookup the pre shared key (@a psk) for a given * HTTP connection based on the @a username. * * @param cls closure * @param connection the HTTPS connection * @param username the user name claimed by the other side * @param[out] psk to be set to the pre-shared-key; should be allocated with malloc(), * will be freed by MHD * @param[out] psk_size to be set to the number of bytes in @a psk * @return 0 on success, -1 on errors */ typedef int (*MHD_PskServerCredentialsCallback)(void *cls, const struct MHD_Connection *connection, const char *username, void **psk, size_t *psk_size); /** * Configure PSK to use for the TLS key exchange. * * @param daemon daemon to configure tls for * @param psk_cb function to call to obtain pre-shared key * @param psk_cb_cls closure for @a psk_cb * @return #MHD_SC_OK upon success; TODO: define failure modes */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_set_tls_psk_callback (struct MHD_Daemon *daemon, MHD_PskServerCredentialsCallback psk_cb, void *psk_cb_cls) MHD_NONNULL (1); /** * Memory pointer for the certificate (ca.pem) to be used by the * HTTPS daemon for client authentication. * * @param daemon daemon to configure tls for * @param mem_trust memory pointer to the certificate * @return #MHD_SC_OK upon success; TODO: define failure modes */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_tls_mem_trust (struct MHD_Daemon *daemon, const char *mem_trust) MHD_NONNULL (1); /** * Configure daemon credentials type for GnuTLS. * * @param gnutls_credentials must be a value of * type `gnutls_credentials_type_t` * @return #MHD_SC_OK upon success; TODO: define failure modes */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_gnutls_credentials (struct MHD_Daemon *daemon, int gnutls_credentials) MHD_NONNULL (1); /** * Provide TLS key and certificate data via callback. * * Use a callback to determine which X.509 certificate should be used * for a given HTTPS connection. This option provides an alternative * to #MHD_daemon_tls_key_and_cert_from_memory(). You must use this * version if multiple domains are to be hosted at the same IP address * using TLS's Server Name Indication (SNI) extension. In this case, * the callback is expected to select the correct certificate based on * the SNI information provided. The callback is expected to access * the SNI data using `gnutls_server_name_get()`. Using this option * requires GnuTLS 3.0 or higher. * * @param daemon daemon to configure callback for * @param cb must be of type `gnutls_certificate_retrieve_function2 *`. * @return #MHD_SC_OK on success */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_gnutls_key_and_cert_from_callback (struct MHD_Daemon *daemon, void *cb) MHD_NONNULL (1); /** * Which threading mode should be used by MHD? */ enum MHD_ThreadingMode { /** * MHD should create its own thread for listening and furthermore * create another thread per connection to handle requests. Use * this if handling requests is CPU-intensive or blocking, your * application is thread-safe and you have plenty of memory (per * request). */ MHD_TM_THREAD_PER_CONNECTION = -1, /** * Use an external event loop. This is the default. */ MHD_TM_EXTERNAL_EVENT_LOOP = 0, /** * Run with one or more worker threads. Any positive value * means that MHD should start that number of worker threads * (so > 1 is a thread pool) and distributed processing of * requests among the workers. * * A good way to express the use of a thread pool * in your code would be to write "MHD_TM_THREAD_POOL(4)" * to indicate four threads. * * If a positive value is set, * #MHD_daemon_run() and * #MHD_daemon_run_from_select() cannot be used. */ MHD_TM_WORKER_THREADS = 1 }; /** * Use a thread pool of size @a n. * * @return an `enum MHD_ThreadingMode` for a thread pool of size @a n */ #define MHD_TM_THREAD_POOL(n) ((enum MHD_ThreadingMode) (n)) /** * Specify threading mode to use. * * @param daemon daemon to configure * @param tm mode to use (positive values indicate the * number of worker threads to be used) */ _MHD_EXTERN void MHD_daemon_threading_mode (struct MHD_Daemon *daemon, enum MHD_ThreadingMode tm) MHD_NONNULL (1); /** * Allow or deny a client to connect. * * @param cls closure * @param addr address information from the client * @param addrlen length of @a addr * @see #MHD_daemon_accept_policy() * @return #MHD_YES if connection is allowed, #MHD_NO if not */ typedef enum MHD_Bool (*MHD_AcceptPolicyCallback)(void *cls, const struct sockaddr *addr, size_t addrlen); /** * Set a policy callback that accepts/rejects connections * based on the client's IP address. This function will be called * before a connection object is created. * * @param daemon daemon to set policy for * @param apc function to call to check the policy * @param apc_cls closure for @a apc */ _MHD_EXTERN void MHD_daemon_accept_policy (struct MHD_Daemon *daemon, MHD_AcceptPolicyCallback apc, void *apc_cls) MHD_NONNULL (1); /** * Function called by MHD to allow the application to log * the full @a uri of a @a request. * * @param cls client-defined closure * @param uri the full URI from the HTTP request * @param request the HTTP request handle (headers are * not yet available) * @return value to set for the "request_context" of @a request */ typedef void * (*MHD_EarlyUriLogCallback)(void *cls, const char *uri, struct MHD_Request *request); /** * Register a callback to be called first for every request * (before any parsing of the header). Makes it easy to * log the full URL. * * @param daemon daemon for which to set the logger * @param cb function to call * @param cb_cls closure for @a cb */ _MHD_EXTERN void MHD_daemon_set_early_uri_logger (struct MHD_Daemon *daemon, MHD_EarlyUriLogCallback cb, void *cb_cls) MHD_NONNULL (1); /** * The `enum MHD_ConnectionNotificationCode` specifies types * of connection notifications. * @ingroup request */ enum MHD_ConnectionNotificationCode { /** * A new connection has been started. * @ingroup request */ MHD_CONNECTION_NOTIFY_STARTED = 0, /** * A connection is closed. * @ingroup request */ MHD_CONNECTION_NOTIFY_CLOSED = 1 }; /** * Signature of the callback used by MHD to notify the * application about started/stopped connections * * @param cls client-defined closure * @param connection connection handle * @param socket_context socket-specific pointer where the * client can associate some state specific * to the TCP connection; note that this is * different from the "req_cls" which is per * HTTP request. The client can initialize * during #MHD_CONNECTION_NOTIFY_STARTED and * cleanup during #MHD_CONNECTION_NOTIFY_CLOSED * and access in the meantime using * #MHD_CONNECTION_INFO_SOCKET_CONTEXT. * @param toe reason for connection notification * @see #MHD_OPTION_NOTIFY_CONNECTION * @ingroup request */ typedef void (*MHD_NotifyConnectionCallback) (void *cls, struct MHD_Connection *connection, enum MHD_ConnectionNotificationCode toe); /** * Register a function that should be called whenever a connection is * started or closed. * * @param daemon daemon to set callback for * @param ncc function to call to check the policy * @param ncc_cls closure for @a apc */ _MHD_EXTERN void MHD_daemon_set_notify_connection (struct MHD_Daemon *daemon, MHD_NotifyConnectionCallback ncc, void *ncc_cls) MHD_NONNULL (1); /** * Maximum memory size per connection. * Default is 32 kb (#MHD_POOL_SIZE_DEFAULT). * Values above 128k are unlikely to result in much benefit, as half * of the memory will be typically used for IO, and TCP buffers are * unlikely to support window sizes above 64k on most systems. * * @param daemon daemon to configure * @param memory_limit_b connection memory limit to use in bytes * @param memory_increment_b increment to use when growing the read buffer, must be smaller than @a memory_limit_b */ _MHD_EXTERN void MHD_daemon_connection_memory_limit (struct MHD_Daemon *daemon, size_t memory_limit_b, size_t memory_increment_b) MHD_NONNULL (1); /** * Desired size of the stack for threads created by MHD. Use 0 for * system default. Only useful if the selected threading mode * is not #MHD_TM_EXTERNAL_EVENT_LOOP. * * @param daemon daemon to configure * @param stack_limit_b stack size to use in bytes */ _MHD_EXTERN void MHD_daemon_thread_stack_size (struct MHD_Daemon *daemon, size_t stack_limit_b) MHD_NONNULL (1); /** * Set maximum number of concurrent connections to accept. If not * given, MHD will not enforce any limits (modulo running into * OS limits). Values of 0 mean no limit. * * @param daemon daemon to configure * @param global_connection_limit maximum number of (concurrent) connections * @param ip_connection_limit limit on the number of (concurrent) * connections made to the server from the same IP address. * Can be used to prevent one IP from taking over all of * the allowed connections. If the same IP tries to * establish more than the specified number of * connections, they will be immediately rejected. */ _MHD_EXTERN void MHD_daemon_connection_limits (struct MHD_Daemon *daemon, unsigned int global_connection_limit, unsigned int ip_connection_limit) MHD_NONNULL (1); /** * After how many seconds of inactivity should a * connection automatically be timed out? * Use zero for no timeout, which is also the (unsafe!) default. * * @param daemon daemon to configure * @param timeout_s number of seconds of timeout to use */ _MHD_EXTERN void MHD_daemon_connection_default_timeout (struct MHD_Daemon *daemon, unsigned int timeout_s) MHD_NONNULL (1); /** * Signature of functions performing unescaping of strings. * The return value must be "strlen(s)" and @a s should be * updated. Note that the unescape function must not lengthen @a s * (the result must be shorter than the input and still be * 0-terminated). * * @param cls closure * @param req the request for which unescaping is performed * @param[in,out] s string to unescape * @return number of characters in @a s (excluding 0-terminator) */ typedef size_t (*MHD_UnescapeCallback) (void *cls, struct MHD_Request *req, char *s); /** * Specify a function that should be called for unescaping escape * sequences in URIs and URI arguments. Note that this function * will NOT be used by the `struct MHD_PostProcessor`. If this * option is not specified, the default method will be used which * decodes escape sequences of the form "%HH". * * @param daemon daemon to configure * @param unescape_cb function to use, NULL for default * @param unescape_cb_cls closure for @a unescape_cb */ _MHD_EXTERN void MHD_daemon_unescape_cb (struct MHD_Daemon *daemon, MHD_UnescapeCallback unescape_cb, void *unescape_cb_cls) MHD_NONNULL (1); /** * Set random values to be used by the Digest Auth module. Note that * the application must ensure that @a buf remains allocated and * unmodified while the daemon is running. * * @param daemon daemon to configure * @param buf_size number of bytes in @a buf * @param buf entropy buffer */ _MHD_EXTERN void MHD_daemon_digest_auth_random (struct MHD_Daemon *daemon, size_t buf_size, const void *buf) MHD_NONNULL (1,3); /** * Length of the internal array holding the map of the nonce and * the nonce counter. * * @param daemon daemon to configure * @param nc_length desired array length */ _MHD_EXTERN enum MHD_StatusCode MHD_daemon_digest_auth_nc_length (struct MHD_Daemon *daemon, size_t nc_length) MHD_NONNULL (1); /* ********************* connection options ************** */ /** * Set custom timeout for the given connection. * Specified as the number of seconds. Use zero for no timeout. * Calling this function will reset timeout timer. * * @param connection connection to configure timeout for * @param timeout_s new timeout in seconds */ _MHD_EXTERN void MHD_connection_set_timeout (struct MHD_Connection *connection, unsigned int timeout_s) MHD_NONNULL (1); /* **************** Request handling functions ***************** */ /** * The `enum MHD_ValueKind` specifies the source of * the key-value pairs in the HTTP protocol. */ enum MHD_ValueKind { /** * HTTP header (request/response). */ MHD_HEADER_KIND = 1, /** * Cookies. Note that the original HTTP header containing * the cookie(s) will still be available and intact. */ MHD_COOKIE_KIND = 2, /** * POST data. This is available only if a content encoding * supported by MHD is used (currently only URL encoding), * and only if the posted content fits within the available * memory pool. Note that in that case, the upload data * given to the #MHD_AccessHandlerCallback will be * empty (since it has already been processed). */ MHD_POSTDATA_KIND = 4, /** * GET (URI) arguments. */ MHD_GET_ARGUMENT_KIND = 8, /** * HTTP footer (only for HTTP 1.1 chunked encodings). */ MHD_FOOTER_KIND = 16 }; /** * Iterator over key-value pairs. This iterator can be used to * iterate over all of the cookies, headers, or POST-data fields of a * request, and also to iterate over the headers that have been added * to a response. * * @param cls closure * @param kind kind of the header we are looking at * @param key key for the value, can be an empty string * @param value corresponding value, can be NULL * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration * @ingroup request */ typedef int (*MHD_KeyValueIterator) (void *cls, enum MHD_ValueKind kind, const char *key, const char *value); /** * Get all of the headers from the request. * * @param request request to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup request */ _MHD_EXTERN unsigned int MHD_request_get_values (struct MHD_Request *request, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) MHD_NONNULL (1); /** * This function can be used to add an entry to the HTTP headers of a * request (so that the #MHD_request_get_values function will * return them -- and the `struct MHD_PostProcessor` will also see * them). This maybe required in certain situations (see Mantis * #1399) where (broken) HTTP implementations fail to supply values * needed by the post processor (or other parts of the application). * * This function MUST only be called from within the * request callbacks (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param request the request for which a * value should be set * @param kind kind of the value * @param key key for the value * @param value the value itself * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Bool MHD_request_set_value (struct MHD_Request *request, enum MHD_ValueKind kind, const char *key, const char *value) MHD_NONNULL (1,3,4); /** * Get a particular header value. If multiple * values match the kind, return any one of them. * * @param request request to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @return NULL if no such item was found * @ingroup request */ _MHD_EXTERN const char * MHD_request_lookup_value (struct MHD_Request *request, enum MHD_ValueKind kind, const char *key) MHD_NONNULL (1); /** * @defgroup httpcode HTTP response codes. * These are the status codes defined for HTTP responses. * @{ */ /* See http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml */ enum MHD_HTTP_StatusCode { MHD_HTTP_CONTINUE = 100, MHD_HTTP_SWITCHING_PROTOCOLS = 101, MHD_HTTP_PROCESSING = 102, MHD_HTTP_OK = 200, MHD_HTTP_CREATED = 201, MHD_HTTP_ACCEPTED = 202, MHD_HTTP_NON_AUTHORITATIVE_INFORMATION = 203, MHD_HTTP_NO_CONTENT = 204, MHD_HTTP_RESET_CONTENT = 205, MHD_HTTP_PARTIAL_CONTENT = 206, MHD_HTTP_MULTI_STATUS = 207, MHD_HTTP_ALREADY_REPORTED = 208, MHD_HTTP_IM_USED = 226, MHD_HTTP_MULTIPLE_CHOICES = 300, MHD_HTTP_MOVED_PERMANENTLY = 301, MHD_HTTP_FOUND = 302, MHD_HTTP_SEE_OTHER = 303, MHD_HTTP_NOT_MODIFIED = 304, MHD_HTTP_USE_PROXY = 305, MHD_HTTP_SWITCH_PROXY = 306, /* IANA: unused */ MHD_HTTP_TEMPORARY_REDIRECT = 307, MHD_HTTP_PERMANENT_REDIRECT = 308, MHD_HTTP_BAD_REQUEST = 400, MHD_HTTP_UNAUTHORIZED = 401, MHD_HTTP_PAYMENT_REQUIRED = 402, MHD_HTTP_FORBIDDEN = 403, MHD_HTTP_NOT_FOUND = 404, MHD_HTTP_METHOD_NOT_ALLOWED = 405, MHD_HTTP_NOT_ACCEPTABLE = 406, /** @deprecated */ #define MHD_HTTP_METHOD_NOT_ACCEPTABLE \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, use MHD_HTTP_NOT_ACCEPTABLE") \ MHD_HTTP_NOT_ACCEPTABLE MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED = 407, MHD_HTTP_REQUEST_TIMEOUT = 408, MHD_HTTP_CONFLICT = 409, MHD_HTTP_GONE = 410, MHD_HTTP_LENGTH_REQUIRED = 411, MHD_HTTP_PRECONDITION_FAILED = 412, MHD_HTTP_PAYLOAD_TOO_LARGE = 413, /** @deprecated */ #define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, use MHD_HTTP_PAYLOAD_TOO_LARGE") \ MHD_HTTP_PAYLOAD_TOO_LARGE MHD_HTTP_URI_TOO_LONG = 414, /** @deprecated */ #define MHD_HTTP_REQUEST_URI_TOO_LONG \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, use MHD_HTTP_URI_TOO_LONG") \ MHD_HTTP_URI_TOO_LONG MHD_HTTP_UNSUPPORTED_MEDIA_TYPE = 415, MHD_HTTP_RANGE_NOT_SATISFIABLE = 416, /** @deprecated */ #define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE") \ MHD_HTTP_RANGE_NOT_SATISFIABLE MHD_HTTP_EXPECTATION_FAILED = 417, MHD_HTTP_MISDIRECTED_REQUEST = 421, MHD_HTTP_UNPROCESSABLE_ENTITY = 422, MHD_HTTP_LOCKED = 423, MHD_HTTP_FAILED_DEPENDENCY = 424, MHD_HTTP_UNORDERED_COLLECTION = 425, /* IANA: unused */ MHD_HTTP_UPGRADE_REQUIRED = 426, MHD_HTTP_PRECONDITION_REQUIRED = 428, MHD_HTTP_TOO_MANY_REQUESTS = 429, MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431, MHD_HTTP_NO_RESPONSE = 444, /* IANA: unused */ MHD_HTTP_RETRY_WITH = 449, /* IANA: unused */ MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450, /* IANA: unused */ MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451, MHD_HTTP_INTERNAL_SERVER_ERROR = 500, MHD_HTTP_NOT_IMPLEMENTED = 501, MHD_HTTP_BAD_GATEWAY = 502, MHD_HTTP_SERVICE_UNAVAILABLE = 503, MHD_HTTP_GATEWAY_TIMEOUT = 504, MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED = 505, MHD_HTTP_VARIANT_ALSO_NEGOTIATES = 506, MHD_HTTP_INSUFFICIENT_STORAGE = 507, MHD_HTTP_LOOP_DETECTED = 508, MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED = 509, /* IANA: unused */ MHD_HTTP_NOT_EXTENDED = 510, MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511 }; /** * Returns the string reason phrase for a response code. * * If we don't have a string for a status code, we give the first * message in that status code class. */ _MHD_EXTERN const char * MHD_get_reason_phrase_for (enum MHD_HTTP_StatusCode code); /** @} */ /* end of group httpcode */ /** * @defgroup versions HTTP versions * These strings should be used to match against the first line of the * HTTP header. * @{ */ #define MHD_HTTP_VERSION_1_0 "HTTP/1.0" #define MHD_HTTP_VERSION_1_1 "HTTP/1.1" /** @} */ /* end of group versions */ /** * Suspend handling of network data for a given request. This can * be used to dequeue a request from MHD's event loop for a while. * * If you use this API in conjunction with a internal select or a * thread pool, you must set the option #MHD_USE_ITC to * ensure that a resumed request is immediately processed by MHD. * * Suspended requests continue to count against the total number of * requests allowed (per daemon, as well as per IP, if such limits * are set). Suspended requests will NOT time out; timeouts will * restart when the request handling is resumed. While a * request is suspended, MHD will not detect disconnects by the * client. * * The only safe time to suspend a request is from either a * #MHD_RequestHeaderCallback, #MHD_UploadCallback, or a * #MHD_RequestfetchResponseCallback. Suspending a request * at any other time will cause an assertion failure. * * Finally, it is an API violation to call #MHD_daemon_stop() while * having suspended requests (this will at least create memory and * socket leaks or lead to undefined behavior). You must explicitly * resume all requests before stopping the daemon. * * @return action to cause a request to be suspended. */ _MHD_EXTERN const struct MHD_Action * MHD_action_suspend (void); /** * Resume handling of network data for suspended request. It is * safe to resume a suspended request at any time. Calling this * function on a request that was not previously suspended will * result in undefined behavior. * * If you are using this function in ``external'' select mode, you must * make sure to run #MHD_run() afterwards (before again calling * #MHD_get_fdset(), as otherwise the change may not be reflected in * the set returned by #MHD_get_fdset() and you may end up with a * request that is stuck until the next network activity. * * @param request the request to resume */ _MHD_EXTERN void MHD_request_resume (struct MHD_Request *request) MHD_NONNULL (1); /* **************** Response manipulation functions ***************** */ /** * Data transmitted in response to an HTTP request. * Usually the final action taken in response to * receiving a request. */ struct MHD_Response; /** * Converts a @a response to an action. If @a destroy_after_use * is set, the reference to the @a response is consumed * by the conversion. If @a consume is #MHD_NO, then * the @a response can be converted to actions in the future. * However, the @a response is frozen by this step and * must no longer be modified (i.e. by setting headers). * * @param response response to convert, not NULL * @param destroy_after_use should the response object be consumed? * @return corresponding action, never returns NULL * * Implementation note: internally, this is largely just * a cast (and possibly an RC increment operation), * as a response *is* an action. As no memory is * allocated, this operation cannot fail. */ _MHD_EXTERN const struct MHD_Action * MHD_action_from_response (struct MHD_Response *response, enum MHD_Bool destroy_after_use) MHD_NONNULL (1); /** * Only respond in conservative HTTP 1.0-mode. In * particular, do not (automatically) sent "Connection" headers and * always close the connection after generating the response. * * @param request the request for which we force HTTP 1.0 to be used */ _MHD_EXTERN void MHD_response_option_v10_only (struct MHD_Response *response) MHD_NONNULL (1); /** * The `enum MHD_RequestTerminationCode` specifies reasons * why a request has been terminated (or completed). * @ingroup request */ enum MHD_RequestTerminationCode { /** * We finished sending the response. * @ingroup request */ MHD_REQUEST_TERMINATED_COMPLETED_OK = 0, /** * Error handling the connection (resources * exhausted, other side closed connection, * application error accepting request, etc.) * @ingroup request */ MHD_REQUEST_TERMINATED_WITH_ERROR = 1, /** * No activity on the connection for the number * of seconds specified using * #MHD_OPTION_CONNECTION_TIMEOUT. * @ingroup request */ MHD_REQUEST_TERMINATED_TIMEOUT_REACHED = 2, /** * We had to close the session since MHD was being * shut down. * @ingroup request */ MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3, /** * We tried to read additional data, but the other side closed the * connection. This error is similar to * #MHD_REQUEST_TERMINATED_WITH_ERROR, but specific to the case where * the connection died because the other side did not send expected * data. * @ingroup request */ MHD_REQUEST_TERMINATED_READ_ERROR = 4, /** * The client terminated the connection by closing the socket * for writing (TCP half-closed); MHD aborted sending the * response according to RFC 2616, section 8.1.4. * @ingroup request */ MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5 }; /** * Signature of the callback used by MHD to notify the application * about completed requests. * * @param cls client-defined closure * @param toe reason for request termination * @param request_context request context value, as originally * returned by the #MHD_EarlyUriLogCallback * @see #MHD_option_request_completion() * @ingroup request */ typedef void (*MHD_RequestTerminationCallback) (void *cls, enum MHD_RequestTerminationCode toe, void *request_context); /** * Set a function to be called once MHD is finished with the * request. * * @param response which response to set the callback for * @param termination_cb function to call * @param termination_cb_cls closure for @e termination_cb */ _MHD_EXTERN void MHD_response_option_termination_callback (struct MHD_Response *response, MHD_RequestTerminationCallback termination_cb, void *termination_cb_cls) MHD_NONNULL (1); /** * Callback used by libmicrohttpd in order to obtain content. The * callback is to copy at most @a max bytes of content into @a buf. The * total number of bytes that has been placed into @a buf should be * returned. * * Note that returning zero will cause libmicrohttpd to try again. * Thus, returning zero should only be used in conjunction * with MHD_suspend_connection() to avoid busy waiting. * * @param cls extra argument to the callback * @param pos position in the datastream to access; * note that if a `struct MHD_Response` object is re-used, * it is possible for the same content reader to * be queried multiple times for the same data; * however, if a `struct MHD_Response` is not re-used, * libmicrohttpd guarantees that "pos" will be * the sum of all non-negative return values * obtained from the content reader so far. * @param buf where to copy the data * @param max maximum number of bytes to copy to @a buf (size of @a buf) * @return number of bytes written to @a buf; * 0 is legal unless we are running in internal select mode (since * this would cause busy-waiting); 0 in external select mode * will cause this function to be called again once the external * select calls MHD again; * #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular * end of transmission (with chunked encoding, MHD will then * terminate the chunk and send any HTTP footers that might be * present; without chunked encoding and given an unknown * response size, MHD will simply close the connection; note * that while returning #MHD_CONTENT_READER_END_OF_STREAM is not technically * legal if a response size was specified, MHD accepts this * and treats it just as #MHD_CONTENT_READER_END_WITH_ERROR; * #MHD_CONTENT_READER_END_WITH_ERROR (-2) to indicate a server * error generating the response; this will cause MHD to simply * close the connection immediately. If a response size was * given or if chunked encoding is in use, this will indicate * an error to the client. Note, however, that if the client * does not know a response size and chunked encoding is not in * use, then clients will not be able to tell the difference between * #MHD_CONTENT_READER_END_WITH_ERROR and #MHD_CONTENT_READER_END_OF_STREAM. * This is not a limitation of MHD but rather of the HTTP protocol. */ typedef ssize_t (*MHD_ContentReaderCallback) (void *cls, uint64_t pos, char *buf, size_t max); /** * This method is called by libmicrohttpd if we are done with a * content reader. It should be used to free resources associated * with the content reader. * * @param cls closure * @ingroup response */ typedef void (*MHD_ContentReaderFreeCallback) (void *cls); /** * Create a response action. The response object can be extended with * header information and then be used any number of times. * * @param sc status code to return * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown * @param block_size preferred block size for querying crc (advisory only, * MHD may still call @a crc using smaller chunks); this * is essentially the buffer size used for IO, clients * should pick a value that is appropriate for IO and * memory performance requirements * @param crc callback to use to obtain response data * @param crc_cls extra argument to @a crc * @param crfc callback to call to free @a crc_cls resources * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_response_from_callback (enum MHD_HTTP_StatusCode sc, uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc); /** * Specification for how MHD should treat the memory buffer * given for the response. * @ingroup response */ enum MHD_ResponseMemoryMode { /** * Buffer is a persistent (static/global) buffer that won't change * for at least the lifetime of the response, MHD should just use * it, not free it, not copy it, just keep an alias to it. * @ingroup response */ MHD_RESPMEM_PERSISTENT, /** * Buffer is heap-allocated with `malloc()` (or equivalent) and * should be freed by MHD after processing the response has * concluded (response reference counter reaches zero). * @ingroup response */ MHD_RESPMEM_MUST_FREE, /** * Buffer is in transient memory, but not on the heap (for example, * on the stack or non-`malloc()` allocated) and only valid during the * call to #MHD_create_response_from_buffer. MHD must make its * own private copy of the data for processing. * @ingroup response */ MHD_RESPMEM_MUST_COPY }; /** * Create a response object. The response object can be extended with * header information and then be used any number of times. * * @param sc status code to use for the response; * #MHD_HTTP_NO_CONTENT is only valid if @a size is 0; * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param mode flags for buffer management * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_response_from_buffer (enum MHD_HTTP_StatusCode sc, size_t size, void *buffer, enum MHD_ResponseMemoryMode mode); /** * Create a response object based on an @a fd from which * data is read. The response object can be extended with * header information and then be used any number of times. * * @param sc status code to return * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * reading file beyond 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_response_from_fd (enum MHD_HTTP_StatusCode sc, int fd, uint64_t offset, uint64_t size); /** * Enumeration for operations MHD should perform on the underlying socket * of the upgrade. This API is not finalized, and in particular * the final set of actions is yet to be decided. This is just an * idea for what we might want. */ enum MHD_UpgradeOperation { /** * Close the socket, the application is done with it. * * Takes no extra arguments. */ MHD_UPGRADE_OPERATION_CLOSE = 0 }; /** * Handle given to the application to manage special * actions relating to MHD responses that "upgrade" * the HTTP protocol (i.e. to WebSockets). */ struct MHD_UpgradeResponseHandle; /** * This connection-specific callback is provided by MHD to * applications (unusual) during the #MHD_UpgradeHandler. * It allows applications to perform 'special' actions on * the underlying socket from the upgrade. * * FIXME: this API still uses the untyped, ugly varargs. * Should we not modernize this one as well? * * @param urh the handle identifying the connection to perform * the upgrade @a action on. * @param operation which operation should be performed * @param ... arguments to the action (depends on the action) * @return #MHD_NO on error, #MHD_YES on success */ _MHD_EXTERN enum MHD_Bool MHD_upgrade_operation (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeOperation operation, ...) MHD_NONNULL (1); /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_response_create_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ typedef void (*MHD_UpgradeHandler)(void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh); /** * Create a response object that can be used for 101 UPGRADE * responses, for example to implement WebSockets. After sending the * response, control over the data stream is given to the callback (which * can then, for example, start some bi-directional communication). * If the response is queued for multiple connections, the callback * will be called for each connection. The callback * will ONLY be called after the response header was successfully passed * to the OS; if there are communication errors before, the usual MHD * connection error handling code will be performed. * * MHD will automatically set the correct HTTP status * code (#MHD_HTTP_SWITCHING_PROTOCOLS). * Setting correct HTTP headers for the upgrade must be done * manually (this way, it is possible to implement most existing * WebSocket versions using this API; in fact, this API might be useful * for any protocol switch, not just WebSockets). Note that * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 * Switching Protocols" (if the response code 101 is used). * * As usual, the response object can be extended with header * information and then be used any number of times (as long as the * header information is not connection-specific). * * @param upgrade_handler function to call with the "upgraded" socket * @param upgrade_handler_cls closure for @a upgrade_handler * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) MHD_NONNULL (1); /** * Explicitly decrease reference counter of a response object. If the * counter hits zero, destroys a response object and associated * resources. Usually, this is implicitly done by converting a * response to an action and returning the action to MHD. * * @param response response to decrement RC of * @ingroup response */ _MHD_EXTERN void MHD_response_queue_for_destroy (struct MHD_Response *response) MHD_NONNULL (1); /** * Add a header line to the response. * * @param response response to add a header to * @param header the header to add * @param content value to add * @return #MHD_NO on error (i.e. invalid header or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Bool MHD_response_add_header (struct MHD_Response *response, const char *header, const char *content) MHD_NONNULL (1,2,3); /** * Add a tailer line to the response. * * @param response response to add a footer to * @param footer the footer to add * @param content value to add * @return #MHD_NO on error (i.e. invalid footer or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Bool MHD_response_add_trailer (struct MHD_Response *response, const char *footer, const char *content) MHD_NONNULL (1,2,3); /** * Delete a header (or footer) line from the response. * * @param response response to remove a header from * @param header the header to delete * @param content value to delete * @return #MHD_NO on error (no such header known) * @ingroup response */ _MHD_EXTERN enum MHD_Bool MHD_response_del_header (struct MHD_Response *response, const char *header, const char *content) MHD_NONNULL (1,2,3); /** * Get all of the headers (and footers) added to a response. * * @param response response to query * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup response */ _MHD_EXTERN unsigned int MHD_response_get_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) MHD_NONNULL (1); /** * Get a particular header (or footer) from the response. * * @param response response to query * @param key which header to get * @return NULL if header does not exist * @ingroup response */ _MHD_EXTERN const char * MHD_response_get_header (struct MHD_Response *response, const char *key) MHD_NONNULL (1,2); /* ************Upload and PostProcessor functions ********************** */ /** * Action telling MHD to continue processing the upload. * * @return action operation, never NULL */ _MHD_EXTERN const struct MHD_Action * MHD_action_continue (void); /** * Function to process data uploaded by a client. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param upload_data the data being uploaded (excluding headers) * POST data will typically be made available incrementally via * multiple callbacks * @param[in,out] upload_data_size set initially to the size of the * @a upload_data provided; the method must update this * value to the number of bytes NOT processed; * @return action specifying how to proceed, often * #MHD_action_continue() if all is well, * #MHD_action_suspend() to stop reading the upload until * the request is resumed, * NULL to close the socket, or a response * to discard the rest of the upload and return the data given */ typedef const struct MHD_Action * (*MHD_UploadCallback) (void *cls, const char *upload_data, size_t *upload_data_size); /** * Create an action that handles an upload. * * @param uc function to call with uploaded data * @param uc_cls closure for @a uc * @return NULL on error (out of memory) * @ingroup action */ _MHD_EXTERN const struct MHD_Action * MHD_action_process_upload (MHD_UploadCallback uc, void *uc_cls) MHD_NONNULL (1); /** * Iterator over key-value pairs where the value maybe made available * in increments and/or may not be zero-terminated. Used for * MHD parsing POST data. To access "raw" data from POST or PUT * requests, use #MHD_action_process_upload() instead. * * @param cls user-specified closure * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to @a size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in @a data available * @return action specifying how to proceed, often * #MHD_action_continue() if all is well, * #MHD_action_suspend() to stop reading the upload until * the request is resumed, * NULL to close the socket, or a response * to discard the rest of the upload and return the data given */ typedef const struct MHD_Action * (*MHD_PostDataIterator) (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size); /** * Create an action that parses a POST request. * * This action can be used to (incrementally) parse the data portion * of a POST request. Note that some buggy browsers fail to set the * encoding type. If you want to support those, you may have to call * #MHD_set_connection_value with the proper encoding type before * returning this action (if no supported encoding type is detected, * returning this action will cause a bad request to be returned to * the client). * * @param buffer_size maximum number of bytes to use for * internal buffering (used only for the parsing, * specifically the parsing of the keys). A * tiny value (256-1024) should be sufficient. * Do NOT use a value smaller than 256. For good * performance, use 32 or 64k (i.e. 65536). * @param iter iterator to be called with the parsed data, * Must NOT be NULL. * @param iter_cls first argument to @a iter * @return NULL on error (out of memory, unsupported encoding), * otherwise a PP handle * @ingroup request */ _MHD_EXTERN const struct MHD_Action * MHD_action_parse_post (size_t buffer_size, MHD_PostDataIterator iter, void *iter_cls) MHD_NONNULL (2); /* ********************** generic query functions ********************** */ /** * Select which member of the `struct ConnectionInformation` * union is desired to be returned by #MHD_connection_get_info(). */ enum MHD_ConnectionInformationType { /** * What cipher algorithm is being used. * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFORMATION_CIPHER_ALGO, /** * * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFORMATION_PROTOCOL, /** * Obtain IP address of the client. Takes no extra arguments. * Returns essentially a `struct sockaddr **` (since the API returns * a `union MHD_ConnectionInfo *` and that union contains a `struct * sockaddr *`). * @ingroup request */ MHD_CONNECTION_INFORMATION_CLIENT_ADDRESS, /** * Get the gnuTLS session handle. * @ingroup request */ MHD_CONNECTION_INFORMATION_GNUTLS_SESSION, /** * Get the gnuTLS client certificate handle. Dysfunctional (never * implemented, deprecated). Use #MHD_CONNECTION_INFORMATION_GNUTLS_SESSION * to get the `gnutls_session_t` and then call * gnutls_certificate_get_peers(). */ MHD_CONNECTION_INFORMATION_GNUTLS_CLIENT_CERT, /** * Get the `struct MHD_Daemon *` responsible for managing this connection. * @ingroup request */ MHD_CONNECTION_INFORMATION_DAEMON, /** * Request the file descriptor for the connection socket. * No extra arguments should be passed. * @ingroup request */ MHD_CONNECTION_INFORMATION_CONNECTION_FD, /** * Returns the client-specific pointer to a `void *` that was (possibly) * set during a #MHD_NotifyConnectionCallback when the socket was * first accepted. Note that this is NOT the same as the "req_cls" * argument of the #MHD_AccessHandlerCallback. The "req_cls" is * fresh for each HTTP request, while the "socket_context" is fresh * for each socket. */ MHD_CONNECTION_INFORMATION_SOCKET_CONTEXT, /** * Get connection timeout * @ingroup request */ MHD_CONNECTION_INFORMATION_CONNECTION_TIMEOUT, /** * Check whether the connection is suspended. * @ingroup request */ MHD_CONNECTION_INFORMATION_CONNECTION_SUSPENDED }; /** * Information about a connection. */ union MHD_ConnectionInformation { /** * Cipher algorithm used, of type "enum gnutls_cipher_algorithm". */ int /* enum gnutls_cipher_algorithm */ cipher_algorithm; /** * Protocol used, of type "enum gnutls_protocol". */ int /* enum gnutls_protocol */ protocol; /** * Amount of second that connection could spend in idle state * before automatically disconnected. * Zero for no timeout (unlimited idle time). */ unsigned int connection_timeout; /** * Connect socket */ MHD_socket connect_fd; /** * GNUtls session handle, of type "gnutls_session_t". */ void * /* gnutls_session_t */ tls_session; /** * GNUtls client certificate handle, of type "gnutls_x509_crt_t". */ void * /* gnutls_x509_crt_t */ client_cert; /** * Address information for the client. */ const struct sockaddr *client_addr; /** * Which daemon manages this connection (useful in case there are many * daemons running). */ struct MHD_Daemon *daemon; /** * Pointer to connection-specific client context. Points to the * same address as the "socket_context" of the * #MHD_NotifyConnectionCallback. */ void **socket_context; /** * Is this connection right now suspended? */ enum MHD_Bool suspended; }; /** * Obtain information about the given connection. * Use wrapper macro #MHD_connection_get_information() instead of direct use * of this function. * * @param connection what connection to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @param return_value_size size of union MHD_ConnectionInformation at compile * time * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ _MHD_EXTERN enum MHD_Bool MHD_connection_get_information_sz (struct MHD_Connection *connection, enum MHD_ConnectionInformationType info_type, union MHD_ConnectionInformation *return_value, size_t return_value_size) MHD_NONNULL (1,3); /** * Obtain information about the given connection. * * @param connection what connection to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ #define MHD_connection_get_information(connection, \ info_type, \ return_value) \ MHD_connection_get_information_sz ((connection),(info_type),(return_value), \ sizeof(union MHD_ConnectionInformation)) /** * Information we return about a request. */ union MHD_RequestInformation { /** * Connection via which we received the request. */ struct MHD_Connection *connection; /** * Pointer to client context. Will also be given to * the application in a #MHD_RequestTerminationCallback. */ void **request_context; /** * HTTP version requested by the client. */ const char *http_version; /** * HTTP method of the request, as a string. Particularly useful if * #MHD_HTTP_METHOD_UNKNOWN was given. */ const char *http_method; /** * Size of the client's HTTP header. */ size_t header_size; }; /** * Select which member of the `struct RequestInformation` * union is desired to be returned by #MHD_request_get_info(). */ enum MHD_RequestInformationType { /** * Return which connection the request is associated with. */ MHD_REQUEST_INFORMATION_CONNECTION, /** * Returns the client-specific pointer to a `void *` that * is specific to this request. */ MHD_REQUEST_INFORMATION_CLIENT_CONTEXT, /** * Return the HTTP version string given by the client. * @ingroup request */ MHD_REQUEST_INFORMATION_HTTP_VERSION, /** * Return the HTTP method used by the request. * @ingroup request */ MHD_REQUEST_INFORMATION_HTTP_METHOD, /** * Return length of the client's HTTP request header. * @ingroup request */ MHD_REQUEST_INFORMATION_HEADER_SIZE }; /** * Obtain information about the given request. * Use wrapper macro #MHD_request_get_information() instead of direct use * of this function. * * @param request what request to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @param return_value_size size of union MHD_RequestInformation at compile * time * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ _MHD_EXTERN enum MHD_Bool MHD_request_get_information_sz (struct MHD_Request *request, enum MHD_RequestInformationType info_type, union MHD_RequestInformation *return_value, size_t return_value_size) MHD_NONNULL (1,3); /** * Obtain information about the given request. * * @param request what request to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ #define MHD_request_get_information (request, \ info_type, \ return_value) \ MHD_request_get_information_sz ((request), (info_type), (return_value), \ sizeof(union MHD_RequestInformation)) /** * Values of this enum are used to specify what * information about a daemon is desired. */ enum MHD_DaemonInformationType { /** * Request the file descriptor for the listening socket. * No extra arguments should be passed. */ MHD_DAEMON_INFORMATION_LISTEN_SOCKET, /** * Request the file descriptor for the external epoll. * No extra arguments should be passed. */ MHD_DAEMON_INFORMATION_EPOLL_FD, /** * Request the number of current connections handled by the daemon. * No extra arguments should be passed. * Note: when using MHD in external polling mode, this type of request * could be used only when #MHD_run()/#MHD_run_from_select is not * working in other thread at the same time. */ MHD_DAEMON_INFORMATION_CURRENT_CONNECTIONS, /** * Request the port number of daemon's listen socket. * No extra arguments should be passed. * Note: if port '0' was specified for #MHD_option_port(), returned * value will be real port number. */ MHD_DAEMON_INFORMATION_BIND_PORT }; /** * Information about an MHD daemon. */ union MHD_DaemonInformation { /** * Socket, returned for #MHD_DAEMON_INFORMATION_LISTEN_SOCKET. */ MHD_socket listen_socket; /** * Bind port number, returned for #MHD_DAEMON_INFORMATION_BIND_PORT. */ uint16_t port; /** * epoll FD, returned for #MHD_DAEMON_INFORMATION_EPOLL_FD. */ int epoll_fd; /** * Number of active connections, for #MHD_DAEMON_INFORMATION_CURRENT_CONNECTIONS. */ unsigned int num_connections; }; /** * Obtain information about the given daemon. * Use wrapper macro #MHD_daemon_get_information() instead of direct use * of this function. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @param return_value_size size of union MHD_DaemonInformation at compile * time * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ _MHD_EXTERN enum MHD_Bool MHD_daemon_get_information_sz (struct MHD_Daemon *daemon, enum MHD_DaemonInformationType info_type, union MHD_DaemonInformation *return_value, size_t return_value_size) MHD_NONNULL (1,3); /** * Obtain information about the given daemon. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param[out] return_value pointer to union where requested information will * be stored * @return #MHD_YES on success, #MHD_NO on error * (@a info_type is unknown, NULL pointer etc.) * @ingroup specialized */ #define MHD_daemon_get_information(daemon, \ info_type, \ return_value) \ MHD_daemon_get_information_sz ((daemon), (info_type), (return_value), \ sizeof(union MHD_DaemonInformation)); /** * Callback for serious error condition. The default action is to print * an error message and `abort()`. * * @param cls user specified value * @param file where the error occurred * @param line where the error occurred * @param reason error detail, may be NULL * @ingroup logging */ typedef void (*MHD_PanicCallback) (void *cls, const char *file, unsigned int line, const char *reason); /** * Sets the global error handler to a different implementation. @a cb * will only be called in the case of typically fatal, serious * internal consistency issues. These issues should only arise in the * case of serious memory corruption or similar problems with the * architecture. While @a cb is allowed to return and MHD will then * try to continue, this is never safe. * * The default implementation that is used if no panic function is set * simply prints an error message and calls `abort()`. Alternative * implementations might call `exit()` or other similar functions. * * @param cb new error handler * @param cls passed to @a cb * @ingroup logging */ _MHD_EXTERN void MHD_set_panic_func (MHD_PanicCallback cb, void *cls); /** * Process escape sequences ('%HH') Updates val in place; the * result should be UTF-8 encoded and cannot be larger than the input. * The result must also still be 0-terminated. * * @param val value to unescape (modified in the process) * @return length of the resulting val (`strlen(val)` may be * shorter afterwards due to elimination of escape sequences) */ _MHD_EXTERN size_t MHD_http_unescape (char *val) MHD_NONNULL (1); /** * Types of information about MHD features, * used by #MHD_is_feature_supported(). */ enum MHD_Feature { /** * Get whether messages are supported. If supported then in debug * mode messages can be printed to stderr or to external logger. */ MHD_FEATURE_MESSAGES = 1, /** * Get whether HTTPS is supported. If supported then flag * #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST, * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE, * #MHD_OPTION_HTTPS_PRIORITIES can be used. */ MHD_FEATURE_TLS = 2, /** * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is * supported. */ MHD_FEATURE_HTTPS_CERT_CALLBACK = 3, /** * Get whether IPv6 is supported. If supported then flag * #MHD_USE_IPv6 can be used. */ MHD_FEATURE_IPv6 = 4, /** * Get whether IPv6 without IPv4 is supported. If not supported * then IPv4 is always enabled in IPv6 sockets and * flag #MHD_USE_DUAL_STACK if always used when #MHD_USE_IPv6 is * specified. */ MHD_FEATURE_IPv6_ONLY = 5, /** * Get whether `poll()` is supported. If supported then flag * #MHD_USE_POLL can be used. */ MHD_FEATURE_POLL = 6, /** * Get whether `epoll()` is supported. If supported then Flags * #MHD_USE_EPOLL and * #MHD_USE_EPOLL_INTERNAL_THREAD can be used. */ MHD_FEATURE_EPOLL = 7, /** * Get whether shutdown on listen socket to signal other * threads is supported. If not supported flag * #MHD_USE_ITC is automatically forced. */ MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8, /** * Get whether socketpair is used internally instead of pipe to * signal other threads. */ MHD_FEATURE_SOCKETPAIR = 9, /** * Get whether TCP Fast Open is supported. If supported then * flag #MHD_USE_TCP_FASTOPEN and option * #MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. */ MHD_FEATURE_TCP_FASTOPEN = 10, /** * Get whether HTTP Basic authorization is supported. If supported * then functions #MHD_basic_auth_get_username_password and * #MHD_queue_basic_auth_fail_response can be used. */ MHD_FEATURE_BASIC_AUTH = 11, /** * Get whether HTTP Digest authorization is supported. If * supported then options #MHD_OPTION_DIGEST_AUTH_RANDOM, * #MHD_OPTION_NONCE_NC_SIZE and * #MHD_digest_auth_check() can be used. */ MHD_FEATURE_DIGEST_AUTH = 12, /** * Get whether postprocessor is supported. If supported then * functions #MHD_create_post_processor(), #MHD_post_process() and * #MHD_destroy_post_processor() can * be used. */ MHD_FEATURE_POSTPROCESSOR = 13, /** * Get whether password encrypted private key for HTTPS daemon is * supported. If supported then option * ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used. */ MHD_FEATURE_HTTPS_KEY_PASSWORD = 14, /** * Get whether reading files beyond 2 GiB boundary is supported. * If supported then #MHD_create_response_from_fd(), * #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset() * and #MHD_create_response_from_fd_at_offset64() can be used with sizes and * offsets larger than 2 GiB. If not supported value of size+offset is * limited to 2 GiB. */ MHD_FEATURE_LARGE_FILE = 15, /** * Get whether MHD set names on generated threads. */ MHD_FEATURE_THREAD_NAMES = 16, /** * Get whether HTTP "Upgrade" is supported. * If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and * #MHD_create_response_for_upgrade() can be used. */ MHD_FEATURE_UPGRADE = 17, /** * Get whether it's safe to use same FD for multiple calls of * #MHD_create_response_from_fd() and whether it's safe to use single * response generated by #MHD_create_response_from_fd() with multiple * connections at same time. * If #MHD_is_feature_supported() return #MHD_NO for this feature then * usage of responses with same file FD in multiple parallel threads may * results in incorrect data sent to remote client. * It's always safe to use same file FD in multiple responses if MHD * is run in any single thread mode. */ MHD_FEATURE_RESPONSES_SHARED_FD = 18, /** * Get whether MHD support automatic detection of bind port number. * @sa #MHD_DAEMON_INFO_BIND_PORT */ MHD_FEATURE_AUTODETECT_BIND_PORT = 19, /** * Get whether MHD support SIGPIPE suppression. * If SIGPIPE suppression is not supported, application must handle * SIGPIPE signal by itself. */ MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20, /** * Get whether MHD use system's sendfile() function to send * file-FD based responses over non-TLS connections. * @note Since v0.9.56 */ MHD_FEATURE_SENDFILE = 21 }; /** * Get information about supported MHD features. * Indicate that MHD was compiled with or without support for * particular feature. Some features require additional support * by kernel. Kernel support is not checked by this function. * * @param feature type of requested information * @return #MHD_YES if feature is supported by MHD, #MHD_NO if * feature is not supported or feature is unknown. * @ingroup specialized */ _MHD_EXTERN enum MHD_Bool MHD_is_feature_supported (enum MHD_Feature feature); /** * What is this request waiting for? */ enum MHD_RequestEventLoopInfo { /** * We are waiting to be able to read. */ MHD_EVENT_LOOP_INFO_READ = 0, /** * We are waiting to be able to write. */ MHD_EVENT_LOOP_INFO_WRITE = 1, /** * We are waiting for the application to provide data. */ MHD_EVENT_LOOP_INFO_BLOCK = 2, /** * We are finished and are awaiting cleanup. */ MHD_EVENT_LOOP_INFO_CLEANUP = 3 }; #endif libmicrohttpd-1.0.2/src/include/microhttpd.h0000644000175000017500000075722115035216576016067 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2006-2021 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd.h * @brief public interface to libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * @author Chris GauthierDickey * * All symbols defined in this header start with MHD. MHD is a small * HTTP daemon library. As such, it does not have any API for logging * errors (you can only enable or disable logging to stderr). Also, * it may not support all of the HTTP features directly, where * applicable, portions of HTTP may have to be handled by clients of * the library. * * The library is supposed to handle everything that it must handle * (because the API would not allow clients to do this), such as basic * connection management; however, detailed interpretations of headers * -- such as range requests -- and HTTP methods are left to clients. * The library does understand HEAD and will only send the headers of * the response and not the body, even if the client supplied a body. * The library also understands headers that control connection * management (specifically, "Connection: close" and "Expect: 100 * continue" are understood and handled automatically). * * MHD understands POST data and is able to decode certain formats * (at the moment only "application/x-www-form-urlencoded" and * "multipart/formdata"). Unsupported encodings and large POST * submissions may require the application to manually process * the stream, which is provided to the main application (and thus can be * processed, just not conveniently by MHD). * * The header file defines various constants used by the HTTP protocol. * This does not mean that MHD actually interprets all of these * values. The provided constants are exported as a convenience * for users of the library. MHD does not verify that transmitted * HTTP headers are part of the standard specification; users of the * library are free to define their own extensions of the HTTP * standard and use those with MHD. * * All functions are guaranteed to be completely reentrant and * thread-safe (with the exception of #MHD_set_connection_value, * which must only be used in a particular context). * * * @defgroup event event-loop control * MHD API to start and stop the HTTP server and manage the event loop. * @defgroup response generation of responses * MHD API used to generate responses. * @defgroup request handling of requests * MHD API used to access information about requests. * @defgroup authentication HTTP authentication * MHD API related to basic and digest HTTP authentication. * @defgroup logging logging * MHD API to mange logging and error handling * @defgroup specialized misc. specialized functions * This group includes functions that do not fit into any particular * category and that are rarely used. */ #ifndef MHD_MICROHTTPD_H #define MHD_MICROHTTPD_H #ifndef __cplusplus # define MHD_C_DECLRATIONS_START_HERE_ /* Empty */ # define MHD_C_DECLRATIONS_FINISH_HERE_ /* Empty */ #else /* __cplusplus */ /* *INDENT-OFF* */ # define MHD_C_DECLRATIONS_START_HERE_ extern "C" { # define MHD_C_DECLRATIONS_FINISH_HERE_ } /* *INDENT-ON* */ #endif /* __cplusplus */ MHD_C_DECLRATIONS_START_HERE_ /** * Current version of the library in packed BCD form. * @note Version number components are coded as Simple Binary-Coded Decimal * (also called Natural BCD or BCD 8421). While they are hexadecimal numbers, * they are parsed as decimal numbers. * Example: 0x01093001 = 1.9.30-1. */ #define MHD_VERSION 0x01000200 /* If generic headers don't work on your platform, include headers which define 'va_list', 'size_t', 'ssize_t', 'intptr_t', 'off_t', 'uint8_t', 'uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t', 'struct sockaddr', 'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before including "microhttpd.h". Then the following "standard" includes won't be used (which might be a good idea, especially on platforms where they do not exist). */ #ifndef MHD_PLATFORM_H #if defined(_WIN32) && ! defined(__CYGWIN__) && \ ! defined(_CRT_DECLARE_NONSTDC_NAMES) /* Declare POSIX-compatible names */ #define _CRT_DECLARE_NONSTDC_NAMES 1 #endif /* _WIN32 && ! __CYGWIN__ && ! _CRT_DECLARE_NONSTDC_NAMES */ #include #include #include #if ! defined(_WIN32) || defined(__CYGWIN__) #include #include #include #else /* _WIN32 && ! __CYGWIN__ */ #include #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #endif /* _WIN32 && ! __CYGWIN__ */ #endif #if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET) /* Do not define __USE_W32_SOCKETS under Cygwin! */ #error Cygwin with winsock fd_set is not supported #endif #ifdef __has_attribute #if __has_attribute (flag_enum) #define _MHD_FLAGS_ENUM __attribute__((flag_enum)) #endif /* flag_enum */ #if __has_attribute (enum_extensibility) #define _MHD_FIXED_ENUM __attribute__((enum_extensibility (closed))) #endif /* enum_extensibility */ #endif /* __has_attribute */ #ifndef _MHD_FLAGS_ENUM #define _MHD_FLAGS_ENUM #endif /* _MHD_FLAGS_ENUM */ #ifndef _MHD_FIXED_ENUM #define _MHD_FIXED_ENUM #endif /* _MHD_FIXED_ENUM */ #define _MHD_FIXED_FLAGS_ENUM _MHD_FIXED_ENUM _MHD_FLAGS_ENUM /** * Operational results from MHD calls. */ enum MHD_Result { /** * MHD result code for "NO". */ MHD_NO = 0, /** * MHD result code for "YES". */ MHD_YES = 1 } _MHD_FIXED_ENUM; /** * Constant used to indicate unknown size (use when * creating a response). */ #ifdef UINT64_MAX #define MHD_SIZE_UNKNOWN UINT64_MAX #else #define MHD_SIZE_UNKNOWN ((uint64_t) -1LL) #endif #define MHD_CONTENT_READER_END_OF_STREAM ((ssize_t) -1) #define MHD_CONTENT_READER_END_WITH_ERROR ((ssize_t) -2) #ifndef _MHD_EXTERN #if defined(_WIN32) && defined(MHD_W32LIB) #define _MHD_EXTERN extern #elif defined(_WIN32) && defined(MHD_W32DLL) /* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */ #define _MHD_EXTERN __declspec(dllimport) #else #define _MHD_EXTERN extern #endif #endif #ifndef MHD_SOCKET_DEFINED /** * MHD_socket is type for socket FDs */ #if ! defined(_WIN32) || defined(_SYS_TYPES_FD_SET) #define MHD_POSIX_SOCKETS 1 typedef int MHD_socket; #define MHD_INVALID_SOCKET (-1) #else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_WINSOCK_SOCKETS 1 #include typedef SOCKET MHD_socket; #define MHD_INVALID_SOCKET (INVALID_SOCKET) #endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_SOCKET_DEFINED 1 #endif /* MHD_SOCKET_DEFINED */ /** * Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages */ #ifdef MHD_NO_DEPRECATION #define _MHD_DEPR_MACRO(msg) #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* MHD_NO_DEPRECATION */ #ifndef _MHD_DEPR_MACRO #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1500 /* VS 2008 or later */ /* Stringify macros */ #define _MHD_INSTRMACRO(a) #a #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) /* deprecation message */ #define _MHD_DEPR_MACRO(msg) \ __pragma \ (message (__FILE__ "(" _MHD_STRMACRO ( __LINE__) "): warning: " msg)) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #elif defined(__clang__) || defined(__GNUC_PATCHLEVEL__) /* clang or GCC since 3.0 */ #define _MHD_GCC_PRAG(x) _Pragma(#x) #if (defined(__clang__) && \ (__clang_major__ + 0 >= 5 || \ (! defined(__apple_build_version__) && \ (__clang_major__ + 0 > 3 || \ (__clang_major__ + 0 == 3 && __clang_minor__ >= 3))))) || \ __GNUC__ + 0 > 4 || (__GNUC__ + 0 == 4 && __GNUC_MINOR__ + 0 >= 8) /* clang >= 3.3 (or XCode's clang >= 5.0) or GCC >= 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (GCC warning msg) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #else /* older clang or GCC */ /* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (message msg) #if (defined(__clang__) && \ (__clang_major__ + 0 > 2 || \ (__clang_major__ + 0 == 2 && __clang_minor__ >= 9))) /* clang >= 2.9 */ /* clang handles inline pragmas better than GCC */ #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #endif /* clang >= 2.9 */ #endif /* older clang or GCC */ /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang || GCC >= 3.0 */ #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_MACRO #define _MHD_DEPR_MACRO(msg) #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_IN_MACRO #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #endif /* !_MHD_DEPR_IN_MACRO */ #ifndef _MHD_DEPR_FUNC #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1400 /* VS 2005 or later */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated (msg)) #elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1310 /* VS .NET 2003 deprecation does not support custom messages */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated) #elif (__GNUC__ + 0 >= 5) || (defined(__clang__) && \ (__clang_major__ + 0 > 2 || \ (__clang_major__ + 0 == 2 && __clang_minor__ >= 9))) /* GCC >= 5.0 or clang >= 2.9 */ #define _MHD_DEPR_FUNC(msg) __attribute__((deprecated (msg))) #elif defined(__clang__) || __GNUC__ + 0 > 3 || \ (__GNUC__ + 0 == 3 && __GNUC_MINOR__ + 0 >= 1) /* 3.1 <= GCC < 5.0 or clang < 2.9 */ /* old GCC-style deprecation does not support custom messages */ #define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__)) /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang < 2.9 || GCC >= 3.1 */ #endif /* !_MHD_DEPR_FUNC */ #ifndef _MHD_DEPR_FUNC #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* !_MHD_DEPR_FUNC */ /** * Not all architectures and `printf()`'s support the `long long` type. * This gives the ability to replace `long long` with just a `long`, * standard `int` or a `short`. */ #ifndef MHD_LONG_LONG /** * @deprecated use #MHD_UNSIGNED_LONG_LONG instead! */ #define MHD_LONG_LONG long long #define MHD_UNSIGNED_LONG_LONG unsigned long long #else /* MHD_LONG_LONG */ _MHD_DEPR_MACRO ( \ "Macro MHD_LONG_LONG is deprecated, use MHD_UNSIGNED_LONG_LONG") #endif /** * Format string for printing a variable of type #MHD_LONG_LONG. * You should only redefine this if you also define #MHD_LONG_LONG. */ #ifndef MHD_LONG_LONG_PRINTF /** * @deprecated use #MHD_UNSIGNED_LONG_LONG_PRINTF instead! */ #define MHD_LONG_LONG_PRINTF "ll" #define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu" #else /* MHD_LONG_LONG_PRINTF */ _MHD_DEPR_MACRO ( \ "Macro MHD_LONG_LONG_PRINTF is deprecated, use MHD_UNSIGNED_LONG_LONG_PRINTF") #endif /** * @defgroup httpcode HTTP response codes. * These are the status codes defined for HTTP responses. * See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * Registry export date: 2023-09-29 * @{ */ /* 100 "Continue". RFC9110, Section 15.2.1. */ #define MHD_HTTP_CONTINUE 100 /* 101 "Switching Protocols". RFC9110, Section 15.2.2. */ #define MHD_HTTP_SWITCHING_PROTOCOLS 101 /* 102 "Processing". RFC2518. */ #define MHD_HTTP_PROCESSING 102 /* 103 "Early Hints". RFC8297. */ #define MHD_HTTP_EARLY_HINTS 103 /* 200 "OK". RFC9110, Section 15.3.1. */ #define MHD_HTTP_OK 200 /* 201 "Created". RFC9110, Section 15.3.2. */ #define MHD_HTTP_CREATED 201 /* 202 "Accepted". RFC9110, Section 15.3.3. */ #define MHD_HTTP_ACCEPTED 202 /* 203 "Non-Authoritative Information". RFC9110, Section 15.3.4. */ #define MHD_HTTP_NON_AUTHORITATIVE_INFORMATION 203 /* 204 "No Content". RFC9110, Section 15.3.5. */ #define MHD_HTTP_NO_CONTENT 204 /* 205 "Reset Content". RFC9110, Section 15.3.6. */ #define MHD_HTTP_RESET_CONTENT 205 /* 206 "Partial Content". RFC9110, Section 15.3.7. */ #define MHD_HTTP_PARTIAL_CONTENT 206 /* 207 "Multi-Status". RFC4918. */ #define MHD_HTTP_MULTI_STATUS 207 /* 208 "Already Reported". RFC5842. */ #define MHD_HTTP_ALREADY_REPORTED 208 /* 226 "IM Used". RFC3229. */ #define MHD_HTTP_IM_USED 226 /* 300 "Multiple Choices". RFC9110, Section 15.4.1. */ #define MHD_HTTP_MULTIPLE_CHOICES 300 /* 301 "Moved Permanently". RFC9110, Section 15.4.2. */ #define MHD_HTTP_MOVED_PERMANENTLY 301 /* 302 "Found". RFC9110, Section 15.4.3. */ #define MHD_HTTP_FOUND 302 /* 303 "See Other". RFC9110, Section 15.4.4. */ #define MHD_HTTP_SEE_OTHER 303 /* 304 "Not Modified". RFC9110, Section 15.4.5. */ #define MHD_HTTP_NOT_MODIFIED 304 /* 305 "Use Proxy". RFC9110, Section 15.4.6. */ #define MHD_HTTP_USE_PROXY 305 /* 306 "Switch Proxy". Not used! RFC9110, Section 15.4.7. */ #define MHD_HTTP_SWITCH_PROXY 306 /* 307 "Temporary Redirect". RFC9110, Section 15.4.8. */ #define MHD_HTTP_TEMPORARY_REDIRECT 307 /* 308 "Permanent Redirect". RFC9110, Section 15.4.9. */ #define MHD_HTTP_PERMANENT_REDIRECT 308 /* 400 "Bad Request". RFC9110, Section 15.5.1. */ #define MHD_HTTP_BAD_REQUEST 400 /* 401 "Unauthorized". RFC9110, Section 15.5.2. */ #define MHD_HTTP_UNAUTHORIZED 401 /* 402 "Payment Required". RFC9110, Section 15.5.3. */ #define MHD_HTTP_PAYMENT_REQUIRED 402 /* 403 "Forbidden". RFC9110, Section 15.5.4. */ #define MHD_HTTP_FORBIDDEN 403 /* 404 "Not Found". RFC9110, Section 15.5.5. */ #define MHD_HTTP_NOT_FOUND 404 /* 405 "Method Not Allowed". RFC9110, Section 15.5.6. */ #define MHD_HTTP_METHOD_NOT_ALLOWED 405 /* 406 "Not Acceptable". RFC9110, Section 15.5.7. */ #define MHD_HTTP_NOT_ACCEPTABLE 406 /* 407 "Proxy Authentication Required". RFC9110, Section 15.5.8. */ #define MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED 407 /* 408 "Request Timeout". RFC9110, Section 15.5.9. */ #define MHD_HTTP_REQUEST_TIMEOUT 408 /* 409 "Conflict". RFC9110, Section 15.5.10. */ #define MHD_HTTP_CONFLICT 409 /* 410 "Gone". RFC9110, Section 15.5.11. */ #define MHD_HTTP_GONE 410 /* 411 "Length Required". RFC9110, Section 15.5.12. */ #define MHD_HTTP_LENGTH_REQUIRED 411 /* 412 "Precondition Failed". RFC9110, Section 15.5.13. */ #define MHD_HTTP_PRECONDITION_FAILED 412 /* 413 "Content Too Large". RFC9110, Section 15.5.14. */ #define MHD_HTTP_CONTENT_TOO_LARGE 413 /* 414 "URI Too Long". RFC9110, Section 15.5.15. */ #define MHD_HTTP_URI_TOO_LONG 414 /* 415 "Unsupported Media Type". RFC9110, Section 15.5.16. */ #define MHD_HTTP_UNSUPPORTED_MEDIA_TYPE 415 /* 416 "Range Not Satisfiable". RFC9110, Section 15.5.17. */ #define MHD_HTTP_RANGE_NOT_SATISFIABLE 416 /* 417 "Expectation Failed". RFC9110, Section 15.5.18. */ #define MHD_HTTP_EXPECTATION_FAILED 417 /* 421 "Misdirected Request". RFC9110, Section 15.5.20. */ #define MHD_HTTP_MISDIRECTED_REQUEST 421 /* 422 "Unprocessable Content". RFC9110, Section 15.5.21. */ #define MHD_HTTP_UNPROCESSABLE_CONTENT 422 /* 423 "Locked". RFC4918. */ #define MHD_HTTP_LOCKED 423 /* 424 "Failed Dependency". RFC4918. */ #define MHD_HTTP_FAILED_DEPENDENCY 424 /* 425 "Too Early". RFC8470. */ #define MHD_HTTP_TOO_EARLY 425 /* 426 "Upgrade Required". RFC9110, Section 15.5.22. */ #define MHD_HTTP_UPGRADE_REQUIRED 426 /* 428 "Precondition Required". RFC6585. */ #define MHD_HTTP_PRECONDITION_REQUIRED 428 /* 429 "Too Many Requests". RFC6585. */ #define MHD_HTTP_TOO_MANY_REQUESTS 429 /* 431 "Request Header Fields Too Large". RFC6585. */ #define MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE 431 /* 451 "Unavailable For Legal Reasons". RFC7725. */ #define MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451 /* 500 "Internal Server Error". RFC9110, Section 15.6.1. */ #define MHD_HTTP_INTERNAL_SERVER_ERROR 500 /* 501 "Not Implemented". RFC9110, Section 15.6.2. */ #define MHD_HTTP_NOT_IMPLEMENTED 501 /* 502 "Bad Gateway". RFC9110, Section 15.6.3. */ #define MHD_HTTP_BAD_GATEWAY 502 /* 503 "Service Unavailable". RFC9110, Section 15.6.4. */ #define MHD_HTTP_SERVICE_UNAVAILABLE 503 /* 504 "Gateway Timeout". RFC9110, Section 15.6.5. */ #define MHD_HTTP_GATEWAY_TIMEOUT 504 /* 505 "HTTP Version Not Supported". RFC9110, Section 15.6.6. */ #define MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED 505 /* 506 "Variant Also Negotiates". RFC2295. */ #define MHD_HTTP_VARIANT_ALSO_NEGOTIATES 506 /* 507 "Insufficient Storage". RFC4918. */ #define MHD_HTTP_INSUFFICIENT_STORAGE 507 /* 508 "Loop Detected". RFC5842. */ #define MHD_HTTP_LOOP_DETECTED 508 /* 510 "Not Extended". (OBSOLETED) RFC2774; status-change-http-experiments-to-historic. */ #define MHD_HTTP_NOT_EXTENDED 510 /* 511 "Network Authentication Required". RFC6585. */ #define MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED 511 /* Not registered non-standard codes */ /* 449 "Reply With". MS IIS extension. */ #define MHD_HTTP_RETRY_WITH 449 /* 450 "Blocked by Windows Parental Controls". MS extension. */ #define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450 /* 509 "Bandwidth Limit Exceeded". Apache extension. */ #define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED 509 /* Deprecated names and codes */ /** @deprecated */ #define MHD_HTTP_METHOD_NOT_ACCEPTABLE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, use MHD_HTTP_NOT_ACCEPTABLE" \ ) 406 /** @deprecated */ #define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, use MHD_HTTP_CONTENT_TOO_LARGE" \ ) 413 /** @deprecated */ #define MHD_HTTP_PAYLOAD_TOO_LARGE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_PAYLOAD_TOO_LARGE is deprecated use MHD_HTTP_CONTENT_TOO_LARGE" \ ) 413 /** @deprecated */ #define MHD_HTTP_REQUEST_URI_TOO_LONG _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, use MHD_HTTP_URI_TOO_LONG" \ ) 414 /** @deprecated */ #define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE" \ ) 416 /** @deprecated */ #define MHD_HTTP_UNPROCESSABLE_ENTITY _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_UNPROCESSABLE_ENTITY is deprecated, use MHD_HTTP_UNPROCESSABLE_CONTENT" \ ) 422 /** @deprecated */ #define MHD_HTTP_UNORDERED_COLLECTION _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_UNORDERED_COLLECTION is deprecated as it was removed from RFC" \ ) 425 /** @deprecated */ #define MHD_HTTP_NO_RESPONSE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_NO_RESPONSE is deprecated as it is nginx internal code for logs only" \ ) 444 /** @} */ /* end of group httpcode */ /** * Returns the string reason phrase for a response code. * * If message string is not available for a status code, * "Unknown" string will be returned. */ _MHD_EXTERN const char * MHD_get_reason_phrase_for (unsigned int code); /** * Returns the length of the string reason phrase for a response code. * * If message string is not available for a status code, * 0 is returned. */ _MHD_EXTERN size_t MHD_get_reason_phrase_len_for (unsigned int code); /** * Flag to be or-ed with MHD_HTTP status code for * SHOUTcast. This will cause the response to begin * with the SHOUTcast "ICY" line instead of "HTTP/1.x". * @ingroup specialized */ #define MHD_ICY_FLAG ((uint32_t) (((uint32_t) 1) << 31)) /** * @defgroup headers HTTP headers * The standard headers found in HTTP requests and responses. * See: https://www.iana.org/assignments/http-fields/http-fields.xhtml * Registry export date: 2023-10-02 * @{ */ /* Main HTTP headers. */ /* Permanent. RFC9110, Section 12.5.1: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT "Accept" /* Deprecated. RFC9110, Section 12.5.2: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset" /* Permanent. RFC9110, Section 12.5.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding" /* Permanent. RFC9110, Section 12.5.4: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language" /* Permanent. RFC9110, Section 14.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges" /* Permanent. RFC9111, Section 5.1: HTTP Caching */ #define MHD_HTTP_HEADER_AGE "Age" /* Permanent. RFC9110, Section 10.2.1: HTTP Semantics */ #define MHD_HTTP_HEADER_ALLOW "Allow" /* Permanent. RFC9110, Section 11.6.3: HTTP Semantics */ #define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info" /* Permanent. RFC9110, Section 11.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_AUTHORIZATION "Authorization" /* Permanent. RFC9111, Section 5.2 */ #define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control" /* Permanent. RFC9112, Section 9.6: HTTP/1.1 */ #define MHD_HTTP_HEADER_CLOSE "Close" /* Permanent. RFC9110, Section 7.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_CONNECTION "Connection" /* Permanent. RFC9110, Section 8.4: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding" /* Permanent. RFC9110, Section 8.5: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language" /* Permanent. RFC9110, Section 8.6: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length" /* Permanent. RFC9110, Section 8.7: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location" /* Permanent. RFC9110, Section 14.4: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range" /* Permanent. RFC9110, Section 8.3: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type" /* Permanent. RFC9110, Section 6.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_DATE "Date" /* Permanent. RFC9110, Section 8.8.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ETAG "ETag" /* Permanent. RFC9110, Section 10.1.1: HTTP Semantics */ #define MHD_HTTP_HEADER_EXPECT "Expect" /* Permanent. RFC9111, Section 5.3: HTTP Caching */ #define MHD_HTTP_HEADER_EXPIRES "Expires" /* Permanent. RFC9110, Section 10.1.2: HTTP Semantics */ #define MHD_HTTP_HEADER_FROM "From" /* Permanent. RFC9110, Section 7.2: HTTP Semantics */ #define MHD_HTTP_HEADER_HOST "Host" /* Permanent. RFC9110, Section 13.1.1: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_MATCH "If-Match" /* Permanent. RFC9110, Section 13.1.3: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since" /* Permanent. RFC9110, Section 13.1.2: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match" /* Permanent. RFC9110, Section 13.1.5: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_RANGE "If-Range" /* Permanent. RFC9110, Section 13.1.4: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since" /* Permanent. RFC9110, Section 8.8.2: HTTP Semantics */ #define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified" /* Permanent. RFC9110, Section 10.2.2: HTTP Semantics */ #define MHD_HTTP_HEADER_LOCATION "Location" /* Permanent. RFC9110, Section 7.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards" /* Permanent. RFC9112, Appendix B.1: HTTP/1.1 */ #define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version" /* Deprecated. RFC9111, Section 5.4: HTTP Caching */ #define MHD_HTTP_HEADER_PRAGMA "Pragma" /* Permanent. RFC9110, Section 11.7.1: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate" /* Permanent. RFC9110, Section 11.7.3: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info" /* Permanent. RFC9110, Section 11.7.2: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization" /* Permanent. RFC9110, Section 14.2: HTTP Semantics */ #define MHD_HTTP_HEADER_RANGE "Range" /* Permanent. RFC9110, Section 10.1.3: HTTP Semantics */ #define MHD_HTTP_HEADER_REFERER "Referer" /* Permanent. RFC9110, Section 10.2.3: HTTP Semantics */ #define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After" /* Permanent. RFC9110, Section 10.2.4: HTTP Semantics */ #define MHD_HTTP_HEADER_SERVER "Server" /* Permanent. RFC9110, Section 10.1.4: HTTP Semantics */ #define MHD_HTTP_HEADER_TE "TE" /* Permanent. RFC9110, Section 6.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_TRAILER "Trailer" /* Permanent. RFC9112, Section 6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" /* Permanent. RFC9110, Section 7.8: HTTP Semantics */ #define MHD_HTTP_HEADER_UPGRADE "Upgrade" /* Permanent. RFC9110, Section 10.1.5: HTTP Semantics */ #define MHD_HTTP_HEADER_USER_AGENT "User-Agent" /* Permanent. RFC9110, Section 12.5.5: HTTP Semantics */ #define MHD_HTTP_HEADER_VARY "Vary" /* Permanent. RFC9110, Section 7.6.3: HTTP Semantics */ #define MHD_HTTP_HEADER_VIA "Via" /* Permanent. RFC9110, Section 11.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate" /* Permanent. RFC9110, Section 12.5.5: HTTP Semantics */ #define MHD_HTTP_HEADER_ASTERISK "*" /* Additional HTTP headers. */ /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_A_IM "A-IM" /* Permanent. RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) */ #define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions" /* Permanent. RFC 8942, Section 3.1: HTTP Client Hints */ #define MHD_HTTP_HEADER_ACCEPT_CH "Accept-CH" /* Permanent. RFC 7089: HTTP Framework for Time-Based Access to Resource States -- Memento */ #define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features" /* Permanent. RFC 5789: PATCH Method for HTTP */ #define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch" /* Permanent. Linked Data Platform 1.0 */ #define MHD_HTTP_HEADER_ACCEPT_POST "Accept-Post" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 5.1: HTTP Message Signatures */ #define MHD_HTTP_HEADER_ACCEPT_SIGNATURE "Accept-Signature" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS \ "Access-Control-Allow-Credentials" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS \ "Access-Control-Allow-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_METHODS \ "Access-Control-Allow-Methods" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \ "Access-Control-Allow-Origin" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS \ "Access-Control-Expose-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_MAX_AGE "Access-Control-Max-Age" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_HEADERS \ "Access-Control-Request-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_METHOD \ "Access-Control-Request-Method" /* Permanent. RFC 7639, Section 2: The ALPN HTTP Header Field */ #define MHD_HTTP_HEADER_ALPN "ALPN" /* Permanent. RFC 7838: HTTP Alternative Services */ #define MHD_HTTP_HEADER_ALT_SVC "Alt-Svc" /* Permanent. RFC 7838: HTTP Alternative Services */ #define MHD_HTTP_HEADER_ALT_USED "Alt-Used" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_ALTERNATES "Alternates" /* Permanent. RFC 4437: Web Distributed Authoring and Versioning (WebDAV) Redirect Reference Resources */ #define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref" /* Permanent. RFC 8053, Section 4: HTTP Authentication Extensions for Interactive Clients */ #define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control" /* Permanent. RFC9211: The Cache-Status HTTP Response Header Field */ #define MHD_HTTP_HEADER_CACHE_STATUS "Cache-Status" /* Permanent. RFC 8607, Section 5.1: Calendaring Extensions to WebDAV (CalDAV): Managed Attachments */ #define MHD_HTTP_HEADER_CAL_MANAGED_ID "Cal-Managed-ID" /* Permanent. RFC 7809, Section 7.1: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference */ #define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones" /* Permanent. RFC9297 */ #define MHD_HTTP_HEADER_CAPSULE_PROTOCOL "Capsule-Protocol" /* Permanent. RFC9213: Targeted HTTP Cache Control */ #define MHD_HTTP_HEADER_CDN_CACHE_CONTROL "CDN-Cache-Control" /* Permanent. RFC 8586: Loop Detection in Content Delivery Networks (CDNs) */ #define MHD_HTTP_HEADER_CDN_LOOP "CDN-Loop" /* Permanent. RFC 8739, Section 3.3: Support for Short-Term, Automatically Renewed (STAR) Certificates in the Automated Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_CERT_NOT_AFTER "Cert-Not-After" /* Permanent. RFC 8739, Section 3.3: Support for Short-Term, Automatically Renewed (STAR) Certificates in the Automated Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_CERT_NOT_BEFORE "Cert-Not-Before" /* Permanent. Clear Site Data */ #define MHD_HTTP_HEADER_CLEAR_SITE_DATA "Clear-Site-Data" /* Permanent. RFC9440, Section 2: Client-Cert HTTP Header Field */ #define MHD_HTTP_HEADER_CLIENT_CERT "Client-Cert" /* Permanent. RFC9440, Section 2: Client-Cert HTTP Header Field */ #define MHD_HTTP_HEADER_CLIENT_CERT_CHAIN "Client-Cert-Chain" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 2: Digest Fields */ #define MHD_HTTP_HEADER_CONTENT_DIGEST "Content-Digest" /* Permanent. RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP) */ #define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition" /* Permanent. The HTTP Distribution and Replication Protocol */ #define MHD_HTTP_HEADER_CONTENT_ID "Content-ID" /* Permanent. Content Security Policy Level 3 */ #define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY "Content-Security-Policy" /* Permanent. Content Security Policy Level 3 */ #define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY_REPORT_ONLY \ "Content-Security-Policy-Report-Only" /* Permanent. RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_COOKIE "Cookie" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY \ "Cross-Origin-Embedder-Policy" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY \ "Cross-Origin-Embedder-Policy-Report-Only" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY "Cross-Origin-Opener-Policy" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY_REPORT_ONLY \ "Cross-Origin-Opener-Policy-Report-Only" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_RESOURCE_POLICY \ "Cross-Origin-Resource-Policy" /* Permanent. RFC 5323: Web Distributed Authoring and Versioning (WebDAV) SEARCH */ #define MHD_HTTP_HEADER_DASL "DASL" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DAV "DAV" /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_DELTA_BASE "Delta-Base" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DEPTH "Depth" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DESTINATION "Destination" /* Permanent. The HTTP Distribution and Replication Protocol */ #define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID" /* Permanent. RFC9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP) */ #define MHD_HTTP_HEADER_DPOP "DPoP" /* Permanent. RFC9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP) */ #define MHD_HTTP_HEADER_DPOP_NONCE "DPoP-Nonce" /* Permanent. RFC 8470: Using Early Data in HTTP */ #define MHD_HTTP_HEADER_EARLY_DATA "Early-Data" /* Permanent. RFC9163: Expect-CT Extension for HTTP */ #define MHD_HTTP_HEADER_EXPECT_CT "Expect-CT" /* Permanent. RFC 7239: Forwarded HTTP Extension */ #define MHD_HTTP_HEADER_FORWARDED "Forwarded" /* Permanent. RFC 7486, Section 6.1.1: HTTP Origin-Bound Authentication (HOBA) */ #define MHD_HTTP_HEADER_HOBAREG "Hobareg" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_IF "If" /* Permanent. RFC 6338: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match" /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_IM "IM" /* Permanent. RFC 8473: Token Binding over HTTP */ #define MHD_HTTP_HEADER_INCLUDE_REFERRED_TOKEN_BINDING_ID \ "Include-Referred-Token-Binding-ID" /* Permanent. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_KEEP_ALIVE "Keep-Alive" /* Permanent. RFC 3253: Versioning Extensions to WebDAV: (Web Distributed Authoring and Versioning) */ #define MHD_HTTP_HEADER_LABEL "Label" /* Permanent. HTML */ #define MHD_HTTP_HEADER_LAST_EVENT_ID "Last-Event-ID" /* Permanent. RFC 8288: Web Linking */ #define MHD_HTTP_HEADER_LINK "Link" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_LOCK_TOKEN "Lock-Token" /* Permanent. RFC 7089: HTTP Framework for Time-Based Access to Resource States -- Memento */ #define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime" /* Permanent. RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP */ #define MHD_HTTP_HEADER_METER "Meter" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_NEGOTIATE "Negotiate" /* Permanent. Network Error Logging */ #define MHD_HTTP_HEADER_NEL "NEL" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_ENTITYID "OData-EntityId" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_ISOLATION "OData-Isolation" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_MAXVERSION "OData-MaxVersion" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_VERSION "OData-Version" /* Permanent. RFC 8053, Section 3: HTTP Authentication Extensions for Interactive Clients */ #define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate" /* Permanent. RFC 3648: Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol */ #define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type" /* Permanent. RFC 6454: The Web Origin Concept */ #define MHD_HTTP_HEADER_ORIGIN "Origin" /* Permanent. HTML */ #define MHD_HTTP_HEADER_ORIGIN_AGENT_CLUSTER "Origin-Agent-Cluster" /* Permanent. RFC 8613, Section 11.1: Object Security for Constrained RESTful Environments (OSCORE) */ #define MHD_HTTP_HEADER_OSCORE "OSCORE" /* Permanent. OASIS Project Specification 01; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_OSLC_CORE_VERSION "OSLC-Core-Version" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_OVERWRITE "Overwrite" /* Permanent. HTML */ #define MHD_HTTP_HEADER_PING_FROM "Ping-From" /* Permanent. HTML */ #define MHD_HTTP_HEADER_PING_TO "Ping-To" /* Permanent. RFC 3648: Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol */ #define MHD_HTTP_HEADER_POSITION "Position" /* Permanent. RFC 7240: Prefer Header for HTTP */ #define MHD_HTTP_HEADER_PREFER "Prefer" /* Permanent. RFC 7240: Prefer Header for HTTP */ #define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied" /* Permanent. RFC9218: Extensible Prioritization Scheme for HTTP */ #define MHD_HTTP_HEADER_PRIORITY "Priority" /* Permanent. RFC9209: The Proxy-Status HTTP Response Header Field */ #define MHD_HTTP_HEADER_PROXY_STATUS "Proxy-Status" /* Permanent. RFC 7469: Public Key Pinning Extension for HTTP */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins" /* Permanent. RFC 7469: Public Key Pinning Extension for HTTP */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY \ "Public-Key-Pins-Report-Only" /* Permanent. RFC 4437: Web Distributed Authoring and Versioning (WebDAV) Redirect Reference Resources */ #define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref" /* Permanent. HTML */ #define MHD_HTTP_HEADER_REFRESH "Refresh" /* Permanent. RFC 8555, Section 6.5.1: Automatic Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_REPLAY_NONCE "Replay-Nonce" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 3: Digest Fields */ #define MHD_HTTP_HEADER_REPR_DIGEST "Repr-Digest" /* Permanent. RFC 6638: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply" /* Permanent. RFC 6338: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_SEC_PURPOSE "Sec-Purpose" /* Permanent. RFC 8473: Token Binding over HTTP */ #define MHD_HTTP_HEADER_SEC_TOKEN_BINDING "Sec-Token-Binding" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version" /* Permanent. Server Timing */ #define MHD_HTTP_HEADER_SERVER_TIMING "Server-Timing" /* Permanent. RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 4.2: HTTP Message Signatures */ #define MHD_HTTP_HEADER_SIGNATURE "Signature" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 4.1: HTTP Message Signatures */ #define MHD_HTTP_HEADER_SIGNATURE_INPUT "Signature-Input" /* Permanent. RFC 5023: The Atom Publishing Protocol */ #define MHD_HTTP_HEADER_SLUG "SLUG" /* Permanent. Simple Object Access Protocol (SOAP) 1.1 */ #define MHD_HTTP_HEADER_SOAPACTION "SoapAction" /* Permanent. RFC 2518: HTTP Extensions for Distributed Authoring -- WEBDAV */ #define MHD_HTTP_HEADER_STATUS_URI "Status-URI" /* Permanent. RFC 6797: HTTP Strict Transport Security (HSTS) */ #define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security" /* Permanent. RFC 8594: The Sunset HTTP Header Field */ #define MHD_HTTP_HEADER_SUNSET "Sunset" /* Permanent. Edge Architecture Specification */ #define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability" /* Permanent. Edge Architecture Specification */ #define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_TCN "TCN" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_TIMEOUT "Timeout" /* Permanent. RFC 8030, Section 5.4: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_TOPIC "Topic" /* Permanent. Trace Context */ #define MHD_HTTP_HEADER_TRACEPARENT "Traceparent" /* Permanent. Trace Context */ #define MHD_HTTP_HEADER_TRACESTATE "Tracestate" /* Permanent. RFC 8030, Section 5.2: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_TTL "TTL" /* Permanent. RFC 8030, Section 5.3: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_URGENCY "Urgency" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 4: Digest Fields */ #define MHD_HTTP_HEADER_WANT_CONTENT_DIGEST "Want-Content-Digest" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 4: Digest Fields */ #define MHD_HTTP_HEADER_WANT_REPR_DIGEST "Want-Repr-Digest" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_X_CONTENT_TYPE_OPTIONS "X-Content-Type-Options" /* Permanent. HTML */ #define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options" /* Provisional. AMP-Cache-Transform HTTP request header */ #define MHD_HTTP_HEADER_AMP_CACHE_TRANSFORM "AMP-Cache-Transform" /* Provisional. OSLC Configuration Management Version 1.0. Part 3: Configuration Specification */ #define MHD_HTTP_HEADER_CONFIGURATION_CONTEXT "Configuration-Context" /* Provisional. RFC 6017: Electronic Data Interchange - Internet Integration (EDIINT) Features Header Field */ #define MHD_HTTP_HEADER_EDIINT_FEATURES "EDIINT-Features" /* Provisional. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ISOLATION "Isolation" /* Provisional. Permissions Policy */ #define MHD_HTTP_HEADER_PERMISSIONS_POLICY "Permissions-Policy" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_CLIENT_ID "Repeatability-Client-ID" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_FIRST_SENT "Repeatability-First-Sent" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_REQUEST_ID "Repeatability-Request-ID" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_RESULT "Repeatability-Result" /* Provisional. Reporting API */ #define MHD_HTTP_HEADER_REPORTING_ENDPOINTS "Reporting-Endpoints" /* Provisional. Global Privacy Control (GPC) */ #define MHD_HTTP_HEADER_SEC_GPC "Sec-GPC" /* Provisional. Resource Timing Level 1 */ #define MHD_HTTP_HEADER_TIMING_ALLOW_ORIGIN "Timing-Allow-Origin" /* Deprecated. PEP - an Extension Mechanism for HTTP; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_PEP_INFO "C-PEP-Info" /* Deprecated. White Paper: Joint Electronic Payment Initiative */ #define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info" /* Deprecated. White Paper: Joint Electronic Payment Initiative */ #define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_ACCESS_CONTROL "Access-Control" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_EXT "C-Ext" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_MAN "C-Man" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_OPT "C-Opt" /* Obsoleted. PEP - an Extension Mechanism for HTTP; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_PEP "C-PEP" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1; RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base" /* Obsoleted. RFC 2616, Section 14.15: Hypertext Transfer Protocol -- HTTP/1.1; RFC 7231, Appendix B: Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content */ #define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version" /* Obsoleted. RFC 2965: HTTP State Management Mechanism; RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_COOKIE2 "Cookie2" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From" /* Obsoleted. RFC 3230: Instance Digests in HTTP; RFC-ietf-httpbis-digest-headers-13, Section 1.3: Digest Fields */ #define MHD_HTTP_HEADER_DIGEST "Digest" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_EXT "Ext" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_GETPROFILE "GetProfile" /* Obsoleted. RFC 7540, Section 3.2.1: Hypertext Transfer Protocol Version 2 (HTTP/2) */ #define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_MAN "Man" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_METHOD_CHECK "Method-Check" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_METHOD_CHECK_EXPIRES "Method-Check-Expires" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_OPT "Opt" /* Obsoleted. The Platform for Privacy Preferences 1.0 (P3P1.0) Specification */ #define MHD_HTTP_HEADER_P3P "P3P" /* Obsoleted. PEP - an Extension Mechanism for HTTP */ #define MHD_HTTP_HEADER_PEP "PEP" /* Obsoleted. PEP - an Extension Mechanism for HTTP */ #define MHD_HTTP_HEADER_PEP_INFO "Pep-Info" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PICS_LABEL "PICS-Label" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PROTOCOL "Protocol" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request" /* Obsoleted. Notification for Proxy Caches */ #define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features" /* Obsoleted. Notification for Proxy Caches */ #define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_PUBLIC "Public" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_REFERER_ROOT "Referer-Root" /* Obsoleted. RFC 2310: The Safe Response Header Field; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_SAFE "Safe" /* Obsoleted. RFC 2660: The Secure HyperText Transfer Protocol; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme" /* Obsoleted. RFC 2965: HTTP State Management Mechanism; RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_SETPROFILE "SetProfile" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_URI "URI" /* Obsoleted. RFC 3230: Instance Digests in HTTP; RFC-ietf-httpbis-digest-headers-13, Section 1.3: Digest Fields */ #define MHD_HTTP_HEADER_WANT_DIGEST "Want-Digest" /* Obsoleted. RFC9111, Section 5.5: HTTP Caching */ #define MHD_HTTP_HEADER_WARNING "Warning" /* Headers removed from the registry. Do not use! */ /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_COMPLIANCE "Compliance" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_TRANSFER_ENCODING "Content-Transfer-Encoding" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_COST "Cost" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_MESSAGE_ID "Message-ID" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_NON_COMPLIANCE "Non-Compliance" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_OPTIONAL "Optional" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_RESOLUTION_HINT "Resolution-Hint" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_RESOLVER_LOCATION "Resolver-Location" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_SUBOK "SubOK" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_SUBST "Subst" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_TITLE "Title" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_COLOR "UA-Color" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_MEDIA "UA-Media" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_PIXELS "UA-Pixels" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_RESOLUTION "UA-Resolution" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_WINDOWPIXELS "UA-Windowpixels" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_VERSION "Version" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT "X-Device-Accept" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_CHARSET "X-Device-Accept-Charset" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_ENCODING "X-Device-Accept-Encoding" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_LANGUAGE "X-Device-Accept-Language" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_USER_AGENT "X-Device-User-Agent" /** @} */ /* end of group headers */ /** * @defgroup versions HTTP versions * These strings should be used to match against the first line of the * HTTP header. * @{ */ #define MHD_HTTP_VERSION_1_0 "HTTP/1.0" #define MHD_HTTP_VERSION_1_1 "HTTP/1.1" /** @} */ /* end of group versions */ /** * @defgroup methods HTTP methods * HTTP methods (as strings). * See: https://www.iana.org/assignments/http-methods/http-methods.xml * Registry export date: 2023-10-02 * @{ */ /* Main HTTP methods. */ /* Safe. Idempotent. RFC9110, Section 9.3.1. */ #define MHD_HTTP_METHOD_GET "GET" /* Safe. Idempotent. RFC9110, Section 9.3.2. */ #define MHD_HTTP_METHOD_HEAD "HEAD" /* Not safe. Not idempotent. RFC9110, Section 9.3.3. */ #define MHD_HTTP_METHOD_POST "POST" /* Not safe. Idempotent. RFC9110, Section 9.3.4. */ #define MHD_HTTP_METHOD_PUT "PUT" /* Not safe. Idempotent. RFC9110, Section 9.3.5. */ #define MHD_HTTP_METHOD_DELETE "DELETE" /* Not safe. Not idempotent. RFC9110, Section 9.3.6. */ #define MHD_HTTP_METHOD_CONNECT "CONNECT" /* Safe. Idempotent. RFC9110, Section 9.3.7. */ #define MHD_HTTP_METHOD_OPTIONS "OPTIONS" /* Safe. Idempotent. RFC9110, Section 9.3.8. */ #define MHD_HTTP_METHOD_TRACE "TRACE" /* Additional HTTP methods. */ /* Not safe. Idempotent. RFC3744, Section 8.1. */ #define MHD_HTTP_METHOD_ACL "ACL" /* Not safe. Idempotent. RFC3253, Section 12.6. */ #define MHD_HTTP_METHOD_BASELINE_CONTROL "BASELINE-CONTROL" /* Not safe. Idempotent. RFC5842, Section 4. */ #define MHD_HTTP_METHOD_BIND "BIND" /* Not safe. Idempotent. RFC3253, Section 4.4, Section 9.4. */ #define MHD_HTTP_METHOD_CHECKIN "CHECKIN" /* Not safe. Idempotent. RFC3253, Section 4.3, Section 8.8. */ #define MHD_HTTP_METHOD_CHECKOUT "CHECKOUT" /* Not safe. Idempotent. RFC4918, Section 9.8. */ #define MHD_HTTP_METHOD_COPY "COPY" /* Not safe. Idempotent. RFC3253, Section 8.2. */ #define MHD_HTTP_METHOD_LABEL "LABEL" /* Not safe. Idempotent. RFC2068, Section 19.6.1.2. */ #define MHD_HTTP_METHOD_LINK "LINK" /* Not safe. Not idempotent. RFC4918, Section 9.10. */ #define MHD_HTTP_METHOD_LOCK "LOCK" /* Not safe. Idempotent. RFC3253, Section 11.2. */ #define MHD_HTTP_METHOD_MERGE "MERGE" /* Not safe. Idempotent. RFC3253, Section 13.5. */ #define MHD_HTTP_METHOD_MKACTIVITY "MKACTIVITY" /* Not safe. Idempotent. RFC4791, Section 5.3.1; RFC8144, Section 2.3. */ #define MHD_HTTP_METHOD_MKCALENDAR "MKCALENDAR" /* Not safe. Idempotent. RFC4918, Section 9.3; RFC5689, Section 3; RFC8144, Section 2.3. */ #define MHD_HTTP_METHOD_MKCOL "MKCOL" /* Not safe. Idempotent. RFC4437, Section 6. */ #define MHD_HTTP_METHOD_MKREDIRECTREF "MKREDIRECTREF" /* Not safe. Idempotent. RFC3253, Section 6.3. */ #define MHD_HTTP_METHOD_MKWORKSPACE "MKWORKSPACE" /* Not safe. Idempotent. RFC4918, Section 9.9. */ #define MHD_HTTP_METHOD_MOVE "MOVE" /* Not safe. Idempotent. RFC3648, Section 7. */ #define MHD_HTTP_METHOD_ORDERPATCH "ORDERPATCH" /* Not safe. Not idempotent. RFC5789, Section 2. */ #define MHD_HTTP_METHOD_PATCH "PATCH" /* Safe. Idempotent. RFC9113, Section 3.4. */ #define MHD_HTTP_METHOD_PRI "PRI" /* Safe. Idempotent. RFC4918, Section 9.1; RFC8144, Section 2.1. */ #define MHD_HTTP_METHOD_PROPFIND "PROPFIND" /* Not safe. Idempotent. RFC4918, Section 9.2; RFC8144, Section 2.2. */ #define MHD_HTTP_METHOD_PROPPATCH "PROPPATCH" /* Not safe. Idempotent. RFC5842, Section 6. */ #define MHD_HTTP_METHOD_REBIND "REBIND" /* Safe. Idempotent. RFC3253, Section 3.6; RFC8144, Section 2.1. */ #define MHD_HTTP_METHOD_REPORT "REPORT" /* Safe. Idempotent. RFC5323, Section 2. */ #define MHD_HTTP_METHOD_SEARCH "SEARCH" /* Not safe. Idempotent. RFC5842, Section 5. */ #define MHD_HTTP_METHOD_UNBIND "UNBIND" /* Not safe. Idempotent. RFC3253, Section 4.5. */ #define MHD_HTTP_METHOD_UNCHECKOUT "UNCHECKOUT" /* Not safe. Idempotent. RFC2068, Section 19.6.1.3. */ #define MHD_HTTP_METHOD_UNLINK "UNLINK" /* Not safe. Idempotent. RFC4918, Section 9.11. */ #define MHD_HTTP_METHOD_UNLOCK "UNLOCK" /* Not safe. Idempotent. RFC3253, Section 7.1. */ #define MHD_HTTP_METHOD_UPDATE "UPDATE" /* Not safe. Idempotent. RFC4437, Section 7. */ #define MHD_HTTP_METHOD_UPDATEREDIRECTREF "UPDATEREDIRECTREF" /* Not safe. Idempotent. RFC3253, Section 3.5. */ #define MHD_HTTP_METHOD_VERSION_CONTROL "VERSION-CONTROL" /* Not safe. Not idempotent. RFC9110, Section 18.2. */ #define MHD_HTTP_METHOD_ASTERISK "*" /** @} */ /* end of group methods */ /** * @defgroup postenc HTTP POST encodings * See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 * @{ */ #define MHD_HTTP_POST_ENCODING_FORM_URLENCODED \ "application/x-www-form-urlencoded" #define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data" /** @} */ /* end of group postenc */ /** * @brief Handle for the daemon (listening on a socket for HTTP traffic). * @ingroup event */ struct MHD_Daemon; /** * @brief Handle for a connection / HTTP request. * * With HTTP/1.1, multiple requests can be run over the same * connection. However, MHD will only show one request per TCP * connection to the client at any given time. * @ingroup request */ struct MHD_Connection; /** * @brief Handle for a response. * @ingroup response */ struct MHD_Response; /** * @brief Handle for POST processing. * @ingroup response */ struct MHD_PostProcessor; /** * @brief Flags for the `struct MHD_Daemon`. * * Note that MHD will run automatically in background thread(s) only * if #MHD_USE_INTERNAL_POLLING_THREAD is used. Otherwise caller (application) * must use #MHD_run() or #MHD_run_from_select() to have MHD processed * network connections and data. * * Starting the daemon may also fail if a particular option is not * implemented or not supported on the target platform (i.e. no * support for TLS, epoll or IPv6). */ enum MHD_FLAG { /** * No options selected. */ MHD_NO_FLAG = 0, /** * Print errors messages to custom error logger or to `stderr` if * custom error logger is not set. * @sa ::MHD_OPTION_EXTERNAL_LOGGER */ MHD_USE_ERROR_LOG = 1, /** * Run in debug mode. If this flag is used, the library should * print error messages and warnings to `stderr`. */ MHD_USE_DEBUG = 1, /** * Run in HTTPS mode. The modern protocol is called TLS. */ MHD_USE_TLS = 2, /** @deprecated */ MHD_USE_SSL = 2, #if 0 /* let's do this later once versions that define MHD_USE_TLS a more widely deployed. */ #define MHD_USE_SSL \ _MHD_DEPR_IN_MACRO ("Value MHD_USE_SSL is deprecated, use MHD_USE_TLS") \ MHD_USE_TLS #endif /** * Run using one thread per connection. * Must be used only with #MHD_USE_INTERNAL_POLLING_THREAD. * * If #MHD_USE_ITC is also not used, closed and expired connections may only * be cleaned up internally when a new connection is received. * Consider adding of #MHD_USE_ITC flag to have faster internal cleanups * at very minor increase in system resources usage. */ MHD_USE_THREAD_PER_CONNECTION = 4, /** * Run using an internal thread (or thread pool) for sockets sending * and receiving and data processing. Without this flag MHD will not * run automatically in background thread(s). * If this flag is set, #MHD_run() and #MHD_run_from_select() couldn't * be used. * This flag is set explicitly by #MHD_USE_POLL_INTERNAL_THREAD and * by #MHD_USE_EPOLL_INTERNAL_THREAD. * When this flag is not set, MHD run in "external" polling mode. */ MHD_USE_INTERNAL_POLLING_THREAD = 8, /** @deprecated */ MHD_USE_SELECT_INTERNALLY = 8, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_SELECT_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_SELECT_INTERNALLY is deprecated, use MHD_USE_INTERNAL_POLLING_THREAD instead") \ MHD_USE_INTERNAL_POLLING_THREAD #endif /* 0 */ /** * Run using the IPv6 protocol (otherwise, MHD will just support * IPv4). If you want MHD to support IPv4 and IPv6 using a single * socket, pass #MHD_USE_DUAL_STACK, otherwise, if you only pass * this option, MHD will try to bind to IPv6-only (resulting in * no IPv4 support). */ MHD_USE_IPv6 = 16, /** * Be pedantic about the protocol (as opposed to as tolerant as * possible). * This flag is equivalent to setting 1 as #MHD_OPTION_CLIENT_DISCIPLINE_LVL * value. * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ MHD_USE_PEDANTIC_CHECKS = 32, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_PEDANTIC_CHECKS \ _MHD_DEPR_IN_MACRO ( \ "Flag MHD_USE_PEDANTIC_CHECKS is deprecated, " \ "use option MHD_OPTION_CLIENT_DISCIPLINE_LVL instead") \ 32 #endif /* 0 */ /** * Use `poll()` instead of `select()` for polling sockets. * This allows sockets with `fd >= FD_SETSIZE`. * This option is not compatible with an "external" polling mode * (as there is no API to get the file descriptors for the external * poll() from MHD) and must also not be used in combination * with #MHD_USE_EPOLL. * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL_INTERNAL_THREAD */ MHD_USE_POLL = 64, /** * Run using an internal thread (or thread pool) doing `poll()`. * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL, #MHD_USE_INTERNAL_POLLING_THREAD */ MHD_USE_POLL_INTERNAL_THREAD = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_POLL_INTERNALLY = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_POLL_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_POLL_INTERNALLY is deprecated, use MHD_USE_POLL_INTERNAL_THREAD instead") \ MHD_USE_POLL_INTERNAL_THREAD #endif /* 0 */ /** * Suppress (automatically) adding the 'Date:' header to HTTP responses. * This option should ONLY be used on systems that do not have a clock * and that DO provide other mechanisms for cache control. See also * RFC 2616, section 14.18 (exception 3). */ MHD_USE_SUPPRESS_DATE_NO_CLOCK = 128, /** @deprecated */ MHD_SUPPRESS_DATE_NO_CLOCK = 128, #if 0 /* Will be marked for real deprecation later. */ #define MHD_SUPPRESS_DATE_NO_CLOCK \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_SUPPRESS_DATE_NO_CLOCK is deprecated, use MHD_USE_SUPPRESS_DATE_NO_CLOCK instead") \ MHD_USE_SUPPRESS_DATE_NO_CLOCK #endif /* 0 */ /** * Run without a listen socket. This option only makes sense if * #MHD_add_connection is to be used exclusively to connect HTTP * clients to the HTTP server. This option is incompatible with * using a thread pool; if it is used, #MHD_OPTION_THREAD_POOL_SIZE * is ignored. */ MHD_USE_NO_LISTEN_SOCKET = 256, /** * Use `epoll()` instead of `select()` or `poll()` for the event loop. * This option is only available on some systems; using the option on * systems without epoll will cause #MHD_start_daemon to fail. Using * this option is not supported with #MHD_USE_THREAD_PER_CONNECTION. * @sa ::MHD_FEATURE_EPOLL */ MHD_USE_EPOLL = 512, /** @deprecated */ MHD_USE_EPOLL_LINUX_ONLY = 512, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_LINUX_ONLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_LINUX_ONLY is deprecated, use MHD_USE_EPOLL") \ MHD_USE_EPOLL #endif /* 0 */ /** * Run using an internal thread (or thread pool) doing `epoll` polling. * This option is only available on certain platforms; using the option on * platform without `epoll` support will cause #MHD_start_daemon to fail. * @sa ::MHD_FEATURE_EPOLL, #MHD_USE_EPOLL, #MHD_USE_INTERNAL_POLLING_THREAD */ MHD_USE_EPOLL_INTERNAL_THREAD = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_EPOLL_INTERNALLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_INTERNALLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \ MHD_USE_EPOLL_INTERNAL_THREAD /** @deprecated */ #define MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \ MHD_USE_EPOLL_INTERNAL_THREAD #endif /* 0 */ /** * Use inter-thread communication channel. * #MHD_USE_ITC can be used with #MHD_USE_INTERNAL_POLLING_THREAD * and is ignored with any "external" sockets polling. * It's required for use of #MHD_quiesce_daemon * or #MHD_add_connection. * This option is enforced by #MHD_ALLOW_SUSPEND_RESUME or * #MHD_USE_NO_LISTEN_SOCKET. * #MHD_USE_ITC is always used automatically on platforms * where select()/poll()/other ignore shutdown of listen * socket. */ MHD_USE_ITC = 1024, /** @deprecated */ MHD_USE_PIPE_FOR_SHUTDOWN = 1024, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_PIPE_FOR_SHUTDOWN \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_PIPE_FOR_SHUTDOWN is deprecated, use MHD_USE_ITC") \ MHD_USE_ITC #endif /* 0 */ /** * Use a single socket for IPv4 and IPv6. */ MHD_USE_DUAL_STACK = MHD_USE_IPv6 | 2048, /** * Enable `turbo`. Disables certain calls to `shutdown()`, * enables aggressive non-blocking optimistic reads and * other potentially unsafe optimizations. * Most effects only happen with #MHD_USE_EPOLL. */ MHD_USE_TURBO = 4096, /** @deprecated */ MHD_USE_EPOLL_TURBO = 4096, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_TURBO \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_TURBO is deprecated, use MHD_USE_TURBO") \ MHD_USE_TURBO #endif /* 0 */ /** * Enable suspend/resume functions, which also implies setting up * ITC to signal resume. */ MHD_ALLOW_SUSPEND_RESUME = 8192 | MHD_USE_ITC, /** @deprecated */ MHD_USE_SUSPEND_RESUME = 8192 | MHD_USE_ITC, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_SUSPEND_RESUME \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_SUSPEND_RESUME is deprecated, use MHD_ALLOW_SUSPEND_RESUME instead") \ MHD_ALLOW_SUSPEND_RESUME #endif /* 0 */ /** * Enable TCP_FASTOPEN option. This option is only available on Linux with a * kernel >= 3.6. On other systems, using this option cases #MHD_start_daemon * to fail. */ MHD_USE_TCP_FASTOPEN = 16384, /** * You need to set this option if you want to use HTTP "Upgrade". * "Upgrade" may require usage of additional internal resources, * which we do not want to use unless necessary. */ MHD_ALLOW_UPGRADE = 32768, /** * Automatically use best available polling function. * Choice of polling function is also depend on other daemon options. * If #MHD_USE_INTERNAL_POLLING_THREAD is specified then epoll, poll() or * select() will be used (listed in decreasing preference order, first * function available on system will be used). * If #MHD_USE_THREAD_PER_CONNECTION is specified then poll() or select() * will be used. * If those flags are not specified then epoll or select() will be * used (as the only suitable for MHD_get_fdset()) */ MHD_USE_AUTO = 65536, /** * Run using an internal thread (or thread pool) with best available on * system polling function. * This is combination of #MHD_USE_AUTO and #MHD_USE_INTERNAL_POLLING_THREAD * flags. */ MHD_USE_AUTO_INTERNAL_THREAD = MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, /** * Flag set to enable post-handshake client authentication * (only useful in combination with #MHD_USE_TLS). */ MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT = 1U << 17, /** * Flag set to enable TLS 1.3 early data. This has * security implications, be VERY careful when using this. */ MHD_USE_INSECURE_TLS_EARLY_DATA = 1U << 18, /** * Indicates that MHD daemon will be used by application in single-threaded * mode only. When this flag is set then application must call any MHD * function only within a single thread. * This flag turns off some internal thread-safety and allows MHD making * some of the internal optimisations suitable only for single-threaded * environment. * Not compatible with #MHD_USE_INTERNAL_POLLING_THREAD. * @note Available since #MHD_VERSION 0x00097707 */ MHD_USE_NO_THREAD_SAFETY = 1U << 19 }; /** * Type of a callback function used for logging by MHD. * * @param cls closure * @param fm format string (`printf()`-style) * @param ap arguments to @a fm * @ingroup logging */ typedef void (*MHD_LogCallback)(void *cls, const char *fm, va_list ap); /** * Function called to lookup the pre shared key (@a psk) for a given * HTTP connection based on the @a username. * * @param cls closure * @param connection the HTTPS connection * @param username the user name claimed by the other side * @param[out] psk to be set to the pre-shared-key; should be allocated with malloc(), * will be freed by MHD * @param[out] psk_size to be set to the number of bytes in @a psk * @return 0 on success, -1 on errors */ typedef int (*MHD_PskServerCredentialsCallback)(void *cls, const struct MHD_Connection *connection, const char *username, void **psk, size_t *psk_size); /** * Values for #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE. * * These values can limit the scope of validity of MHD-generated nonces. * Values can be combined with bitwise OR. * Any value, except #MHD_DAUTH_BIND_NONCE_NONE, enforce function * #MHD_digest_auth_check3() (and similar functions) to check nonce by * re-generating it again with the same parameters, which is CPU-intensive * operation. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DAuthBindNonce { /** * Generated nonces are valid for any request from any client until expired. * This is default and recommended value. * #MHD_digest_auth_check3() (and similar functions) would check only whether * the nonce value that is used by client has been generated by MHD and not * expired yet. * It is recommended because RFC 7616 allows clients to use the same nonce * for any request in the same "protection space". * When checking client's authorisation requests CPU is loaded less if this * value is used. * This mode gives MHD maximum flexibility for nonces generation and can * prevent possible nonce collisions (and corresponding log warning messages) * when clients' requests are intensive. * This value cannot be biwise-OR combined with other values. */ MHD_DAUTH_BIND_NONCE_NONE = 0, /** * Generated nonces are valid only for the same realm. */ MHD_DAUTH_BIND_NONCE_REALM = 1 << 0, /** * Generated nonces are valid only for the same URI (excluding parameters * after '?' in URI) and request method (GET, POST etc). * Not recommended unless "protection space" is limited to a single URI as * RFC 7616 allows clients to re-use server-generated nonces for any URI * in the same "protection space" which by default consists of all server * URIs. * Before #MHD_VERSION 0x00097701 this was default (and only supported) * nonce bind type. */ MHD_DAUTH_BIND_NONCE_URI = 1 << 1, /** * Generated nonces are valid only for the same URI including URI parameters * and request method (GET, POST etc). * This value implies #MHD_DAUTH_BIND_NONCE_URI. * Not recommended for that same reasons as #MHD_DAUTH_BIND_NONCE_URI. */ MHD_DAUTH_BIND_NONCE_URI_PARAMS = 1 << 2, /** * Generated nonces are valid only for the single client's IP. * While it looks like security improvement, in practice the same client may * jump from one IP to another (mobile or Wi-Fi handover, DHCP re-assignment, * Multi-NAT, different proxy chain and other reasons), while IP address * spoofing could be used relatively easily. */ MHD_DAUTH_BIND_NONCE_CLIENT_IP = 1 << 3 } _MHD_FLAGS_ENUM; /** * @brief MHD options. * * Passed in the varargs portion of #MHD_start_daemon. */ enum MHD_OPTION { /** * No more options / last option. This is used * to terminate the VARARGs list. */ MHD_OPTION_END = 0, /** * Maximum memory size per connection (followed by a `size_t`). * Default is 32 kb (#MHD_POOL_SIZE_DEFAULT). * Values above 128k are unlikely to result in much benefit, as half * of the memory will be typically used for IO, and TCP buffers are * unlikely to support window sizes above 64k on most systems. * Values below 64 bytes are completely unusable. * Since #MHD_VERSION 0x00097710 silently ignored if followed by zero value. */ MHD_OPTION_CONNECTION_MEMORY_LIMIT = 1, /** * Maximum number of concurrent connections to * accept (followed by an `unsigned int`). */ MHD_OPTION_CONNECTION_LIMIT = 2, /** * After how many seconds of inactivity should a * connection automatically be timed out? (followed * by an `unsigned int`; use zero for no timeout). * Values larger than (UINT64_MAX / 2000 - 1) will * be clipped to this number. */ MHD_OPTION_CONNECTION_TIMEOUT = 3, /** * Register a function that should be called whenever a request has * been completed (this can be used for application-specific clean * up). Requests that have never been presented to the application * (via #MHD_AccessHandlerCallback) will not result in * notifications. * * This option should be followed by TWO pointers. First a pointer * to a function of type #MHD_RequestCompletedCallback and second a * pointer to a closure to pass to the request completed callback. * The second pointer may be NULL. */ MHD_OPTION_NOTIFY_COMPLETED = 4, /** * Limit on the number of (concurrent) connections made to the * server from the same IP address. Can be used to prevent one * IP from taking over all of the allowed connections. If the * same IP tries to establish more than the specified number of * connections, they will be immediately rejected. The option * should be followed by an `unsigned int`. The default is * zero, which means no limit on the number of connections * from the same IP address. */ MHD_OPTION_PER_IP_CONNECTION_LIMIT = 5, /** * Bind daemon to the supplied `struct sockaddr`. This option should * be followed by a `struct sockaddr *`. If #MHD_USE_IPv6 is * specified, the `struct sockaddr*` should point to a `struct * sockaddr_in6`, otherwise to a `struct sockaddr_in`. * Silently ignored if followed by NULL pointer. * @deprecated Use #MHD_OPTION_SOCK_ADDR_LEN */ MHD_OPTION_SOCK_ADDR = 6, /** * Specify a function that should be called before parsing the URI from * the client. The specified callback function can be used for processing * the URI (including the options) before it is parsed. The URI after * parsing will no longer contain the options, which maybe inconvenient for * logging. This option should be followed by two arguments, the first * one must be of the form * * void * my_logger(void *cls, const char *uri, struct MHD_Connection *con) * * where the return value will be passed as * (`* req_cls`) in calls to the #MHD_AccessHandlerCallback * when this request is processed later; returning a * value of NULL has no special significance (however, * note that if you return non-NULL, you can no longer * rely on the first call to the access handler having * `NULL == *req_cls` on entry;) * "cls" will be set to the second argument following * #MHD_OPTION_URI_LOG_CALLBACK. Finally, uri will * be the 0-terminated URI of the request. * * Note that during the time of this call, most of the connection's * state is not initialized (as we have not yet parsed the headers). * However, information about the connecting client (IP, socket) * is available. * * The specified function is called only once per request, therefore some * programmers may use it to instantiate their own request objects, freeing * them in the notifier #MHD_OPTION_NOTIFY_COMPLETED. */ MHD_OPTION_URI_LOG_CALLBACK = 7, /** * Memory pointer for the private key (key.pem) to be used by the * HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_CERT. */ MHD_OPTION_HTTPS_MEM_KEY = 8, /** * Memory pointer for the certificate (cert.pem) to be used by the * HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY. */ MHD_OPTION_HTTPS_MEM_CERT = 9, /** * Daemon credentials type. * Followed by an argument of type * `gnutls_credentials_type_t`. */ MHD_OPTION_HTTPS_CRED_TYPE = 10, /** * Memory pointer to a `const char *` specifying the GnuTLS priorities string. * If this options is not specified, then MHD will try the following strings: * * "@LIBMICROHTTPD" (application-specific system-wide configuration) * * "@SYSTEM" (system-wide configuration) * * default GnuTLS priorities string * * "NORMAL" * The first configuration accepted by GnuTLS will be used. * For more details see GnuTLS documentation for "Application-specific * priority strings". */ MHD_OPTION_HTTPS_PRIORITIES = 11, /** * Pass a listen socket for MHD to use (systemd-style). If this * option is used, MHD will not open its own listen socket(s). The * argument passed must be of type `MHD_socket` and refer to an * existing socket that has been bound to a port and is listening. * If followed by MHD_INVALID_SOCKET value, MHD ignores this option * and creates socket by itself. */ MHD_OPTION_LISTEN_SOCKET = 12, /** * Use the given function for logging error messages. This option * must be followed by two arguments; the first must be a pointer to * a function of type #MHD_LogCallback and the second a pointer * `void *` which will be passed as the first argument to the log * callback. * Should be specified as the first option, otherwise some messages * may be printed by standard MHD logger during daemon startup. * * Note that MHD will not generate any log messages * if it was compiled without the "--enable-messages" * flag being set. */ MHD_OPTION_EXTERNAL_LOGGER = 13, /** * Number (`unsigned int`) of threads in thread pool. Enable * thread pooling by setting this value to to something * greater than 1. * Can be used only for daemons started with #MHD_USE_INTERNAL_POLLING_THREAD. * Ignored if followed by zero value. */ MHD_OPTION_THREAD_POOL_SIZE = 14, /** * Additional options given in an array of `struct MHD_OptionItem`. * The array must be terminated with an entry `{MHD_OPTION_END, 0, NULL}`. * An example for code using #MHD_OPTION_ARRAY is: * * struct MHD_OptionItem ops[] = { * { MHD_OPTION_CONNECTION_LIMIT, 100, NULL }, * { MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL }, * { MHD_OPTION_END, 0, NULL } * }; * d = MHD_start_daemon (0, 8080, NULL, NULL, dh, NULL, * MHD_OPTION_ARRAY, ops, * MHD_OPTION_END); * * For options that expect a single pointer argument, the * 'value' member of the `struct MHD_OptionItem` is ignored. * For options that expect two pointer arguments, the first * argument must be cast to `intptr_t`. */ MHD_OPTION_ARRAY = 15, /** * Specify a function that should be called for unescaping escape * sequences in URIs and URI arguments. Note that this function * will NOT be used by the `struct MHD_PostProcessor`. If this * option is not specified, the default method will be used which * decodes escape sequences of the form "%HH". This option should * be followed by two arguments, the first one must be of the form * * size_t my_unescaper(void *cls, * struct MHD_Connection *c, * char *s) * * where the return value must be the length of the value left in * "s" (without the 0-terminator) and "s" should be updated. Note * that the unescape function must not lengthen "s" (the result must * be shorter than the input and must still be 0-terminated). * However, it may also include binary zeros before the * 0-termination. "cls" will be set to the second argument * following #MHD_OPTION_UNESCAPE_CALLBACK. */ MHD_OPTION_UNESCAPE_CALLBACK = 16, /** * Memory pointer for the random values to be used by the Digest * Auth module. This option should be followed by two arguments. * First an integer of type `size_t` which specifies the size * of the buffer pointed to by the second argument in bytes. * The recommended size is between 8 and 32. If size is four or less * then security could be lowered. Sizes more then 32 (or, probably * more than 16 - debatable) will not increase security. * Note that the application must ensure that the buffer of the * second argument remains allocated and unmodified while the * daemon is running. * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM_COPY */ MHD_OPTION_DIGEST_AUTH_RANDOM = 17, /** * Size of the internal array holding the map of the nonce and * the nonce counter. This option should be followed by an `unsigend int` * argument. * The map size is 4 by default, which is enough to communicate with * a single client at any given moment of time, but not enough to * handle several clients simultaneously. * If Digest Auth is not used, this option can be set to zero to minimise * memory allocation. */ MHD_OPTION_NONCE_NC_SIZE = 18, /** * Desired size of the stack for threads created by MHD. Followed * by an argument of type `size_t`. Use 0 for system default. */ MHD_OPTION_THREAD_STACK_SIZE = 19, /** * Memory pointer for the certificate (ca.pem) to be used by the * HTTPS daemon for client authentication. * This option should be followed by a `const char *` argument. */ MHD_OPTION_HTTPS_MEM_TRUST = 20, /** * Increment to use for growing the read buffer (followed by a * `size_t`). * Must not be higher than 1/4 of #MHD_OPTION_CONNECTION_MEMORY_LIMIT. * Since #MHD_VERSION 0x00097710 silently ignored if followed by zero value. */ MHD_OPTION_CONNECTION_MEMORY_INCREMENT = 21, /** * Use a callback to determine which X.509 certificate should be * used for a given HTTPS connection. This option should be * followed by a argument of type `gnutls_certificate_retrieve_function2 *`. * This option provides an * alternative to #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT. You must use this version if * multiple domains are to be hosted at the same IP address using * TLS's Server Name Indication (SNI) extension. In this case, * the callback is expected to select the correct certificate * based on the SNI information provided. The callback is expected * to access the SNI data using `gnutls_server_name_get()`. * Using this option requires GnuTLS 3.0 or higher. */ MHD_OPTION_HTTPS_CERT_CALLBACK = 22, /** * When using #MHD_USE_TCP_FASTOPEN, this option changes the default TCP * fastopen queue length of 50. Note that having a larger queue size can * cause resource exhaustion attack as the TCP stack has to now allocate * resources for the SYN packet along with its DATA. This option should be * followed by an `unsigned int` argument. */ MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE = 23, /** * Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used by the * HTTPS daemon for key exchange. * This option must be followed by a `const char *` argument. */ MHD_OPTION_HTTPS_MEM_DHPARAMS = 24, /** * If present and set to true, allow reusing address:port socket * (by using SO_REUSEPORT on most platform, or platform-specific ways). * If present and set to false, disallow reusing address:port socket * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on Windows). * This option must be followed by a `unsigned int` argument. */ MHD_OPTION_LISTENING_ADDRESS_REUSE = 25, /** * Memory pointer for a password that decrypts the private key (key.pem) * to be used by the HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY. * @sa ::MHD_FEATURE_HTTPS_KEY_PASSWORD */ MHD_OPTION_HTTPS_KEY_PASSWORD = 26, /** * Register a function that should be called whenever a connection is * started or closed. * * This option should be followed by TWO pointers. First a pointer * to a function of type #MHD_NotifyConnectionCallback and second a * pointer to a closure to pass to the request completed callback. * The second pointer may be NULL. */ MHD_OPTION_NOTIFY_CONNECTION = 27, /** * Allow to change maximum length of the queue of pending connections on * listen socket. If not present than default platform-specific SOMAXCONN * value is used. This option should be followed by an `unsigned int` * argument. */ MHD_OPTION_LISTEN_BACKLOG_SIZE = 28, /** * If set to 1 - be strict about the protocol. Use -1 to be * as tolerant as possible. * * The more flexible option #MHD_OPTION_CLIENT_DISCIPLINE_LVL is recommended * instead of this option. * * The values mapping table: * #MHD_OPTION_STRICT_FOR_CLIENT | #MHD_OPTION_CLIENT_DISCIPLINE_LVL * -----------------------------:|:--------------------------------- * 1 | 1 * 0 | 0 * -1 | -3 * * This option should be followed by an `int` argument. * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ MHD_OPTION_STRICT_FOR_CLIENT = 29, /** * This should be a pointer to callback of type * gnutls_psk_server_credentials_function that will be given to * gnutls_psk_set_server_credentials_function. It is used to * retrieve the shared key for a given username. */ MHD_OPTION_GNUTLS_PSK_CRED_HANDLER = 30, /** * Use a callback to determine which X.509 certificate should be * used for a given HTTPS connection. This option should be * followed by a argument of type `gnutls_certificate_retrieve_function3 *`. * This option provides an * alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK. * You must use this version if you want to use OCSP stapling. * Using this option requires GnuTLS 3.6.3 or higher. */ MHD_OPTION_HTTPS_CERT_CALLBACK2 = 31, /** * Allows the application to disable certain sanity precautions * in MHD. With these, the client can break the HTTP protocol, * so this should never be used in production. The options are, * however, useful for testing HTTP clients against "broken" * server implementations. * This argument must be followed by an "unsigned int", corresponding * to an `enum MHD_DisableSanityCheck`. */ MHD_OPTION_SERVER_INSANITY = 32, /** * If followed by value '1' informs MHD that SIGPIPE is suppressed or * handled by application. Allows MHD to use network functions that could * generate SIGPIPE, like `sendfile()`. * Valid only for daemons without #MHD_USE_INTERNAL_POLLING_THREAD as * MHD automatically suppresses SIGPIPE for threads started by MHD. * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097205 */ MHD_OPTION_SIGPIPE_HANDLED_BY_APP = 33, /** * If followed by 'int' with value '1' disables usage of ALPN for TLS * connections even if supported by TLS library. * Valid only for daemons with #MHD_USE_TLS. * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097207 */ MHD_OPTION_TLS_NO_ALPN = 34, /** * Memory pointer for the random values to be used by the Digest * Auth module. This option should be followed by two arguments. * First an integer of type `size_t` which specifies the size * of the buffer pointed to by the second argument in bytes. * The recommended size is between 8 and 32. If size is four or less * then security could be lowered. Sizes more then 32 (or, probably * more than 16 - debatable) will not increase security. * An internal copy of the buffer will be made, the data do not * need to be static. * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_DIGEST_AUTH_RANDOM_COPY = 35, /** * Allow to controls the scope of validity of MHD-generated nonces. * This regulates how "nonces" are generated and how "nonces" are checked by * #MHD_digest_auth_check3() and similar functions. * This option should be followed by an 'unsigned int` argument with value * formed as bitwise OR combination of #MHD_DAuthBindNonce values. * When not specified, default value #MHD_DAUTH_BIND_NONCE_NONE is used. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE = 36, /** * Memory pointer to a `const char *` specifying the GnuTLS priorities to be * appended to default priorities. * This allow some specific options to be enabled/disabled, while leaving * the rest of the settings to their defaults. * The string does not have to start with a colon ':' character. * See #MHD_OPTION_HTTPS_PRIORITIES description for details of automatic * default priorities. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_HTTPS_PRIORITIES_APPEND = 37, /** * Sets specified client discipline level (i.e. HTTP protocol parsing * strictness level). * * The following basic values are supported: * 0 - default MHD level, a balance between extra security and broader * compatibility, as allowed by RFCs for HTTP servers; * 1 - more strict protocol interpretation, within the limits set by * RFCs for HTTP servers; * -1 - more lenient protocol interpretation, within the limits set by * RFCs for HTTP servers. * The following extended values could be used as well: * 2 - stricter protocol interpretation, even stricter then allowed * by RFCs for HTTP servers, however it should be absolutely compatible * with clients following at least RFCs' "MUST" type of requirements * for HTTP clients; * 3 - strictest protocol interpretation, even stricter then allowed * by RFCs for HTTP servers, however it should be absolutely compatible * with clients following RFCs' "SHOULD" and "MUST" types of requirements * for HTTP clients; * -2 - more relaxed protocol interpretation, violating RFCs' "SHOULD" type * of requirements for HTTP servers; * -3 - the most flexible protocol interpretation, beyond RFCs' "MUST" type of * requirements for HTTP server. * Values higher than "3" or lower than "-3" are interpreted as "3" or "-3" * respectively. * * Higher values are more secure, lower values are more compatible with * various HTTP clients. * * The default value ("0") could be used in most cases. * Value "1" is suitable for highly loaded public servers. * Values "2" and "3" are generally recommended only for testing of HTTP * clients against MHD. * Value "2" may be used for security-centric application, however it is * slight violation of RFCs' requirements. * Negative values are not recommended for public servers. * Values "-1" and "-2" could be used for servers in isolated environment. * Value "-3" is not recommended unless it is absolutely necessary to * communicate with some client(s) with badly broken HTTP implementation. * * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_CLIENT_DISCIPLINE_LVL = 38, /** * Specifies value of FD_SETSIZE used by application. Only For external * polling modes (without MHD internal threads). * Some platforms (FreeBSD, Solaris, W32 etc.) allow overriding of FD_SETSIZE * value. When polling by select() is used, MHD rejects sockets with numbers * equal or higher than FD_SETSIZE. If this option is used, MHD treats this * value as a limitation for socket number instead of FD_SETSIZE value which * was used for building MHD. * When external polling is used with #MHD_get_fdset2() (or #MHD_get_fdset() * macro) and #MHD_run_from_select() interfaces, it is recommended to always * use this option. * It is safe to use this option on platforms with fixed FD_SETSIZE (like * GNU/Linux) if system value of FD_SETSIZE is used as the argument. * Can be used only for daemons without #MHD_USE_INTERNAL_POLLING_THREAD, i.e. * only when external sockets polling is used. * On W32 it is silently ignored, as W32 does not limit the socket number in * fd_sets. * This option should be followed by a positive 'int' argument. * @note Available since #MHD_VERSION 0x00097705 */ MHD_OPTION_APP_FD_SETSIZE = 39, /** * Bind daemon to the supplied 'struct sockaddr'. This option should * be followed by two parameters: 'socklen_t' the size of memory at the next * pointer and the pointer 'const struct sockaddr *'. * Note: the order of the arguments is not the same as for system bind() and * other network functions. * If #MHD_USE_IPv6 is specified, the 'struct sockaddr*' should * point to a 'struct sockaddr_in6'. * The socket domain (protocol family) is detected from provided * 'struct sockaddr'. IP, IPv6 and UNIX sockets are supported (if supported * by the platform). Other types may work occasionally. * Silently ignored if followed by zero size and NULL pointer. * @note Available since #MHD_VERSION 0x00097706 */ MHD_OPTION_SOCK_ADDR_LEN = 40 , /** * Default nonce timeout value used for Digest Auth. * This option should be followed by an 'unsigned int' argument. * Silently ignored if followed by zero value. * @see #MHD_digest_auth_check3(), MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097709 */ MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT = 41 , /** * Default maximum nc (nonce count) value used for Digest Auth. * This option should be followed by an 'uint32_t' argument. * Silently ignored if followed by zero value. * @see #MHD_digest_auth_check3(), MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097709 */ MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC = 42 } _MHD_FIXED_ENUM; /** * Bitfield for the #MHD_OPTION_SERVER_INSANITY specifying * which santiy checks should be disabled. */ enum MHD_DisableSanityCheck { /** * All sanity checks are enabled. */ MHD_DSC_SANE = 0 } _MHD_FIXED_FLAGS_ENUM; /** * Entry in an #MHD_OPTION_ARRAY. */ struct MHD_OptionItem { /** * Which option is being given. Use #MHD_OPTION_END * to terminate the array. */ enum MHD_OPTION option; /** * Option value (for integer arguments, and for options requiring * two pointer arguments); should be 0 for options that take no * arguments or only a single pointer argument. */ intptr_t value; /** * Pointer option value (use NULL for options taking no arguments * or only an integer option). */ void *ptr_value; }; /** * The `enum MHD_ValueKind` specifies the source of * the key-value pairs in the HTTP protocol. */ enum MHD_ValueKind { /** * Response header * @deprecated */ MHD_RESPONSE_HEADER_KIND = 0, #define MHD_RESPONSE_HEADER_KIND \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_RESPONSE_HEADER_KIND is deprecated and not used") \ MHD_RESPONSE_HEADER_KIND /** * HTTP header (request/response). */ MHD_HEADER_KIND = 1, /** * Cookies. Note that the original HTTP header containing * the cookie(s) will still be available and intact. */ MHD_COOKIE_KIND = 2, /** * POST data. This is available only if a content encoding * supported by MHD is used (currently only URL encoding), * and only if the posted content fits within the available * memory pool. Note that in that case, the upload data * given to the #MHD_AccessHandlerCallback will be * empty (since it has already been processed). */ MHD_POSTDATA_KIND = 4, /** * GET (URI) arguments. */ MHD_GET_ARGUMENT_KIND = 8, /** * HTTP footer (only for HTTP 1.1 chunked encodings). */ MHD_FOOTER_KIND = 16 } _MHD_FIXED_ENUM; /** * The `enum MHD_RequestTerminationCode` specifies reasons * why a request has been terminated (or completed). * @ingroup request */ enum MHD_RequestTerminationCode { /** * We finished sending the response. * @ingroup request */ MHD_REQUEST_TERMINATED_COMPLETED_OK = 0, /** * Error handling the connection (resources * exhausted, application error accepting request, * decrypt error (for HTTPS), connection died when * sending the response etc.) * @ingroup request */ MHD_REQUEST_TERMINATED_WITH_ERROR = 1, /** * No activity on the connection for the number * of seconds specified using * #MHD_OPTION_CONNECTION_TIMEOUT. * @ingroup request */ MHD_REQUEST_TERMINATED_TIMEOUT_REACHED = 2, /** * We had to close the session since MHD was being * shut down. * @ingroup request */ MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3, /** * We tried to read additional data, but the connection became broken or * the other side hard closed the connection. * This error is similar to #MHD_REQUEST_TERMINATED_WITH_ERROR, but * specific to the case where the connection died before request completely * received. * @ingroup request */ MHD_REQUEST_TERMINATED_READ_ERROR = 4, /** * The client terminated the connection by closing the socket * for writing (TCP half-closed) while still sending request. * @ingroup request */ MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5 } _MHD_FIXED_ENUM; /** * The `enum MHD_ConnectionNotificationCode` specifies types * of connection notifications. * @ingroup request */ enum MHD_ConnectionNotificationCode { /** * A new connection has been started. * @ingroup request */ MHD_CONNECTION_NOTIFY_STARTED = 0, /** * A connection is closed. * @ingroup request */ MHD_CONNECTION_NOTIFY_CLOSED = 1 } _MHD_FIXED_ENUM; /** * Information about a connection. */ union MHD_ConnectionInfo { /** * Cipher algorithm used, of type "enum gnutls_cipher_algorithm". */ int /* enum gnutls_cipher_algorithm */ cipher_algorithm; /** * Protocol used, of type "enum gnutls_protocol". */ int /* enum gnutls_protocol */ protocol; /** * The suspended status of a connection. */ int /* MHD_YES or MHD_NO */ suspended; /** * Amount of second that connection could spend in idle state * before automatically disconnected. * Zero for no timeout (unlimited idle time). */ unsigned int connection_timeout; /** * HTTP status queued with the response, for #MHD_CONNECTION_INFO_HTTP_STATUS. */ unsigned int http_status; /** * Connect socket */ MHD_socket connect_fd; /** * Size of the client's HTTP header. * It includes the request line, all request headers, the header section * terminating empty line, with all CRLF (or LF) characters. */ size_t header_size; /** * GNUtls session handle, of type "gnutls_session_t". */ void * /* gnutls_session_t */ tls_session; /** * GNUtls client certificate handle, of type "gnutls_x509_crt_t". */ void * /* gnutls_x509_crt_t */ client_cert; /** * Address information for the client. */ struct sockaddr *client_addr; /** * Which daemon manages this connection (useful in case there are many * daemons running). */ struct MHD_Daemon *daemon; /** * Socket-specific client context. Points to the same address as * the "socket_context" of the #MHD_NotifyConnectionCallback. */ void *socket_context; }; /** * I/O vector type. Provided for use with #MHD_create_response_from_iovec(). * @note Available since #MHD_VERSION 0x00097204 */ struct MHD_IoVec { /** * The pointer to the memory region for I/O. */ const void *iov_base; /** * The size in bytes of the memory region for I/O. */ size_t iov_len; }; /** * Values of this enum are used to specify what * information about a connection is desired. * @ingroup request */ enum MHD_ConnectionInfoType { /** * What cipher algorithm is being used. * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFO_CIPHER_ALGO, /** * * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFO_PROTOCOL, /** * Obtain IP address of the client. Takes no extra arguments. * Returns essentially a `struct sockaddr **` (since the API returns * a `union MHD_ConnectionInfo *` and that union contains a `struct * sockaddr *`). * @ingroup request */ MHD_CONNECTION_INFO_CLIENT_ADDRESS, /** * Get the gnuTLS session handle. * @ingroup request */ MHD_CONNECTION_INFO_GNUTLS_SESSION, /** * Get the gnuTLS client certificate handle. Dysfunctional (never * implemented, deprecated). Use #MHD_CONNECTION_INFO_GNUTLS_SESSION * to get the `gnutls_session_t` and then call * gnutls_certificate_get_peers(). */ MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT, /** * Get the `struct MHD_Daemon *` responsible for managing this connection. * @ingroup request */ MHD_CONNECTION_INFO_DAEMON, /** * Request the file descriptor for the connection socket. * MHD sockets are always in non-blocking mode. * No extra arguments should be passed. * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_FD, /** * Returns the client-specific pointer to a `void *` that was (possibly) * set during a #MHD_NotifyConnectionCallback when the socket was * first accepted. * Note that this is NOT the same as the "req_cls" argument of * the #MHD_AccessHandlerCallback. The "req_cls" is fresh for each * HTTP request, while the "socket_context" is fresh for each socket. */ MHD_CONNECTION_INFO_SOCKET_CONTEXT, /** * Check whether the connection is suspended. * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_SUSPENDED, /** * Get connection timeout * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_TIMEOUT, /** * Return length of the client's HTTP request header. * @ingroup request */ MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE, /** * Return HTTP status queued with the response. NULL * if no HTTP response has been queued yet. */ MHD_CONNECTION_INFO_HTTP_STATUS } _MHD_FIXED_ENUM; /** * Values of this enum are used to specify what * information about a daemon is desired. */ enum MHD_DaemonInfoType { /** * No longer supported (will return NULL). */ MHD_DAEMON_INFO_KEY_SIZE, /** * No longer supported (will return NULL). */ MHD_DAEMON_INFO_MAC_KEY_SIZE, /** * Request the file descriptor for the listening socket. * No extra arguments should be passed. */ MHD_DAEMON_INFO_LISTEN_FD, /** * Request the file descriptor for the "external" sockets polling * when 'epoll' mode is used. * No extra arguments should be passed. * * Waiting on epoll FD must not block longer than value * returned by #MHD_get_timeout() otherwise connections * will "hung" with unprocessed data in network buffers * and timed-out connections will not be closed. * * @sa #MHD_get_timeout(), #MHD_run() */ MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY, MHD_DAEMON_INFO_EPOLL_FD = MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY, /** * Request the number of current connections handled by the daemon. * No extra arguments should be passed. * Note: when using MHD in "external" polling mode, this type of request * could be used only when #MHD_run()/#MHD_run_from_select is not * working in other thread at the same time. */ MHD_DAEMON_INFO_CURRENT_CONNECTIONS, /** * Request the daemon flags. * No extra arguments should be passed. * Note: flags may differ from original 'flags' specified for * daemon, especially if #MHD_USE_AUTO was set. */ MHD_DAEMON_INFO_FLAGS, /** * Request the port number of daemon's listen socket. * No extra arguments should be passed. * Note: if port '0' was specified for #MHD_start_daemon(), returned * value will be real port number. */ MHD_DAEMON_INFO_BIND_PORT } _MHD_FIXED_ENUM; /** * Callback for serious error condition. The default action is to print * an error message and `abort()`. * * @param cls user specified value * @param file where the error occurred, may be NULL if MHD was built without * messages support * @param line where the error occurred * @param reason error detail, may be NULL * @ingroup logging */ typedef void (*MHD_PanicCallback) (void *cls, const char *file, unsigned int line, const char *reason); /** * Allow or deny a client to connect. * * @param cls closure * @param addr address information from the client * @param addrlen length of @a addr * @return #MHD_YES if connection is allowed, #MHD_NO if not */ typedef enum MHD_Result (*MHD_AcceptPolicyCallback)(void *cls, const struct sockaddr *addr, socklen_t addrlen); /** * A client has requested the given @a url using the given @a method * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, #MHD_HTTP_METHOD_DELETE, * #MHD_HTTP_METHOD_POST, etc). * * The callback must call MHD function MHD_queue_response() to provide content * to give back to the client and return an HTTP status code (i.e. * #MHD_HTTP_OK, #MHD_HTTP_NOT_FOUND, etc.). The response can be created * in this callback or prepared in advance. * Alternatively, callback may call MHD_suspend_connection() to temporarily * suspend data processing for this connection. * * As soon as response is provided this callback will not be called anymore * for the current request. * * For each HTTP request this callback is called several times: * * after request headers are fully received and decoded, * * for each received part of request body (optional, if request has body), * * when request is fully received. * * If response is provided before request is fully received, the rest * of the request is discarded and connection is automatically closed * after sending response. * * If the request is fully received, but response hasn't been provided and * connection is not suspended, the callback can be called again immediately. * * The response cannot be queued when this callback is called to process * the client upload data (when @a upload_data is not NULL). * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection the connection handle * @param url the requested url * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @param version the HTTP version string (i.e. * #MHD_HTTP_VERSION_1_1) * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of #MHD_get_connection_values; very large POST * data *will* be made available incrementally in * @a upload_data) * @param[in,out] upload_data_size set initially to the size of the * @a upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param[in,out] req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global #MHD_RequestCompletedCallback (which * can be set with the #MHD_OPTION_NOTIFY_COMPLETED). * Initially, `*req_cls` will be NULL. * @return #MHD_YES if the connection was handled successfully, * #MHD_NO if the socket must be closed due to a serious * error while handling the request * * @sa #MHD_queue_response() */ typedef enum MHD_Result (*MHD_AccessHandlerCallback)(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls); /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the #MHD_AccessHandlerCallback * @param toe reason for request termination * @see #MHD_OPTION_NOTIFY_COMPLETED * @ingroup request */ typedef void (*MHD_RequestCompletedCallback) (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe); /** * Signature of the callback used by MHD to notify the * application about started/stopped connections * * @param cls client-defined closure * @param connection connection handle * @param socket_context socket-specific pointer where the * client can associate some state specific * to the TCP connection; note that this is * different from the "req_cls" which is per * HTTP request. The client can initialize * during #MHD_CONNECTION_NOTIFY_STARTED and * cleanup during #MHD_CONNECTION_NOTIFY_CLOSED * and access in the meantime using * #MHD_CONNECTION_INFO_SOCKET_CONTEXT. * @param toe reason for connection notification * @see #MHD_OPTION_NOTIFY_CONNECTION * @ingroup request */ typedef void (*MHD_NotifyConnectionCallback) (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe); /** * Iterator over key-value pairs. This iterator * can be used to iterate over all of the cookies, * headers, or POST-data fields of a request, and * also to iterate over the headers that have been * added to a response. * * @param cls closure * @param kind kind of the header we are looking at * @param key key for the value, can be an empty string * @param value corresponding value, can be NULL * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration * @ingroup request */ typedef enum MHD_Result (*MHD_KeyValueIterator)(void *cls, enum MHD_ValueKind kind, const char *key, const char *value); /** * Iterator over key-value pairs with size parameters. * This iterator can be used to iterate over all of * the cookies, headers, or POST-data fields of a * request, and also to iterate over the headers that * have been added to a response. * @note Available since #MHD_VERSION 0x00096303 * * @param cls closure * @param kind kind of the header we are looking at * @param key key for the value, can be an empty string * @param value corresponding value, can be NULL * @param value_size number of bytes in @a value; * for C-strings, the length excludes the 0-terminator * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration * @ingroup request */ typedef enum MHD_Result (*MHD_KeyValueIteratorN)(void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size); /** * Callback used by libmicrohttpd in order to obtain content. * * The callback is to copy at most @a max bytes of content into @a buf. * The total number of bytes that has been placed into @a buf should be * returned. * * Note that returning zero will cause libmicrohttpd to try again. * Thus, returning zero should only be used in conjunction * with MHD_suspend_connection() to avoid busy waiting. * * @param cls extra argument to the callback * @param pos position in the datastream to access; * note that if a `struct MHD_Response` object is re-used, * it is possible for the same content reader to * be queried multiple times for the same data; * however, if a `struct MHD_Response` is not re-used, * libmicrohttpd guarantees that "pos" will be * the sum of all non-negative return values * obtained from the content reader so far. * @param buf where to copy the data * @param max maximum number of bytes to copy to @a buf (size of @a buf) * @return number of bytes written to @a buf; * 0 is legal unless MHD is started in "internal" sockets polling mode * (since this would cause busy-waiting); 0 in "external" sockets * polling mode will cause this function to be called again once * any MHD_run*() function is called; * #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular * end of transmission (with chunked encoding, MHD will then * terminate the chunk and send any HTTP footers that might be * present; without chunked encoding and given an unknown * response size, MHD will simply close the connection; note * that while returning #MHD_CONTENT_READER_END_OF_STREAM is not technically * legal if a response size was specified, MHD accepts this * and treats it just as #MHD_CONTENT_READER_END_WITH_ERROR; * #MHD_CONTENT_READER_END_WITH_ERROR (-2) to indicate a server * error generating the response; this will cause MHD to simply * close the connection immediately. If a response size was * given or if chunked encoding is in use, this will indicate * an error to the client. Note, however, that if the client * does not know a response size and chunked encoding is not in * use, then clients will not be able to tell the difference between * #MHD_CONTENT_READER_END_WITH_ERROR and #MHD_CONTENT_READER_END_OF_STREAM. * This is not a limitation of MHD but rather of the HTTP protocol. */ typedef ssize_t (*MHD_ContentReaderCallback) (void *cls, uint64_t pos, char *buf, size_t max); /** * This method is called by libmicrohttpd if we * are done with a content reader. It should * be used to free resources associated with the * content reader. * * @param cls closure * @ingroup response */ typedef void (*MHD_ContentReaderFreeCallback) (void *cls); /** * Iterator over key-value pairs where the value * may be made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value, NULL if not known. This value * is never NULL for url-encoded POST data. * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to @a size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in @a data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ typedef enum MHD_Result (*MHD_PostDataIterator)(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size); /* **************** Daemon handling functions ***************** */ /** * Start a webserver on the given port. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if MHD_OPTION_SOCK_ADDR or * MHD_OPTION_LISTEN_SOCKET is provided * or MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @param ap list of options (type-value pairs, * terminated with #MHD_OPTION_END). * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon_va (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, va_list ap); /** * Start a webserver on the given port. Variadic version of * #MHD_start_daemon_va. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if MHD_OPTION_SOCK_ADDR or * MHD_OPTION_LISTEN_SOCKET is provided * or MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...); /** * Stop accepting connections from the listening socket. Allows * clients to continue processing, but stops accepting new * connections. Note that the caller is responsible for closing the * returned socket; however, if MHD is run using threads (anything but * "external" sockets polling mode), it must not be closed until AFTER * #MHD_stop_daemon has been called (as it is theoretically possible * that an existing thread is still using it). * * Note that some thread modes require the caller to have passed * #MHD_USE_ITC when using this API. If this daemon is * in one of those modes and this option was not given to * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. * * @param daemon daemon to stop accepting new connections for * @return old listen socket on success, #MHD_INVALID_SOCKET if * the daemon was already not listening anymore * @ingroup specialized */ _MHD_EXTERN MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon); /** * Shutdown an HTTP daemon. * * @param daemon daemon to stop * @ingroup event */ _MHD_EXTERN void MHD_stop_daemon (struct MHD_Daemon *daemon); /** * Add another client connection to the set of connections managed by * MHD. This API is usually not needed (since MHD will accept inbound * connections on the server socket). Use this API in special cases, * for example if your HTTP server is behind NAT and needs to connect * out to the HTTP client, or if you are building a proxy. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that the freshly added * connection is immediately processed by MHD. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. `malloc()` failed, etc). * The socket will be closed in any case; `errno` is * set to indicate further details about the error. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. FD_SETSIZE is assumed * to be platform's default. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. * * Passing custom FD_SETSIZE as @a fd_setsize allow usage of * larger/smaller than platform's default fd_sets. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. Size of fd_set is * determined by current value of FD_SETSIZE. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ #define MHD_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set,max_fd) \ MHD_get_fdset2 ((daemon),(read_fd_set),(write_fd_set),(except_fd_set), \ (max_fd),FD_SETSIZE) /** * Obtain timeout value for polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout64(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon daemon to query for timeout * @param[out] timeout set to the timeout (in milliseconds) * @return #MHD_YES on success, #MHD_NO if timeouts are * not used and no data processing is pending. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout); /** * Free the memory allocated by MHD. * * If any MHD function explicitly mentions that returned pointer must be * freed by this function, then no other method must be used to free * the memory. * * @param ptr the pointer to free. * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3() * @sa #MHD_basic_auth_get_username_password() * @note Available since #MHD_VERSION 0x00095600 * @ingroup specialized */ _MHD_EXTERN void MHD_free (void *ptr); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon daemon to query for timeout * @param[out] timeout64 the pointer to the variable to be set to the * timeout (in milliseconds) * @return #MHD_YES if timeout value has been set, * #MHD_NO if timeouts are not used and no data processing is pending. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout64 (struct MHD_Daemon *daemon, uint64_t *timeout); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * that external polling function must wait for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int64_t MHD_get_timeout64s (struct MHD_Daemon *daemon); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * (capped at INT_MAX) that external polling function must wait * for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int MHD_get_timeout_i (struct MHD_Daemon *daemon); /** * Run webserver operations (without blocking unless in client callbacks). * * This method should be called by clients in combination with * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD * if epoll is used) and #MHD_get_timeout() if the client-controlled * connection polling method is used (i.e. daemon was started without * #MHD_USE_INTERNAL_POLLING_THREAD flag). * * This function is a convenience method, which is useful if the * fd_sets from #MHD_get_fdset were not directly passed to `select()`; * with this function, MHD will internally do the appropriate `select()` * call itself again. While it is acceptable to call #MHD_run (if * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should * call #MHD_run_from_select() if performance is important (as it saves an * expensive call to `select()`). * * If #MHD_get_timeout() returned #MHD_YES, than this function must be called * right after polling function returns regardless of detected activity on * the daemon's FDs. * * @param daemon daemon to run * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run (struct MHD_Daemon *daemon); /** * Run websever operation with possible blocking. * * This function does the following: waits for any network event not more than * specified number of milliseconds, processes all incoming and outgoing data, * processes new connections, processes any timed-out connection, and does * other things required to run webserver. * Once all connections are processed, function returns. * * This function is useful for quick and simple (lazy) webserver implementation * if application needs to run a single thread only and does not have any other * network activity. * * This function calls MHD_get_timeout() internally and use returned value as * maximum wait time if it less than value of @a millisec parameter. * * It is expected that the "external" socket polling function is not used in * conjunction with this function unless the @a millisec is set to zero. * * @param daemon the daemon to run * @param millisec the maximum time in milliseconds to wait for network and * other events. Note: there is no guarantee that function * blocks for the specified amount of time. The real processing * time can be shorter (if some data or connection timeout * comes earlier) or longer (if data processing requires more * time, especially in user callbacks). * If set to '0' then function does not block and processes * only already available data (if any). * If set to '-1' then function waits for events * indefinitely (blocks until next network activity or * connection timeout). * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or some serious * unrecoverable error occurs. * @note Available since #MHD_VERSION 0x00097206 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_wait (struct MHD_Daemon *daemon, int32_t millisec); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * * You can use this function instead of #MHD_run if you called * `select()` on the result from #MHD_get_fdset. File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run is more efficient as MHD will * not have to call `select()` again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after `select()` returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This function specifies FD_SETSIZE used when provided fd_sets were * created. It is important on platforms where FD_SETSIZE can be * overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select2 (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, unsigned int fd_setsize); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This macro automatically substitutes current FD_SETSIZE value. * It is important on platforms where FD_SETSIZE can be overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ #define MHD_run_from_select(d,r,w,e) \ MHD_run_from_select2 ((d),(r),(w),(e),(unsigned int) (FD_SETSIZE)) /* **************** Connection handling functions ***************** */ /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls); /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @note Available since #MHD_VERSION 0x00096400 * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIteratorN iterator, void *iterator_cls); /** * This function can be used to add an entry to the HTTP headers of a * connection (so that the #MHD_get_connection_values function will * return them -- and the `struct MHD_PostProcessor` will also see * them). This maybe required in certain situations (see Mantis * #1399) where (broken) HTTP implementations fail to supply values * needed by the post processor (or other parts of the application). * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value * @param value the value itself * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value); /** * This function can be used to add an arbitrary entry to connection. * This function could add entry with binary zero, which is allowed * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is * recommended to use #MHD_set_connection_value. * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @note Available since #MHD_VERSION 0x00096400 * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size); /** * Sets the global error handler to a different implementation. * * @a cb will only be called in the case of typically fatal, serious internal * consistency issues or serious system failures like failed lock of mutex. * * These issues should only arise in the case of serious memory corruption or * similar problems with the architecture, there is no safe way to continue * even for closing of the application. * * The default implementation that is used if no panic function is set simply * prints an error message and calls `abort()`. * Alternative implementations might call `exit()` or other similar functions. * * @param cb new error handler or NULL to use default handler * @param cls passed to @a cb * @ingroup logging */ _MHD_EXTERN void MHD_set_panic_func (MHD_PanicCallback cb, void *cls); /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result is still be 0-terminated. * * @param val value to unescape (modified in the process) * @return length of the resulting val (`strlen(val)` may be * shorter afterwards due to elimination of escape sequences) */ _MHD_EXTERN size_t MHD_http_unescape (char *val); /** * Get a particular header value. If multiple * values match the kind, return any one of them. * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @return NULL if no such item was found * @ingroup request */ _MHD_EXTERN const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key); /** * Get a particular header value. If multiple * values match the kind, return any one of them. * @note Since MHD_VERSION 0x00096304 * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @param key_size the length of @a key in bytes * @param[out] value_ptr the pointer to variable, which will be set to found value, * will not be updated if key not found, * could be NULL to just check for presence of @a key * @param[out] value_size_ptr the pointer variable, which will set to found value, * will not be updated if key not found, * could be NULL * @return #MHD_YES if key is found, * #MHD_NO otherwise. * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr); /** * Queue a response to be transmitted to the client (as soon as * possible but after #MHD_AccessHandlerCallback returns). * * For any active connection this function must be called * only by #MHD_AccessHandlerCallback callback. * * For suspended connection this function can be called at any moment (this * behaviour is deprecated and will be removed!). Response will be sent * as soon as connection is resumed. * * For single thread environment, when MHD is used in "external polling" mode * (without MHD_USE_SELECT_INTERNALLY) this function can be called any * time (this behaviour is deprecated and will be removed!). * * If HTTP specifications require use no body in reply, like @a status_code with * value 1xx, the response body is automatically not sent even if it is present * in the response. No "Content-Length" or "Transfer-Encoding" headers are * generated and added. * * When the response is used to respond HEAD request or used with @a status_code * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length" * header is added automatically based the size of the body in the response. * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead * of "Content-Length" header. For example, if response with zero-size body is * used for HEAD request, then "Content-Length: 0" is added automatically to * reply headers. * @sa #MHD_RF_HEAD_ONLY_RESPONSE * * In situations, where reply body is required, like answer for the GET request * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1) * are added automatically. * In practice, the same response object can be used to respond to both HEAD and * GET requests. * * @param connection the connection identifying the client * @param status_code HTTP status code (i.e. #MHD_HTTP_OK) * @param response response to transmit, the NULL is tolerated * @return #MHD_NO on error (reply already sent, response is NULL), * #MHD_YES on success or if message has been queued * @ingroup response * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response); /** * Suspend handling of network data for a given connection. * This can be used to dequeue a connection from MHD's event loop * (not applicable to thread-per-connection!) for a while. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that a resumed * connection is immediately processed by MHD. * * Suspended connections continue to count against the total number of * connections allowed (per daemon, as well as per IP, if such limits * are set). Suspended connections will NOT time out; timeouts will * restart when the connection handling is resumed. While a * connection is suspended, MHD will not detect disconnects by the * client. * * The only safe way to call this function is to call it from the * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback. * * Finally, it is an API violation to call #MHD_stop_daemon while * having suspended connections (this will at least create memory and * socket leaks or lead to undefined behavior). You must explicitly * resume all connections before stopping the daemon. * * @param connection the connection to suspend * * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN void MHD_suspend_connection (struct MHD_Connection *connection); /** * Resume handling of network data for suspended connection. It is * safe to resume a suspended connection at any time. Calling this * function on a connection that was not previously suspended will * result in undefined behavior. * * If you are using this function in "external" sockets polling mode, you must * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before * again calling #MHD_get_fdset()), as otherwise the change may not be * reflected in the set returned by #MHD_get_fdset() and you may end up * with a connection that is stuck until the next network activity. * * @param connection the connection to resume */ _MHD_EXTERN void MHD_resume_connection (struct MHD_Connection *connection); /* **************** Response manipulation functions ***************** */ /** * Flags for special handling of responses. */ enum MHD_ResponseFlags { /** * Default: no special flags. * @note Available since #MHD_VERSION 0x00093701 */ MHD_RF_NONE = 0, /** * Only respond in conservative (dumb) HTTP/1.0-compatible mode. * Response still use HTTP/1.1 version in header, but always close * the connection after sending the response and do not use chunked * encoding for the response. * You can also set the #MHD_RF_HTTP_1_0_SERVER flag to force * HTTP/1.0 version in the response. * Responses are still compatible with HTTP/1.1. * This option can be used to communicate with some broken client, which * does not implement HTTP/1.1 features, but advertises HTTP/1.1 support. * @note Available since #MHD_VERSION 0x00097308 */ MHD_RF_HTTP_1_0_COMPATIBLE_STRICT = 1 << 0, /** * The same as #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT * @note Available since #MHD_VERSION 0x00093701 */ MHD_RF_HTTP_VERSION_1_0_ONLY = 1 << 0, /** * Only respond in HTTP 1.0-mode. * Contrary to the #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag, the response's * HTTP version will always be set to 1.0 and keep-alive connections * will be used if explicitly requested by the client. * The "Connection:" header will be added for both "close" and "keep-alive" * connections. * Chunked encoding will not be used for the response. * Due to backward compatibility, responses still can be used with * HTTP/1.1 clients. * This option can be used to emulate HTTP/1.0 server (for response part * only as chunked encoding in requests (if any) is processed by MHD). * @note Available since #MHD_VERSION 0x00097308 */ MHD_RF_HTTP_1_0_SERVER = 1 << 1, /** * The same as #MHD_RF_HTTP_1_0_SERVER * @note Available since #MHD_VERSION 0x00096000 */ MHD_RF_HTTP_VERSION_1_0_RESPONSE = 1 << 1, /** * Disable sanity check preventing clients from manually * setting the HTTP content length option. * Allow to set several "Content-Length" headers. These headers will * be used even with replies without body. * @note Available since #MHD_VERSION 0x00096702 */ MHD_RF_INSANITY_HEADER_CONTENT_LENGTH = 1 << 2, /** * Enable sending of "Connection: keep-alive" header even for * HTTP/1.1 clients when "Keep-Alive" connection is used. * Disabled by default for HTTP/1.1 clients as per RFC. * @note Available since #MHD_VERSION 0x00097310 */ MHD_RF_SEND_KEEP_ALIVE_HEADER = 1 << 3, /** * Enable special processing of the response as body-less (with undefined * body size). No automatic "Content-Length" or "Transfer-Encoding: chunked" * headers are added when the response is used with #MHD_HTTP_NOT_MODIFIED * code or to respond to HEAD request. * The flag also allow to set arbitrary "Content-Length" by * MHD_add_response_header() function. * This flag value can be used only with responses created without body * (zero-size body). * Responses with this flag enabled cannot be used in situations where * reply body must be sent to the client. * This flag is primarily intended to be used when automatic "Content-Length" * header is undesirable in response to HEAD requests. * @note Available since #MHD_VERSION 0x00097701 */ MHD_RF_HEAD_ONLY_RESPONSE = 1 << 4 } _MHD_FIXED_FLAGS_ENUM; /** * MHD options (for future extensions). */ enum MHD_ResponseOptions { /** * End of the list of options. */ MHD_RO_END = 0 } _MHD_FIXED_ENUM; /** * Set special flags and options for a response. * * @param response the response to modify * @param flags to set for the response * @param ... #MHD_RO_END terminated list of options * @return #MHD_YES on success, #MHD_NO on error */ _MHD_EXTERN enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...); /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown * @param block_size preferred block size for querying crc (advisory only, * MHD may still call @a crc using smaller chunks); this * is essentially the buffer size used for IO, clients * should pick a value that is appropriate for IO and * memory performance requirements * @param crc callback to use to obtain response data * @param crc_cls extra argument to @a crc * @param crfc callback to call to free @a crc_cls resources * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc); /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the @a data portion of the response * @param data the data itself * @param must_free libmicrohttpd should free data when done * @param must_copy libmicrohttpd must make a copy of @a data * right away, the data may be released anytime after * this call returns * @return NULL on error (i.e. invalid arguments, out of memory) * @deprecated use #MHD_create_response_from_buffer instead * @ingroup response */ _MHD_DEPR_FUNC ( \ "MHD_create_response_from_data() is deprecated, use MHD_create_response_from_buffer()" \ ) \ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy); /** * Specification for how MHD should treat the memory buffer * given for the response. * @ingroup response */ enum MHD_ResponseMemoryMode { /** * Buffer is a persistent (static/global) buffer that won't change * for at least the lifetime of the response, MHD should just use * it, not free it, not copy it, just keep an alias to it. * @ingroup response */ MHD_RESPMEM_PERSISTENT, /** * Buffer is heap-allocated with `malloc()` (or equivalent) and * should be freed by MHD after processing the response has * concluded (response reference counter reaches zero). * The more portable way to automatically free the buffer is function * MHD_create_response_from_buffer_with_free_callback() with '&free' as * crfc parameter as it does not require to use the same runtime library. * @warning It is critical to make sure that the same C-runtime library * is used by both application and MHD (especially * important for W32). * @ingroup response */ MHD_RESPMEM_MUST_FREE, /** * Buffer is in transient memory, but not on the heap (for example, * on the stack or non-`malloc()` allocated) and only valid during the * call to #MHD_create_response_from_buffer. MHD must make its * own private copy of the data for processing. * @ingroup response */ MHD_RESPMEM_MUST_COPY } _MHD_FIXED_ENUM; /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param mode flags for buffer management * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *buffer, enum MHD_ResponseMemoryMode mode); /** * Create a response object with the content of provided statically allocated * buffer used as the response body. * * The buffer must be valid for the lifetime of the response. The easiest way * to achieve this is to use a statically allocated buffer. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_static (size_t size, const void *buffer); /** * Create a response object with the content of provided temporal buffer * used as the response body. * * An internal copy of the buffer will be made automatically, so buffer have * to be valid only during the call of this function (as a typical example: * buffer is a local (non-static) array). * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_copy (size_t size, const void *buffer); /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to free the @a buffer * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00096000 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *buffer, MHD_ContentReaderFreeCallback crfc); /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to cleanup, if set to NULL then callback * is not called * @param crfc_cls an argument for @a crfc * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097302 * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback_cls (size_t size, const void *buffer, MHD_ContentReaderFreeCallback crfc, void *crfc_cls); /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd (size_t size, int fd); /** * Create a response object with the response body created by reading * the provided pipe. * * The response object can be extended with header information and * then be used ONLY ONCE. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param fd file descriptor referring to a read-end of a pipe with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097102 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_pipe (int fd); /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd64 (uint64_t size, int fd); /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * Be careful! `off_t` may have been compiled to be a * 64-bit variable for MHD, in which case your application * also has to be compiled using the same options! Read * the MHD manual for more details. * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_DEPR_FUNC ( \ "Function MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()" \ ) \ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset); #if ! defined(_MHD_NO_DEPR_IN_MACRO) || defined(_MHD_NO_DEPR_FUNC) /* Substitute MHD_create_response_from_fd_at_offset64() instead of MHD_create_response_from_fd_at_offset() to minimize potential problems with different off_t sizes */ #define MHD_create_response_from_fd_at_offset(size,fd,offset) \ _MHD_DEPR_IN_MACRO ( \ "Usage of MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()") \ MHD_create_response_from_fd_at_offset64 ((size),(fd),(offset)) #endif /* !_MHD_NO_DEPR_IN_MACRO || _MHD_NO_DEPR_FUNC */ /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * reading file beyond 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset64 (uint64_t size, int fd, uint64_t offset); /** * Create a response object with an array of memory buffers * used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param iov the array for response data buffers, an internal copy of this * will be made * @param iovcnt the number of elements in @a iov * @param free_cb the callback to clean up any data associated with @a iov when * the response is destroyed. * @param cls the argument passed to @a free_cb * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097204 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, unsigned int iovcnt, MHD_ContentReaderFreeCallback free_cb, void *cls); /** * Create a response object with empty (zero size) body. * * The response object can be extended with header information and then be used * any number of times. * * This function is a faster equivalent of #MHD_create_response_from_buffer call * with zero size combined with call of #MHD_set_response_options. * * @param flags the flags for the new response object * @return NULL on error (i.e. invalid arguments, out of memory), * the pointer to the created response object otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_empty (enum MHD_ResponseFlags flags); /** * Enumeration for actions MHD should perform on the underlying socket * of the upgrade. This API is not finalized, and in particular * the final set of actions is yet to be decided. This is just an * idea for what we might want. */ enum MHD_UpgradeAction { /** * Close the socket, the application is done with it. * * Takes no extra arguments. */ MHD_UPGRADE_ACTION_CLOSE = 0, /** * Enable CORKing on the underlying socket. */ MHD_UPGRADE_ACTION_CORK_ON = 1, /** * Disable CORKing on the underlying socket. */ MHD_UPGRADE_ACTION_CORK_OFF = 2 } _MHD_FIXED_ENUM; /** * Handle given to the application to manage special * actions relating to MHD responses that "upgrade" * the HTTP protocol (i.e. to WebSockets). */ struct MHD_UpgradeResponseHandle; /** * This connection-specific callback is provided by MHD to * applications (unusual) during the #MHD_UpgradeHandler. * It allows applications to perform 'special' actions on * the underlying socket from the upgrade. * * @param urh the handle identifying the connection to perform * the upgrade @a action on. * @param action which action should be performed * @param ... arguments to the action (depends on the action) * @return #MHD_NO on error, #MHD_YES on success */ _MHD_EXTERN enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...); /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ typedef void (*MHD_UpgradeHandler)(void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh); /** * Create a response object that can be used for 101 UPGRADE * responses, for example to implement WebSockets. After sending the * response, control over the data stream is given to the callback (which * can then, for example, start some bi-directional communication). * If the response is queued for multiple connections, the callback * will be called for each connection. The callback * will ONLY be called after the response header was successfully passed * to the OS; if there are communication errors before, the usual MHD * connection error handling code will be performed. * * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS) * and setting correct HTTP headers for the upgrade must be done * manually (this way, it is possible to implement most existing * WebSocket versions using this API; in fact, this API might be useful * for any protocol switch, not just WebSockets). Note that * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 * Switching Protocols" (if the response code 101 is used). * * As usual, the response object can be extended with header * information and then be used any number of times (as long as the * header information is not connection-specific). * * @param upgrade_handler function to call with the "upgraded" socket * @param upgrade_handler_cls closure for @a upgrade_handler * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls); /** * Destroy a response object and associated resources. Note that * libmicrohttpd may keep some of the resources around if the response * is still in the queue for some clients, so the memory may not * necessarily be freed immediately. * * @param response response to destroy * @ingroup response */ _MHD_EXTERN void MHD_destroy_response (struct MHD_Response *response); /** * Add a header line to the response. * * When reply is generated with queued response, some headers are generated * automatically. Automatically generated headers are only sent to the client, * but not added back to the response object. * * The list of automatic headers: * + "Date" header is added automatically unless already set by * this function * @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK * + "Content-Length" is added automatically when required, attempt to set * it manually by this function is ignored. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * + "Transfer-Encoding" with value "chunked" is added automatically, * when chunked transfer encoding is used automatically. Same header with * the same value can be set manually by this function to enforce chunked * encoding, however for HTTP/1.0 clients chunked encoding will not be used * and manually set "Transfer-Encoding" header is automatically removed * for HTTP/1.0 clients * + "Connection" may be added automatically with value "Keep-Alive" (only * for HTTP/1.0 clients) or "Close". The header "Connection" with value * "Close" could be set by this function to enforce closure of * the connection after sending this response. "Keep-Alive" cannot be * enforced and will be removed automatically. * @see #MHD_RF_SEND_KEEP_ALIVE_HEADER * * Some headers are pre-processed by this function: * * "Connection" headers are combined into single header entry, value is * normilised, "Keep-Alive" tokens are removed. * * "Transfer-Encoding" header: the only one header is allowed, the only * allowed value is "chunked". * * "Date" header: the only one header is allowed, the second added header * replaces the first one. * * "Content-Length" application-defined header is not allowed. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * * Headers are used in order as they were added. * * @param response the response to add a header to * @param header the header name to add, no need to be static, an internal copy * will be created automatically * @param content the header value to add, no need to be static, an internal * copy will be created automatically * @return #MHD_YES on success, * #MHD_NO on error (i.e. invalid header or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content); /** * Add a footer line to the response. * * @param response response to remove a header from * @param footer the footer to delete * @param content value to delete * @return #MHD_NO on error (i.e. invalid footer or content format). * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content); /** * Delete a header (or footer) line from the response. * * For "Connection" headers this function remove all tokens from existing * value. Successful result means that at least one token has been removed. * If all tokens are removed from "Connection" header, the empty "Connection" * header removed. * * @param response response to remove a header from * @param header the header to delete * @param content value to delete * @return #MHD_NO on error (no such header known) * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content); /** * Get all of the headers (and footers) added to a response. * * @param response response to query * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup response */ _MHD_EXTERN int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls); /** * Get a particular header (or footer) from the response. * * @param response response to query * @param key which header to get * @return NULL if header does not exist * @ingroup response */ _MHD_EXTERN const char * MHD_get_response_header (struct MHD_Response *response, const char *key); /* ********************** PostProcessor functions ********************** */ /** * Create a `struct MHD_PostProcessor`. * * A `struct MHD_PostProcessor` can be used to (incrementally) parse * the data portion of a POST request. Note that some buggy browsers * fail to set the encoding type. If you want to support those, you * may have to call #MHD_set_connection_value with the proper encoding * type before creating a post processor (if no supported encoding * type is set, this function will fail). * * @param connection the connection on which the POST is * happening (used to determine the POST format) * @param buffer_size maximum number of bytes to use for * internal buffering (used only for the parsing, * specifically the parsing of the keys). A * tiny value (256-1024) should be sufficient. * Do NOT use a value smaller than 256. For good * performance, use 32 or 64k (i.e. 65536). * @param iter iterator to be called with the parsed data, * Must NOT be NULL. * @param iter_cls first argument to @a iter * @return NULL on error (out of memory, unsupported encoding), * otherwise a PP handle * @ingroup request */ _MHD_EXTERN struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iter, void *iter_cls); /** * Parse and process POST data. Call this function when POST data is * available (usually during an #MHD_AccessHandlerCallback) with the * "upload_data" and "upload_data_size". Whenever possible, this will * then cause calls to the #MHD_PostDataIterator. * * @param pp the post processor * @param post_data @a post_data_len bytes of POST data * @param post_data_len length of @a post_data * @return #MHD_YES on success, #MHD_NO on error * (out-of-memory, iterator aborted, parse error) * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len); /** * Release PostProcessor resources. * * @param pp the PostProcessor to destroy * @return #MHD_YES if processing completed nicely, * #MHD_NO if there were spurious characters / formatting * problems; it is common to ignore the return * value of this function * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp); /* ********************* Digest Authentication functions *************** */ /** * Length of the binary output of the MD5 hash function. * @sa #MHD_digest_get_hash_size() * @ingroup authentication */ #define MHD_MD5_DIGEST_SIZE 16 /** * Length of the binary output of the SHA-256 hash function. * @sa #MHD_digest_get_hash_size() * @ingroup authentication */ #define MHD_SHA256_DIGEST_SIZE 32 /** * Length of the binary output of the SHA-512/256 hash function. * @warning While this value is the same as the #MHD_SHA256_DIGEST_SIZE, * the calculated digests for SHA-256 and SHA-512/256 are different. * @sa #MHD_digest_get_hash_size() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ #define MHD_SHA512_256_DIGEST_SIZE 32 /** * Base type of hash calculation. * Used as part of #MHD_DigestAuthAlgo3 values. * * @warning Not used directly by MHD API. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestBaseAlgo { /** * Invalid hash algorithm value */ MHD_DIGEST_BASE_ALGO_INVALID = 0, /** * MD5 hash algorithm. * As specified by RFC1321 */ MHD_DIGEST_BASE_ALGO_MD5 = (1 << 0), /** * SHA-256 hash algorithm. * As specified by FIPS PUB 180-4 */ MHD_DIGEST_BASE_ALGO_SHA256 = (1 << 1), /** * SHA-512/256 hash algorithm. * As specified by FIPS PUB 180-4 */ MHD_DIGEST_BASE_ALGO_SHA512_256 = (1 << 2) } _MHD_FIXED_FLAGS_ENUM; /** * The flag indicating non-session algorithm types, * like 'MD5', 'SHA-256' or 'SHA-512-256'. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_ALGO3_NON_SESSION (1 << 6) /** * The flag indicating session algorithm types, * like 'MD5-sess', 'SHA-256-sess' or 'SHA-512-256-sess'. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_ALGO3_SESSION (1 << 7) /** * Digest algorithm identification * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthAlgo3 { /** * Unknown or wrong algorithm type. * Used in struct MHD_DigestAuthInfo to indicate client value that * cannot by identified. */ MHD_DIGEST_AUTH_ALGO3_INVALID = 0, /** * The 'MD5' algorithm, non-session version. */ MHD_DIGEST_AUTH_ALGO3_MD5 = MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'MD5-sess' algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION = MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The 'SHA-256' algorithm, non-session version. */ MHD_DIGEST_AUTH_ALGO3_SHA256 = MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'SHA-256-sess' algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION = MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The 'SHA-512-256' (SHA-512/256) algorithm. */ MHD_DIGEST_AUTH_ALGO3_SHA512_256 = MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION = MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_SESSION }; /** * Get digest size for specified algorithm. * * The size of the digest specifies the size of the userhash, userdigest * and other parameters which size depends on used hash algorithm. * @param algo3 the algorithm to check * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or * #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE) * or zero if the input value is not supported or not valid * @sa #MHD_digest_auth_calc_userdigest() * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN size_t MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3); /** * Digest algorithm identification, allow multiple selection. * * #MHD_DigestAuthAlgo3 always can be casted to #MHD_DigestAuthMultiAlgo3, but * not vice versa. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthMultiAlgo3 { /** * Unknown or wrong algorithm type. */ MHD_DIGEST_AUTH_MULT_ALGO3_INVALID = MHD_DIGEST_AUTH_ALGO3_INVALID, /** * The 'MD5' algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5 = MHD_DIGEST_AUTH_ALGO3_MD5, /** * The 'MD5-sess' algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION = MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, /** * The 'SHA-256' algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 = MHD_DIGEST_AUTH_ALGO3_SHA256, /** * The 'SHA-256-sess' algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, /** * The 'SHA-512-256' (SHA-512/256) algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256 = MHD_DIGEST_AUTH_ALGO3_SHA512_256, /** * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, /** * SHA-256 or SHA-512/256 non-session algorithm, MHD will choose * the preferred or the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_NON_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256 | MHD_DIGEST_AUTH_ALGO3_SHA512_256, /** * Any non-session algorithm, MHD will choose the preferred or * the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION = (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The SHA-256 or SHA-512/256 session algorithm. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION | MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, /** * Any session algorithm. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY_SESSION = (0x3F) | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The MD5 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_MD5 | MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION, /** * The SHA-256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 | MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION, /** * The SHA-512/256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256 | MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION, /** * The SHA-256 or SHA-512/256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_NON_SESSION | MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_SESSION, /** * Any algorithm, MHD will choose the preferred or the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY = (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION | MHD_DIGEST_AUTH_ALGO3_SESSION }; /** * Calculate "userhash", return it as binary data. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_bin the output buffer for userhash as binary data; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of userhash * upon return * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH) * @sa #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, void *userhash_bin, size_t bin_buf_size); /** * Calculate "userhash", return it as hexadecimal string. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_hex the output buffer for userhash as hex string; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3)*2 chars long * userhash zero-terminated string * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3)*2+1 chars long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_calc_userhash() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, char *userhash_hex, size_t hex_buf_size); /** * The type of username used by client in Digest Authorization header * * Values are sorted so simplified checks could be used. * For example: * * (value <= MHD_DIGEST_AUTH_UNAME_TYPE_INVALID) is true if no valid username * is provided by the client * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH) is true if username is * provided in any form * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD) is true if username is * provided in clear text (no userhash matching is needed) * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthUsernameType { /** * No username parameter in in Digest Authorization header. * This should be treated as an error. */ MHD_DIGEST_AUTH_UNAME_TYPE_MISSING = 0, /** * The 'username' parameter is used to specify the username. */ MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD = (1 << 2), /** * The username is specified by 'username*' parameter with * the extended notation (see RFC 5987 #section-3.2.1). * The only difference between standard and extended types is * the way how username value is encoded in the header. */ MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED = (1 << 3), /** * The username provided in form of 'userhash' as * specified by RFC 7616 #section-3.4.4. * @sa #MHD_digest_auth_calc_userhash_hex(), #MHD_digest_auth_calc_userhash() */ MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH = (1 << 1), /** * The invalid combination of username parameters are used by client. * Either: * * both 'username' and 'username*' are used * * 'username*' is used with 'userhash=true' * * 'username*' used with invalid extended notation * * 'username' is not hexadecimal string, while 'userhash' set to 'true' */ MHD_DIGEST_AUTH_UNAME_TYPE_INVALID = (1 << 0) } _MHD_FIXED_ENUM; /** * The QOP ('quality of protection') types. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthQOP { /** * Invalid/unknown QOP. * Used in struct MHD_DigestAuthInfo to indicate client value that * cannot by identified. */ MHD_DIGEST_AUTH_QOP_INVALID = 0, /** * No QOP parameter. * As described in old RFC 2069 original specification. * This mode is not allowed by latest RFCs and should be used only to * communicate with clients that do not support more modern modes (with QOP * parameter). * This mode is less secure than other modes and inefficient. */ MHD_DIGEST_AUTH_QOP_NONE = 1 << 0, /** * The 'auth' QOP type. */ MHD_DIGEST_AUTH_QOP_AUTH = 1 << 1, /** * The 'auth-int' QOP type. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_QOP_AUTH_INT = 1 << 2 } _MHD_FIXED_FLAGS_ENUM; /** * The QOP ('quality of protection') types, multiple selection. * * #MHD_DigestAuthQOP always can be casted to #MHD_DigestAuthMultiQOP, but * not vice versa. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthMultiQOP { /** * Invalid/unknown QOP. */ MHD_DIGEST_AUTH_MULT_QOP_INVALID = MHD_DIGEST_AUTH_QOP_INVALID, /** * No QOP parameter. * As described in old RFC 2069 original specification. * This mode is not allowed by latest RFCs and should be used only to * communicate with clients that do not support more modern modes (with QOP * parameter). * This mode is less secure than other modes and inefficient. */ MHD_DIGEST_AUTH_MULT_QOP_NONE = MHD_DIGEST_AUTH_QOP_NONE, /** * The 'auth' QOP type. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH = MHD_DIGEST_AUTH_QOP_AUTH, /** * The 'auth-int' QOP type. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH_INT = MHD_DIGEST_AUTH_QOP_AUTH_INT, /** * The 'auth' QOP type OR the old RFC2069 (no QOP) type. * In other words: any types except 'auth-int'. * RFC2069-compatible mode is allowed, thus this value should be used only * when it is really necessary. */ MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT = MHD_DIGEST_AUTH_QOP_NONE | MHD_DIGEST_AUTH_QOP_AUTH, /** * Any 'auth' QOP type ('auth' or 'auth-int'). * Currently supported as 'auth' QOP type only. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH_ANY = MHD_DIGEST_AUTH_QOP_AUTH | MHD_DIGEST_AUTH_QOP_AUTH_INT } _MHD_FIXED_ENUM; /** * The invalid value of 'nc' parameter in client Digest Authorization header. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_INVALID_NC_VALUE (0) /** * Information from Digest Authorization client's header. * * All buffers pointed by any struct members are freed when #MHD_free() is * called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure * @note Available since #MHD_VERSION 0x00097701 */ struct MHD_DigestAuthInfo { /** * The algorithm as defined by client. * Set automatically to MD5 if not specified by client. * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! */ enum MHD_DigestAuthAlgo3 algo3; /** * The type of username used by client. */ enum MHD_DigestAuthUsernameType uname_type; /** * The username string. * Used only if username type is standard or extended, always NULL otherwise. * If extended notation is used, this string is pct-decoded string * with charset and language tag removed (i.e. it is original username * extracted from the extended notation). * When userhash is used by the client, this member is NULL and * @a userhash_hex and @a userhash_bin are set. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username. * When the @a username is NULL, this member is always zero. */ size_t username_len; /** * The userhash string. * Valid only if username type is userhash. * This is unqoted string without decoding of the hexadecimal * digits (as provided by the client). * The buffer pointed by the @a userhash_hex becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @sa #MHD_digest_auth_calc_userhash_hex() */ char *userhash_hex; /** * The length of the @a userhash_hex in characters. * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters. * When the @a userhash_hex is NULL, this member is always zero. */ size_t userhash_hex_len; /** * The userhash decoded to binary form. * Used only if username type is userhash, always NULL otherwise. * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes * long. * The valid size should be #MHD_digest_get_hash_size(algo3) bytes. * The buffer pointed by the @a userhash_bin becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @warning This is a binary data, no zero termination. * @warning To avoid buffer overruns, always check the size of the data before * use, because @a userhash_bin can point even to zero-sized * data. * @sa #MHD_digest_auth_calc_userhash() */ uint8_t *userhash_bin; /** * The 'opaque' parameter value, as specified by client. * NULL if not specified by client. * The buffer pointed by the @a opaque becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *opaque; /** * The length of the @a opaque. * When the @a opaque is NULL, this member is always zero. */ size_t opaque_len; /** * The 'realm' parameter value, as specified by client. * NULL if not specified by client. * The buffer pointed by the @a realm becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *realm; /** * The length of the @a realm. * When the @a realm is NULL, this member is always zero. */ size_t realm_len; /** * The 'qop' parameter value. */ enum MHD_DigestAuthQOP qop; /** * The length of the 'cnonce' parameter value, including possible * backslash-escape characters. * 'cnonce' is used in hash calculation, which is CPU-intensive procedure. * An application may want to reject too large cnonces to limit the CPU load. * A few kilobytes is a reasonable limit, typically cnonce is just 32-160 * characters long. */ size_t cnonce_len; /** * The nc parameter value. * Can be used by application to limit the number of nonce re-uses. If @a nc * is higher than application wants to allow, then "auth required" response * with 'stale=true' could be used to force client to retry with the fresh * 'nonce'. * If not specified by client or does not have hexadecimal digits only, the * value is #MHD_DIGEST_AUTH_INVALID_NC_VALUE. */ uint32_t nc; }; /** * Get information about Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request; * a pointer to the structure with information if the valid request * header found, free using #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthInfo * MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection); /** * Information from Digest Authorization client's header. * * All buffers pointed by any struct members are freed when #MHD_free() is * called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure * @note Available since #MHD_VERSION 0x00097701 */ struct MHD_DigestAuthUsernameInfo { /** * The algorithm as defined by client. * Set automatically to MD5 if not specified by client. * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! */ enum MHD_DigestAuthAlgo3 algo3; /** * The type of username used by client. * The 'invalid' and 'missing' types are not used in this structure, * instead NULL is returned by #MHD_digest_auth_get_username3(). */ enum MHD_DigestAuthUsernameType uname_type; /** * The username string. * Used only if username type is standard or extended, always NULL otherwise. * If extended notation is used, this string is pct-decoded string * with charset and language tag removed (i.e. it is original username * extracted from the extended notation). * When userhash is used by the client, this member is NULL and * @a userhash_hex and @a userhash_bin are set. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username. * When the @a username is NULL, this member is always zero. */ size_t username_len; /** * The userhash string. * Valid only if username type is userhash. * This is unqoted string without decoding of the hexadecimal * digits (as provided by the client). * The buffer pointed by the @a userhash_hex becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @sa #MHD_digest_auth_calc_userhash_hex() */ char *userhash_hex; /** * The length of the @a userhash_hex in characters. * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters. * When the @a userhash_hex is NULL, this member is always zero. */ size_t userhash_hex_len; /** * The userhash decoded to binary form. * Used only if username type is userhash, always NULL otherwise. * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes * long. * The valid size should be #MHD_digest_get_hash_size(algo3) bytes. * The buffer pointed by the @a userhash_bin becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @warning This is a binary data, no zero termination. * @warning To avoid buffer overruns, always check the size of the data before * use, because @a userhash_bin can point even to zero-sized * data. * @sa #MHD_digest_auth_calc_userhash() */ uint8_t *userhash_bin; }; /** * Get the username from Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request, * or no username parameter is present in the header, or username is * provided incorrectly by client (see description for * #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID); * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @sa #MHD_digest_auth_get_request_info3() provides more complete information * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthUsernameInfo * MHD_digest_auth_get_username3 (struct MHD_Connection *connection); /** * The result of digest authentication of the client. * * All error values are zero or negative. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthResult { /** * Authentication OK. */ MHD_DAUTH_OK = 1, /** * General error, like "out of memory". */ MHD_DAUTH_ERROR = 0, /** * No "Authorization" header or wrong format of the header. * Also may be returned if required parameters in client Authorisation header * are missing or broken (in invalid format). */ MHD_DAUTH_WRONG_HEADER = -1, /** * Wrong 'username'. */ MHD_DAUTH_WRONG_USERNAME = -2, /** * Wrong 'realm'. */ MHD_DAUTH_WRONG_REALM = -3, /** * Wrong 'URI' (or URI parameters). */ MHD_DAUTH_WRONG_URI = -4, /** * Wrong 'qop'. */ MHD_DAUTH_WRONG_QOP = -5, /** * Wrong 'algorithm'. */ MHD_DAUTH_WRONG_ALGO = -6, /** * Too large (>64 KiB) Authorization parameter value. */ MHD_DAUTH_TOO_LARGE = -15, /* The different form of naming is intentionally used for the results below, * as they are more important */ /** * The 'nonce' is too old. Suggest the client to retry with the same * username and password to get the fresh 'nonce'. * The validity of the 'nonce' may be not checked. */ MHD_DAUTH_NONCE_STALE = -17, /** * The 'nonce' was generated by MHD for other conditions. * This value is only returned if #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE * is set to anything other than #MHD_DAUTH_BIND_NONCE_NONE. * The interpretation of this code could be different. For example, if * #MHD_DAUTH_BIND_NONCE_URI is set and client just used the same 'nonce' for * another URI, the code could be handled as #MHD_DAUTH_NONCE_STALE as * RFCs allow nonces re-using for other URIs in the same "protection * space". However, if only #MHD_DAUTH_BIND_NONCE_CLIENT_IP bit is set and * it is know that clients have fixed IP addresses, this return code could * be handled like #MHD_DAUTH_NONCE_WRONG. */ MHD_DAUTH_NONCE_OTHER_COND = -18, /** * The 'nonce' is wrong. May indicate an attack attempt. */ MHD_DAUTH_NONCE_WRONG = -33, /** * The 'response' is wrong. Typically it means that wrong password used. * May indicate an attack attempt. */ MHD_DAUTH_RESPONSE_WRONG = -34 }; /** * Authenticates the authorization header sent by the client. * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password matching the @a username (and the @a realm) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3); /** * Calculate userdigest, return it as a binary data. * * The "userdigest" is the hash of the "username:realm:password" string. * * The "userdigest" can be used to avoid storing the password in clear text * in database/files * * This function is designed to improve security of stored credentials, * the "userdigest" does not improve security of the authentication process. * * The results can be used to store username & userdigest pairs instead of * username & password pairs. To further improve security, application may * store username & userhash & userdigest triplets. * * @param algo3 the digest algorithm * @param username the username * @param realm the realm * @param password the password * @param[out] userdigest_bin the output buffer for userdigest; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of * userdigest upon return * @param bin_buf_size the size of the @a userdigest_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, const char *password, void *userdigest_bin, size_t bin_buf_size); /** * Authenticates the authorization header sent by the client by using * hash of "username:realm:password". * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param userdigest the precalculated binary hash of the string * "username:realm:password", * see #MHD_digest_auth_calc_userdigest() * @param userdigest_size the size of the @a userdigest in bytes, must match the * hashing algorithm (see #MHD_MD5_DIGEST_SIZE, * #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE, * #MHD_digest_get_hash_size()) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter; * more than one base algorithms (MD5, SHA-256, SHA-512/256) * cannot be used at the same time for this function * as @a userdigest must match specified algorithm * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @sa #MHD_digest_auth_calc_userdigest() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const void *userdigest, size_t userdigest_size, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3); /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed (by #MHD_destroy_response()) after call of * this function. * * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was * not set, because such response should be backward-compatible with RFC 2069. * * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no * 'charset'). For better compatibility with clients, it is recommended (but * not required) to set @a domain to NULL in this mode. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host); * this list provides information for the client only and does * not actually restrict anything on the server side * @param response the reply to send; should contain the "access denied" * body; * note: this function sets the "WWW Authenticate" header and * the caller should not set this header; * the NULL is tolerated * @param signal_stale if set to #MHD_YES then indication of stale nonce used in * the client's request is signalled by adding 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use; if several algorithms are allowed * then MD5 is preferred (currently, may be changed in next * versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, allowing client to provide * hash("username:realm") instead of the username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding for * the username is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_required_response3 (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 algo, int userhash_support, int prefer_utf8); /** * Constant to indicate that the nonce of the provided * authentication code was wrong. * Used as return code by #MHD_digest_auth_check(), #MHD_digest_auth_check2(), * #MHD_digest_auth_check_digest(), #MHD_digest_auth_check_digest2(). * @ingroup authentication */ #define MHD_INVALID_NONCE -1 /** * Get the username from the authorization header sent by the client * * This function supports username in standard and extended notations. * "userhash" is not supported by this function. * * @param connection The MHD connection structure * @return NULL if no username could be found, username provided as * "userhash", extended notation broken or memory allocation error * occurs; * a pointer to the username if found, free using #MHD_free(). * @warning Returned value must be freed by #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @ingroup authentication */ _MHD_EXTERN char * MHD_digest_auth_get_username (struct MHD_Connection *connection); /** * Which digest algorithm should MHD use for HTTP digest authentication? * Used as parameter for #MHD_digest_auth_check2(), * #MHD_digest_auth_check_digest2(), #MHD_queue_auth_fail_response2(). */ enum MHD_DigestAuthAlgorithm { /** * MHD should pick (currently defaults to MD5). */ MHD_DIGEST_ALG_AUTO = 0, /** * Force use of MD5. */ MHD_DIGEST_ALG_MD5, /** * Force use of SHA-256. */ MHD_DIGEST_ALG_SHA256 } _MHD_FIXED_ENUM; /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo); /** * Authenticates the authorization header sent by the client. * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility). * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future. * If you want to be sure you get MD5, use #MHD_digest_auth_check2() * and specify MD5 explicitly. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout); /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary MD5 sum * for the precalculated hash value "username:realm:password" * of @a digest_size bytes * @param digest_size number of bytes in @a digest (size must match @a algo!) * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, size_t digest_size, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo); /** * Authenticates the authorization header sent by the client * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed * size). * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary hash * for the precalculated hash value "username:realm:password"; * length must be #MHD_MD5_DIGEST_SIZE bytes * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096000 * @deprecated use #MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout); /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed after call of this function. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @param algo digest algorithm to use * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_queue_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo); /** * Queues a response to request authentication from the client. * For now uses MD5 (for backwards-compatibility). Still, if you * need to be sure, use #MHD_queue_auth_fail_response2(). * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed after call of this function. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale); /* ********************* Basic Authentication functions *************** */ /** * Information decoded from Basic Authentication client's header. * * The username and the password are technically allowed to have binary zeros, * username_len and password_len could be used to detect such situations. * * The buffers pointed by username and password members are freed * when #MHD_free() is called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure */ struct MHD_BasicAuthInfo { /** * The username, cannot be NULL. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username, not including zero-termination */ size_t username_len; /** * The password, may be NULL if password is not encoded by the client. * The buffer pointed by the @a password becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *password; /** * The length of the @a password, not including zero-termination; * when the @a password is NULL, the length is always zero. */ size_t password_len; }; /** * Get the username and password from the Basic Authorisation header * sent by the client * * @param connection the MHD connection structure * @return NULL if no valid Basic Authentication header is present in * current request, or * pointer to structure with username and password, which must be * freed by #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_BasicAuthInfo * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection); /** * Queues a response to request basic authentication from the client. * * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * See RFC 7617#section-2 for details. * * The @a response is modified by this function. The modified response object * can be used to respond subsequent requests by #MHD_queue_response() * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again * with MHD_queue_basic_auth_required_response3() function. The response could * be destroyed right after call of this function. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will * be added, indicating for client that UTF-8 encoding * is preferred * @param response the response object to modify and queue; the NULL * is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097704 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_required_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response); /** * Get the username and password from the basic authorization header sent by the client * * @param connection The MHD connection structure * @param[out] password a pointer for the password, free using #MHD_free(). * @return NULL if no username could be found, a pointer * to the username if found, free using #MHD_free(). * @deprecated use #MHD_basic_auth_get_username_password3() * @ingroup authentication */ _MHD_EXTERN char * MHD_basic_auth_get_username_password (struct MHD_Connection *connection, char **password); /** * Queues a response to request basic authentication from the client * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param response response object to modify and queue; the NULL is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_basic_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection, const char *realm, struct MHD_Response *response); /* ********************** generic query functions ********************** */ /** * Obtain information about the given connection. * The returned pointer is invalidated with the next call of this function or * when the connection is closed. * * @param connection what connection to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType info_type, ...); /** * MHD connection options. Given to #MHD_set_connection_option to * set custom options for a particular connection. */ enum MHD_CONNECTION_OPTION { /** * Set a custom timeout for the given connection. Specified * as the number of seconds, given as an `unsigned int`. Use * zero for no timeout. * If timeout was set to zero (or unset) before, setup of new value by * MHD_set_connection_option() will reset timeout timer. * Values larger than (UINT64_MAX / 2000 - 1) will * be clipped to this number. */ MHD_CONNECTION_OPTION_TIMEOUT } _MHD_FIXED_ENUM; /** * Set a custom option for the given connection, overriding defaults. * * @param connection connection to modify * @param option option to set * @param ... arguments to the option, depending on the option type * @return #MHD_YES on success, #MHD_NO if setting the option failed * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_set_connection_option (struct MHD_Connection *connection, enum MHD_CONNECTION_OPTION option, ...); /** * Information about an MHD daemon. */ union MHD_DaemonInfo { /** * Size of the key, no longer supported. * @deprecated */ size_t key_size; /** * Size of the mac key, no longer supported. * @deprecated */ size_t mac_key_size; /** * Socket, returned for #MHD_DAEMON_INFO_LISTEN_FD. */ MHD_socket listen_fd; /** * Bind port number, returned for #MHD_DAEMON_INFO_BIND_PORT. */ uint16_t port; /** * epoll FD, returned for #MHD_DAEMON_INFO_EPOLL_FD. */ int epoll_fd; /** * Number of active connections, for #MHD_DAEMON_INFO_CURRENT_CONNECTIONS. */ unsigned int num_connections; /** * Combination of #MHD_FLAG values, for #MHD_DAEMON_INFO_FLAGS. * This value is actually a bitfield. * Note: flags may differ from original 'flags' specified for * daemon, especially if #MHD_USE_AUTO was set. */ enum MHD_FLAG flags; }; /** * Obtain information about the given daemon. * The returned pointer is invalidated with the next call of this function or * when the daemon is stopped. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType info_type, ...); /** * Obtain the version of this library * * @return static version string, e.g. "0.9.9" * @ingroup specialized */ _MHD_EXTERN const char * MHD_get_version (void); /** * Obtain the version of this library as a binary value. * * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of * compiled MHD binary) * @note Available since #MHD_VERSION 0x00097601 * @ingroup specialized */ _MHD_EXTERN uint32_t MHD_get_version_bin (void); /** * Types of information about MHD features, * used by #MHD_is_feature_supported(). */ enum MHD_FEATURE { /** * Get whether messages are supported. If supported then in debug * mode messages can be printed to stderr or to external logger. */ MHD_FEATURE_MESSAGES = 1, /** * Get whether HTTPS is supported. If supported then flag * #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST, * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE, * #MHD_OPTION_HTTPS_PRIORITIES can be used. */ MHD_FEATURE_TLS = 2, MHD_FEATURE_SSL = 2, /** * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is * supported. */ MHD_FEATURE_HTTPS_CERT_CALLBACK = 3, /** * Get whether IPv6 is supported. If supported then flag * #MHD_USE_IPv6 can be used. */ MHD_FEATURE_IPv6 = 4, /** * Get whether IPv6 without IPv4 is supported. If not supported * then IPv4 is always enabled in IPv6 sockets and * flag #MHD_USE_DUAL_STACK is always used when #MHD_USE_IPv6 is * specified. */ MHD_FEATURE_IPv6_ONLY = 5, /** * Get whether `poll()` is supported. If supported then flag * #MHD_USE_POLL can be used. */ MHD_FEATURE_POLL = 6, /** * Get whether `epoll()` is supported. If supported then Flags * #MHD_USE_EPOLL and * #MHD_USE_EPOLL_INTERNAL_THREAD can be used. */ MHD_FEATURE_EPOLL = 7, /** * Get whether shutdown on listen socket to signal other * threads is supported. If not supported flag * #MHD_USE_ITC is automatically forced. */ MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8, /** * Get whether socketpair is used internally instead of pipe to * signal other threads. */ MHD_FEATURE_SOCKETPAIR = 9, /** * Get whether TCP Fast Open is supported. If supported then * flag #MHD_USE_TCP_FASTOPEN and option * #MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. */ MHD_FEATURE_TCP_FASTOPEN = 10, /** * Get whether HTTP Basic authorization is supported. If supported * then functions #MHD_basic_auth_get_username_password and * #MHD_queue_basic_auth_fail_response can be used. */ MHD_FEATURE_BASIC_AUTH = 11, /** * Get whether HTTP Digest authorization is supported. If * supported then options #MHD_OPTION_DIGEST_AUTH_RANDOM, * #MHD_OPTION_NONCE_NC_SIZE and * #MHD_digest_auth_check() can be used. */ MHD_FEATURE_DIGEST_AUTH = 12, /** * Get whether postprocessor is supported. If supported then * functions #MHD_create_post_processor(), #MHD_post_process() and * #MHD_destroy_post_processor() can * be used. */ MHD_FEATURE_POSTPROCESSOR = 13, /** * Get whether password encrypted private key for HTTPS daemon is * supported. If supported then option * ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used. */ MHD_FEATURE_HTTPS_KEY_PASSWORD = 14, /** * Get whether reading files beyond 2 GiB boundary is supported. * If supported then #MHD_create_response_from_fd(), * #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset() * and #MHD_create_response_from_fd_at_offset64() can be used with sizes and * offsets larger than 2 GiB. If not supported value of size+offset is * limited to 2 GiB. */ MHD_FEATURE_LARGE_FILE = 15, /** * Get whether MHD set names on generated threads. */ MHD_FEATURE_THREAD_NAMES = 16, MHD_THREAD_NAMES = 16, /** * Get whether HTTP "Upgrade" is supported. * If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and * #MHD_create_response_for_upgrade() can be used. */ MHD_FEATURE_UPGRADE = 17, /** * Get whether it's safe to use same FD for multiple calls of * #MHD_create_response_from_fd() and whether it's safe to use single * response generated by #MHD_create_response_from_fd() with multiple * connections at same time. * If #MHD_is_feature_supported() return #MHD_NO for this feature then * usage of responses with same file FD in multiple parallel threads may * results in incorrect data sent to remote client. * It's always safe to use same file FD in multiple responses if MHD * is run in any single thread mode. */ MHD_FEATURE_RESPONSES_SHARED_FD = 18, /** * Get whether MHD support automatic detection of bind port number. * @sa #MHD_DAEMON_INFO_BIND_PORT */ MHD_FEATURE_AUTODETECT_BIND_PORT = 19, /** * Get whether MHD supports automatic SIGPIPE suppression. * If SIGPIPE suppression is not supported, application must handle * SIGPIPE signal by itself. */ MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20, /** * Get whether MHD use system's sendfile() function to send * file-FD based responses over non-TLS connections. * @note Since v0.9.56 */ MHD_FEATURE_SENDFILE = 21, /** * Get whether MHD supports threads. */ MHD_FEATURE_THREADS = 22, /** * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK2 is * supported. */ MHD_FEATURE_HTTPS_CERT_CALLBACK2 = 23, /** * Get whether automatic parsing of HTTP Cookie header is supported. * If disabled, no MHD_COOKIE_KIND will be generated by MHD. * MHD versions before 0x00097701 always support cookie parsing. * @note Available since #MHD_VERSION 0x01000200 */ MHD_FEATURE_COOKIE_PARSING = 24, /** * Get whether the early version the Digest Authorization (RFC 2069) is * supported (digest authorisation without QOP parameter). * Since #MHD_VERSION 0x00097701 it is always supported if Digest Auth * module is built. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_RFC2069 = 25, /** * Get whether the MD5-based hashing algorithms are supported for Digest * Authorization. * Currently it is always supported if Digest Auth module is built * unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_MD5 = 26, /** * Get whether the SHA-256-based hashing algorithms are supported for Digest * Authorization. * It is always supported since #MHD_VERSION 0x00096200 if Digest Auth * module is built unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_SHA256 = 27, /** * Get whether the SHA-512/256-based hashing algorithms are supported * for Digest Authorization. * It it always supported since #MHD_VERSION 0x00097701 if Digest Auth * module is built unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_SHA512_256 = 28, /** * Get whether QOP with value 'auth-int' (authentication with integrity * protection) is supported for Digest Authorization. * Currently it is always not supported. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_AUTH_INT = 29, /** * Get whether 'session' algorithms (like 'MD5-sess') are supported for Digest * Authorization. * Currently it is always not supported. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION = 30, /** * Get whether 'userhash' is supported for Digest Authorization. * It is always supported since #MHD_VERSION 0x00097701 if Digest Auth * module is built. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_USERHASH = 31, /** * Get whether any of hashing algorithms is implemented by external * function (like TLS library) and may fail due to external conditions, * like "out-of-memory". * * If result is #MHD_YES then functions which use hash calculations * like #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_check3() and others * potentially may fail even with valid input because of out-of-memory error * or crypto accelerator device failure, however in practice such fails are * unlikely. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_EXTERN_HASH = 32, /** * Get whether MHD was built with asserts enabled. * For debug builds the error log is always enabled even if #MHD_USE_ERROR_LOG * is not specified for daemon. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DEBUG_BUILD = 33, /** * Get whether MHD was build with support for overridable FD_SETSIZE. * This feature should be always available when the relevant platform ability * is detected. * @sa #MHD_OPTION_APP_FD_SETSIZE * @note Available since #MHD_VERSION 0x00097705 */ MHD_FEATURE_FLEXIBLE_FD_SETSIZE = 34 }; #define MHD_FEATURE_HTTPS_COOKIE_PARSING _MHD_DEPR_IN_MACRO ( \ "Value MHD_FEATURE_HTTPS_COOKIE_PARSING is deprecated, use MHD_FEATURE_COOKIE_PARSING" \ ) MHD_FEATURE_COOKIE_PARSING /** * Get information about supported MHD features. * Indicate that MHD was compiled with or without support for * particular feature. Some features require additional support * by kernel. Kernel support is not checked by this function. * * @param feature type of requested information * @return #MHD_YES if feature is supported by MHD, #MHD_NO if * feature is not supported or feature is unknown. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_is_feature_supported (enum MHD_FEATURE feature); MHD_C_DECLRATIONS_FINISH_HERE_ #endif libmicrohttpd-1.0.2/src/include/microhttpd_ws.h0000644000175000017500000013324114760713577016575 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd_ws.h * @brief interface for experimental web socket extension to libmicrohttpd * @author David Gausmann */ /* * *** WARNING! *** * * The websockets interface is currently in "experimental" stage. * * * It does not work on architectures with endianness different from * * * big endian and little endian and may have some portability issues.* * * API and ABI are not yet stable. * */ #ifndef MHD_MICROHTTPD_WS_H #define MHD_MICROHTTPD_WS_H #ifdef __cplusplus extern "C" { #if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif /** * @brief Handle for the encoding/decoding of websocket data * (one stream is used per websocket) * @ingroup websocket */ struct MHD_WebSocketStream; /** * @brief Flags for the initialization of a websocket stream * `struct MHD_WebSocketStream` used by * #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). * @ingroup websocket */ enum MHD_WEBSOCKET_FLAG { /** * The websocket stream is initialized in server mode (default). * Thus all outgoing payload will not be "masked". * All incoming payload must be masked. * This flag cannot be used together with #MHD_WEBSOCKET_FLAG_CLIENT */ MHD_WEBSOCKET_FLAG_SERVER = 0, /** * The websocket stream is initialized in client mode. * You will usually never use that mode in combination with libmicrohttpd, * because libmicrohttpd provides a server and not a client. * In client mode all outgoing payload will be "masked" * (XOR-ed with random values). * All incoming payload must be unmasked. * If you use this mode, you must always call #MHD_websocket_stream_init2() * instead of #MHD_websocket_stream_init(), because you need * to pass a random number generator callback function for masking. * This flag cannot be used together with #MHD_WEBSOCKET_FLAG_SERVER */ MHD_WEBSOCKET_FLAG_CLIENT = 1, /** * You don't want to get fragmented data while decoding (default). * Fragmented frames will be internally put together until * they are complete. * Whether or not data is fragmented is decided * by the sender of the data during encoding. * This cannot be used together with #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS */ MHD_WEBSOCKET_FLAG_NO_FRAGMENTS = 0, /** * You want fragmented data, if it appears while decoding. * You will receive the content of the fragmented frame, * but if you are decoding text, you will never get an unfinished * UTF-8 sequence (if the sequence appears between two fragments). * Instead the text will end before the unfinished UTF-8 sequence. * With the next fragment, which finishes the UTF-8 sequence, * you will get the complete UTF-8 sequence. * This cannot be used together with #MHD_WEBSOCKET_FLAG_NO_FRAGMENTS */ MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS = 2, /** * If the websocket stream becomes invalid during decoding due to * protocol errors, a matching close frame will automatically * be generated. * The close frame will be returned via the parameters * `payload` and `payload_len` of #MHD_websocket_decode() and * the return value is negative * (a value of `enum MHD_WEBSOCKET_STATUS`). * The generated close frame must be freed by the caller * with #MHD_websocket_free(). */ MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR = 4 }; /** * @brief Enum to specify the fragmenting behavior * while encoding with #MHD_websocket_encode_text() or * #MHD_websocket_encode_binary(). * @ingroup websocket */ enum MHD_WEBSOCKET_FRAGMENTATION { /** * You don't want to use fragmentation. * The encoded frame consists of only one frame. */ MHD_WEBSOCKET_FRAGMENTATION_NONE = 0, /** * You want to use fragmentation. * The encoded frame is the first frame of * a series of data frames of the same type * (text or binary). * You may send control frames (ping, pong or close) * between these data frames. */ MHD_WEBSOCKET_FRAGMENTATION_FIRST = 1, /** * You want to use fragmentation. * The encoded frame is not the first frame of * the series of data frames, but also not the last one. * You may send control frames (ping, pong or close) * between these data frames. */ MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING = 2, /** * You want to use fragmentation. * The encoded frame is the last frame of * the series of data frames, but also not the first one. * After this frame, you may send all types of frames again. */ MHD_WEBSOCKET_FRAGMENTATION_LAST = 3 }; /** * @brief Enum of the return value for almost every MHD_websocket function. * Errors are negative and values equal to or above zero mean a success. * Positive values are only used by #MHD_websocket_decode(). * @ingroup websocket */ enum MHD_WEBSOCKET_STATUS { /** * The call succeeded. * For #MHD_websocket_decode() this means that no error occurred, * but also no frame has been completed yet. * For other functions this means simply a success. */ MHD_WEBSOCKET_STATUS_OK = 0, /** * #MHD_websocket_decode() has decoded a text frame. * The parameters `payload` and `payload_len` are filled with * the decoded text (if any). */ MHD_WEBSOCKET_STATUS_TEXT_FRAME = 0x1, /** * #MHD_websocket_decode() has decoded a binary frame. * The parameters `payload` and `payload_len` are filled with * the decoded binary data (if any). */ MHD_WEBSOCKET_STATUS_BINARY_FRAME = 0x2, /** * #MHD_websocket_decode() has decoded a close frame. * This means you must close the socket using #MHD_upgrade_action() * with #MHD_UPGRADE_ACTION_CLOSE. * You may respond with a close frame before closing. * The parameters `payload` and `payload_len` are filled with * the close reason (if any). * The close reason starts with a two byte sequence of close code * in network byte order (see `enum MHD_WEBSOCKET_CLOSEREASON`). * After these two bytes a UTF-8 encoded close reason may follow. * You can call #MHD_websocket_split_close_reason() to split that * close reason. */ MHD_WEBSOCKET_STATUS_CLOSE_FRAME = 0x8, /** * #MHD_websocket_decode() has decoded a ping frame. * You should respond to this with a pong frame. * The pong frame must contain the same binary data as * the corresponding ping frame (if it had any). * The parameters `payload` and `payload_len` are filled with * the binary ping data (if any). */ MHD_WEBSOCKET_STATUS_PING_FRAME = 0x9, /** * #MHD_websocket_decode() has decoded a pong frame. * You should usually only receive pong frames if you sent * a ping frame before. * The binary data should be equal to your ping frame and can be * used to distinguish the response if you sent multiple ping frames. * The parameters `payload` and `payload_len` are filled with * the binary pong data (if any). */ MHD_WEBSOCKET_STATUS_PONG_FRAME = 0xA, /** * #MHD_websocket_decode() has decoded a text frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded text (if any). * This is like #MHD_WEBSOCKET_STATUS_TEXT_FRAME, but it can only * appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS during * the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT = 0x11, /** * #MHD_websocket_decode() has decoded a binary frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded binary data (if any). * This is like #MHD_WEBSOCKET_STATUS_BINARY_FRAME, but it can only * appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS during * the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT = 0x12, /** * #MHD_websocket_decode() has decoded the next text frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded text (if any). * This is like #MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, but it appears * only after the first and before the last fragment of a series of fragments. * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS * during the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT = 0x21, /** * #MHD_websocket_decode() has decoded the next binary frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded binary data (if any). * This is like #MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, but it appears * only after the first and before the last fragment of a series of fragments. * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS * during the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT = 0x22, /** * #MHD_websocket_decode() has decoded the last text frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded text (if any). * This is like #MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, but it appears * only for the last fragment of a series of fragments. * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS * during the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT = 0x41, /** * #MHD_websocket_decode() has decoded the last binary frame fragment. * The parameters `payload` and `payload_len` are filled with * the decoded binary data (if any). * This is like #MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, but it appears * only for the last fragment of a series of fragments. * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS * during the call of #MHD_websocket_stream_init() or * #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT = 0x42, /** * The call failed and the stream is invalid now for decoding. * You must close the websocket now using #MHD_upgrade_action() * with #MHD_UPGRADE_ACTION_CLOSE. * You may send a close frame before closing. * This is only used by #MHD_websocket_decode() and happens * if the stream contains errors (i. e. invalid byte data). */ MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR = -1, /** * You tried to decode something, but the stream has already * been marked invalid. * You must close the websocket now using #MHD_upgrade_action() * with #MHD_UPGRADE_ACTION_CLOSE. * You may send a close frame before closing. * This is only used by #MHD_websocket_decode() and happens * if you call #MDM_websocket_decode() again after * has been invalidated. * You can call #MHD_websocket_stream_is_valid() at any time * to check whether a stream is invalid or not. */ MHD_WEBSOCKET_STATUS_STREAM_BROKEN = -2, /** * A memory allocation failed. The stream remains valid. * If this occurred while decoding, the decoding could be * possible later if enough memory is available. * This could happen while decoding if you received a too big data frame. * You could try to specify max_payload_size during the call of * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2() to * avoid this and close the websocket instead. */ MHD_WEBSOCKET_STATUS_MEMORY_ERROR = -3, /** * You passed invalid parameters during the function call * (i. e. a NULL pointer for a required parameter). * The stream remains valid. */ MHD_WEBSOCKET_STATUS_PARAMETER_ERROR = -4, /** * The maximum payload size has been exceeded. * If you got this return code from #MHD_websocket_decode() then * the stream becomes invalid and the websocket must be closed * using #MHD_upgrade_action() with #MHD_UPGRADE_ACTION_CLOSE. * You may send a close frame before closing. * The maximum payload size is specified during the call of * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2(). * This can also appear if you specified 0 as maximum payload size * when the message is greater than the maximum allocatable memory size * (i. e. more than 4 GiB on 32 bit systems). * If you got this return code from #MHD_websocket_encode_close(), * #MHD_websocket_encode_ping() or #MHD_websocket_encode_pong() then * you passed to much payload data. The stream remains valid then. */ MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED = -5, /** * An UTF-8 sequence is invalid. * If you got this return code from #MHD_websocket_decode() then * the stream becomes invalid and you must close the websocket * using #MHD_upgrade_action() with #MHD_UPGRADE_ACTION_CLOSE. * You may send a close frame before closing. * If you got this from #MHD_websocket_encode_text() or * #MHD_websocket_encode_close() then you passed invalid UTF-8 text. * The stream remains valid then. */ MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR = -6, /** * A check routine for the HTTP headers came to the conclusion that * the header value isn't valid for a websocket handshake request. * This value can only be returned from the following functions: * * #MHD_websocket_check_http_version() * * #MHD_websocket_check_connection_header() * * #MHD_websocket_check_upgrade_header() * * #MHD_websocket_check_version_header() * * #MHD_websocket_create_accept_header() */ MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER = -7 }; /** * @brief Enumeration of possible close reasons for close frames. * * The possible values are specified in RFC 6455 7.4.1 * These close reasons here are the default set specified by RFC 6455, * but also other close reasons could be used. * * The definition is for short: * 0-999 are never used (if you pass 0 in * #MHD_websocket_encode_close() then no close reason is used). * 1000-2999 are specified by RFC 6455. * 3000-3999 are specified by libraries, etc. but must be registered by IANA. * 4000-4999 are reserved for private use. * * @ingroup websocket */ enum MHD_WEBSOCKET_CLOSEREASON { /** * This value is used as placeholder for #MHD_websocket_encode_close() * to tell that you don't want to specify any reason. * If you use this value then no reason text may be used. * This value cannot be a result of decoding, because this value * is not a valid close reason for the websocket protocol. */ MHD_WEBSOCKET_CLOSEREASON_NO_REASON = 0, /** * You close the websocket because it fulfilled its purpose and shall * now be closed in a normal, planned way. */ MHD_WEBSOCKET_CLOSEREASON_REGULAR = 1000, /** * You close the websocket because you are shutting down the server or * something similar. */ MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY = 1001, /** * You close the websocket because a protocol error occurred * during decoding (i. e. invalid byte data). */ MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR = 1002, /** * You close the websocket because you received data which you don't accept. * For example if you received a binary frame, * but your application only expects text frames. */ MHD_WEBSOCKET_CLOSEREASON_UNSUPPORTED_DATATYPE = 1003, /** * You close the websocket because it contains malformed UTF-8. * The UTF-8 validity is automatically checked by #MHD_websocket_decode(), * so you don't need to check it on your own. * UTF-8 is specified in RFC 3629. */ MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8 = 1007, /** * You close the websocket because of any reason. * Usually this close reason is used if no other close reason * is more specific or if you don't want to use any other close reason. */ MHD_WEBSOCKET_CLOSEREASON_POLICY_VIOLATED = 1008, /** * You close the websocket because you received a frame which is too big * to process. * You can specify the maximum allowed payload size during the call of * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2(). */ MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED = 1009, /** * This status code can be sent by the client if it * expected a specific extension, but this extension hasn't been negotiated. */ MHD_WEBSOCKET_CLOSEREASON_MISSING_EXTENSION = 1010, /** * The server closes the websocket because it encountered * an unexpected condition that prevented it from fulfilling the request. */ MHD_WEBSOCKET_CLOSEREASON_UNEXPECTED_CONDITION = 1011 }; /** * @brief Enumeration of possible UTF-8 check steps * * These values are used during the encoding of fragmented text frames * or for error analysis while encoding text frames. * Its values specify the next step of the UTF-8 check. * UTF-8 sequences consist of one to four bytes. * This enumeration just says how long the current UTF-8 sequence is * and what is the next expected byte. * * @ingroup websocket */ enum MHD_WEBSOCKET_UTF8STEP { /** * There is no open UTF-8 sequence. * The next byte must be 0x00-0x7F or 0xC2-0xF4. */ MHD_WEBSOCKET_UTF8STEP_NORMAL = 0, /** * The second byte of a two byte UTF-8 sequence. * The first byte was 0xC2-0xDF. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 = 1, /** * The second byte of a three byte UTF-8 sequence. * The first byte was 0xE0. * The next byte must be 0xA0-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2 = 2, /** * The second byte of a three byte UTF-8 sequence. * The first byte was 0xED. * The next byte must by 0x80-0x9F. */ MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2 = 3, /** * The second byte of a three byte UTF-8 sequence. * The first byte was 0xE1-0xEC or 0xEE-0xEF. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2 = 4, /** * The third byte of a three byte UTF-8 sequence. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2 = 5, /** * The second byte of a four byte UTF-8 sequence. * The first byte was 0xF0. * The next byte must be 0x90-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3 = 6, /** * The second byte of a four byte UTF-8 sequence. * The first byte was 0xF4. * The next byte must be 0x80-0x8F. */ MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3 = 7, /** * The second byte of a four byte UTF-8 sequence. * The first byte was 0xF1-0xF3. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3 = 8, /** * The third byte of a four byte UTF-8 sequence. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3 = 9, /** * The fourth byte of a four byte UTF-8 sequence. * The next byte must be 0x80-0xBF. */ MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3 = 10 }; /** * @brief Enumeration of validity values * * These values are used for #MHD_websocket_stream_is_valid() * and specify the validity status. * * @ingroup websocket */ enum MHD_WEBSOCKET_VALIDITY { /** * The stream is invalid. * It cannot be used for decoding anymore. */ MHD_WEBSOCKET_VALIDITY_INVALID = 0, /** * The stream is valid. * Decoding works as expected. */ MHD_WEBSOCKET_VALIDITY_VALID = 1, /** * The stream has received a close frame and * is partly invalid. * You can still use the stream for decoding, * but if a data frame is received an error will be reported. * After a close frame has been sent, no data frames * may follow from the sender of the close frame. */ MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES = 2 }; /** * This callback function is used internally by many websocket functions * for allocating data. * By default `malloc()` is used. * You can use your own allocation function with * #MHD_websocket_stream_init2() if you wish to. * This can be useful for operating systems like Windows * where `malloc()`, `realloc()` and `free()` are compiler-dependent. * You can call the associated `malloc()` callback of * a websocket stream with #MHD_websocket_malloc(). * * @param buf_len buffer size in bytes * @return allocated memory * @ingroup websocket */ typedef void * (*MHD_WebSocketMallocCallback) (size_t buf_len); /** * This callback function is used internally by many websocket * functions for reallocating data. * By default `realloc()` is used. * You can use your own reallocation function with * #MHD_websocket_stream_init2() if you wish to. * This can be useful for operating systems like Windows * where `malloc()`, `realloc()` and `free()` are compiler-dependent. * You can call the associated `realloc()` callback of * a websocket stream with #MHD_websocket_realloc(). * * @param buf buffer * @param new_buf_len new buffer size in bytes * @return reallocated memory * @ingroup websocket */ typedef void * (*MHD_WebSocketReallocCallback) (void *buf, size_t new_buf_len); /** * This callback function is used internally by many websocket * functions for freeing data. * By default `free()` is used. * You can use your own free function with * #MHD_websocket_stream_init2() if you wish to. * This can be useful for operating systems like Windows * where `malloc()`, `realloc()` and `free()` are compiler-dependent. * You can call the associated `free()` callback of * a websocket stream with #MHD_websocket_free(). * * @param buf buffer * @ingroup websocket */ typedef void (*MHD_WebSocketFreeCallback) (void *buf); /** * This callback function is used for generating random numbers * for masking payload data in client mode. * If you use websockets in server mode with libmicrohttpd then * you don't need a random number generator, because * the server doesn't mask its outgoing messageses. * However if you wish to use a websocket stream in client mode, * you must pass this callback function to #MHD_websocket_stream_init2(). * * @param cls closure specified in #MHD_websocket_stream_init2() * @param buf buffer to fill with random values * @param buf_len size of buffer in bytes * @return The number of generated random bytes. * Should usually equal to buf_len. * @ingroup websocket */ typedef size_t (*MHD_WebSocketRandomNumberGenerator) (void *cls, void *buf, size_t buf_len); /** * Checks the HTTP version of the incoming request. * Websocket requests are only allowed for HTTP/1.1 or above. * * @param http_version The value of the 'version' parameter of your * access_handler callback * @return A value of `enum MHD_WEBSOCKET_STATUS`. * 0 means the HTTP version is correct for a websocket request, * a value less than zero means that the HTTP version isn't * valid for a websocket request. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_http_version (const char *http_version); /** * Checks the value of the 'Connection' HTTP request header. * Websocket requests require the token 'Upgrade' in * the 'Connection' HTTP request header. * * @param connection_header The value of the 'Connection' request header. * You can get this request header value by passing * #MHD_HTTP_HEADER_CONNECTION to * #MHD_lookup_connection_value(). * @return A value of `enum MHD_WEBSOCKET_STATUS`. * 0 means the 'Connection' request header is correct * for a websocket request, * a value less than zero means that the 'Connection' header isn't * valid for a websocket request. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_connection_header (const char *connection_header); /** * Checks the value of the 'Upgrade' HTTP request header. * Websocket requests require the value 'websocket' in * the 'Upgrade' HTTP request header. * * @param upgrade_header The value of the 'Upgrade' request header. * You can get this request header value by passing * #MHD_HTTP_HEADER_UPGRADE to * #MHD_lookup_connection_value(). * @return A value of `enum MHD_WEBSOCKET_STATUS`. * 0 means the 'Upgrade' request header is correct * for a websocket request, * a value less than zero means that the 'Upgrade' header isn't * valid for a websocket request. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_upgrade_header (const char *upgrade_header); /** * Checks the value of the 'Sec-WebSocket-Version' HTTP request header. * Websocket requests require the value '13' * in the 'Sec-WebSocket-Version' HTTP request header. * * @param version_header The value of the 'Sec-WebSocket-Version' * request header. * You can get this request header value by passing * #MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION to * #MHD_lookup_connection_value(). * @return A value of `enum MHD_WEBSOCKET_STATUS`. * 0 means the 'Sec-WebSocket-Version' request header is correct * for a websocket request, * a value less than zero means that the 'Sec-WebSocket-Version' * header isn't valid for a websocket request. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_version_header (const char *version_header); /** * Creates the response value for the 'Sec-WebSocket-Key' HTTP request header. * The generated value must be sent to the client * as 'Sec-WebSocket-Accept' HTTP response header. * * @param sec_websocket_key The value of the 'Sec-WebSocket-Key' * request header. * You can get this request header value by passing * #MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY to * #MHD_lookup_connection_value(). * @param[out] sec_websocket_accept The response buffer, which will receive * the generated 'Sec-WebSocket-Accept' header. * This buffer must be at least 29 bytes long and * will contain the response value plus * a terminating NUL on success. * @return A value of `enum MHD_WEBSOCKET_STATUS`. * Typically 0 on success or less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_create_accept_header (const char *sec_websocket_key, char *sec_websocket_accept); /** * Creates a new websocket stream, used for decoding/encoding. * * @param[out] ws The websocket stream * @param flags Combination of `enum MHD_WEBSOCKET_FLAG` values * to modify the behavior of the websocket stream. * @param max_payload_size The maximum size for incoming payload * data in bytes. Use 0 to allow each size. * @return A value of `enum MHD_WEBSOCKET_STATUS`. * Typically 0 on success or less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size); /** * Creates a new websocket stream, used for decoding/encoding, * but with custom memory functions for malloc, realloc and free. * Also a random number generator can be specified for client mode. * * @param[out] ws The websocket stream * @param flags Combination of `enum MHD_WEBSOCKET_FLAG` values * to modify the behavior of the websocket stream. * @param max_payload_size The maximum size for incoming payload * data in bytes. Use 0 to allow each size. * @param callback_malloc The callback function for `malloc()`. * @param callback_realloc The callback function for `realloc()`. * @param callback_free The callback function for `free()`. * @param cls_rng A closure for the random number generator callback. * This is only required when * MHD_WEBSOCKET_FLAG_CLIENT is passed in `flags`. * The given value is passed to * the random number generator. * May be NULL if not needed. * Should be NULL when you are * not using MHD_WEBSOCKET_FLAG_CLIENT. * @param callback_rng A callback function for a * secure random number generator. * This is only required when * MHD_WEBSOCKET_FLAG_CLIENT is passed in `flags`. * Should be NULL otherwise. * @return A value of `enum MHD_WEBSOCKET_STATUS`. * Typically 0 on success or less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size, MHD_WebSocketMallocCallback callback_malloc, MHD_WebSocketReallocCallback callback_realloc, MHD_WebSocketFreeCallback callback_free, void *cls_rng, MHD_WebSocketRandomNumberGenerator callback_rng); /** * Frees a websocket stream * * @param ws The websocket stream. This value may be NULL. * @return A value of `enum MHD_WEBSOCKET_STATUS`. * Typically 0 on success or less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_free (struct MHD_WebSocketStream *ws); /** * Invalidates a websocket stream. * After invalidation a websocket stream cannot be used for decoding anymore. * Encoding is still possible. * * @param ws The websocket stream. * @return A value of `enum MHD_WEBSOCKET_STATUS`. * Typically 0 on success or less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws); /** * Queries whether a websocket stream is valid. * Invalidated websocket streams cannot be used for decoding anymore. * Encoding is still possible. * * @param ws The websocket stream. * @return A value of `enum MHD_WEBSOCKET_VALIDITY`. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_VALIDITY MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws); /** * Decodes a byte sequence for a websocket stream. * Decoding is done until either a frame is complete or * the end of the byte sequence is reached. * * @param ws The websocket stream. * @param streambuf The byte sequence for decoding. * Typically that what you received via `recv()`. * @param streambuf_len The length of the byte sequence @a streambuf * @param[out] streambuf_read_len The number of bytes which has been processed * by this call. This value may be less * than @a streambuf_len when a frame is decoded * before the end of the buffer is reached. * The remaining bytes of @a buf must be passed * to the next call of this function. * @param[out] payload Pointer to a variable, which receives a buffer * with the decoded payload data. * If no decoded data is available this is NULL. * When the returned value is not NULL then * the buffer contains always @a payload_len bytes plus * one terminating NUL character. * The caller must free this buffer * using #MHD_websocket_free(). * If you passed the flag * #MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR * upon creation of this websocket stream and * a decoding error occurred * (function return value less than 0), then this * buffer contains a generated close frame * which must be sent via the socket to the recipient. * If you passed the flag #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS * upon creation of the websocket stream then * this payload may only be a part of the complete message. * Only complete UTF-8 sequences are returned * for fragmented text frames. * If necessary the UTF-8 sequence will be completed * with the next text fragment. * @param[out] payload_len The length of the result payload buffer in bytes. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is greater than 0 if a frame has is complete, * equal to 0 if more data is needed an less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_decode (struct MHD_WebSocketStream *ws, const char *streambuf, size_t streambuf_len, size_t *streambuf_read_len, char **payload, size_t *payload_len); /** * Splits the payload of a decoded close frame. * * @param payload The payload of the close frame. * This parameter may only be NULL if @a payload_len is 0. * @param payload_len The length of @a payload. * @param[out] reason_code The numeric close reason. * If there was no close reason, this is * #MHD_WEBSOCKET_CLOSEREASON_NO_REASON. * Compare with `enum MHD_WEBSOCKET_CLOSEREASON`. * This parameter is optional and may be NULL. * @param[out] reason_utf8 The literal close reason. * If there was no literal close reason, this is NULL. * This parameter is optional and may be NULL. * Please note that no memory is allocated * in this function. * If not NULL the returned value of this parameter * points to a position in the specified @a payload. * @param[out] reason_utf8_len The length of the literal close reason. * If there was no literal close reason, this is 0. * This parameter is optional and may be NULL. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_split_close_reason (const char *payload, size_t payload_len, unsigned short *reason_code, const char **reason_utf8, size_t *reason_utf8_len); /** * Encodes an UTF-8 encoded text into websocket text frame. * * @param ws The websocket stream. * @param payload_utf8 The UTF-8 encoded text to send. * This may be NULL if payload_utf8_len is 0. * @param payload_utf8_len The length of the UTF-8 encoded text in bytes. * @param fragmentation A value of `enum MHD_WEBSOCKET_FRAGMENTATION` * to specify the fragmentation behavior. * Specify MHD_WEBSOCKET_FRAGMENTATION_NONE * if you don't want to use fragmentation. * @param[out] frame This variable receives a buffer with the encoded frame. * This is what you typically send via `send()` to the recipient. * If no encoded data is available this is NULL. * When this variable is not NULL then the buffer contains always * @a frame_len bytes plus one terminating NUL character. * The caller must free this buffer using #MHD_websocket_free(). * @param[out] frame_len The length of the encoded frame in bytes. * @param[out] utf8_step This parameter is required for fragmentation and * should be NULL if no fragmentation is used. * It contains information about the last encoded * UTF-8 sequence and is required to continue a previous * UTF-8 sequence when fragmentation is used. * `enum MHD_WEBSOCKET_UTF8STEP` is for this value. * If you start a new fragment using * MHD_WEBSOCKET_FRAGMENTATION_NONE or * MHD_WEBSOCKET_FRAGMENTATION_FIRST the value * of this variable will be initialized * to MHD_WEBSOCKET_UTF8STEP_NORMAL. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_text (struct MHD_WebSocketStream *ws, const char *payload_utf8, size_t payload_utf8_len, int fragmentation, char **frame, size_t *frame_len, int *utf8_step); /** * Encodes binary data into websocket binary frame. * * @param ws The websocket stream. * @param payload The binary data to send. * @param payload_len The length of the binary data in bytes. * @param fragmentation A value of `enum MHD_WEBSOCKET_FRAGMENTATION` * to specify the fragmentation behavior. * Specify MHD_WEBSOCKET_FRAGMENTATION_NONE * if you don't want to use fragmentation. * @param[out] frame This variable receives a buffer with * the encoded binary frame. * This is what you typically send via `send()` * to the recipient. * If no encoded frame is available this is NULL. * When this variable is not NULL then the allocated buffer * contains always @a frame_len bytes plus one terminating * NUL character. * The caller must free this buffer using #MHD_websocket_free(). * @param[out] frame_len The length of the result frame buffer in bytes. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_binary (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, int fragmentation, char **frame, size_t *frame_len); /** * Encodes a websocket ping frame * * @param ws The websocket stream. * @param payload The binary ping payload data to send. * This may be NULL if @a payload_len is 0. * @param payload_len The length of the payload data in bytes. * This may not exceed 125 bytes. * @param[out] frame This variable receives a buffer with the encoded ping frame data. * This is what you typically send via `send()` to the recipient. * If no encoded frame is available this is NULL. * When this variable is not NULL then the buffer contains always * @a frame_len bytes plus one terminating NUL character. * The caller must free this buffer using #MHD_websocket_free(). * @param[out] frame_len The length of the result frame buffer in bytes. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_ping (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len); /** * Encodes a websocket pong frame * * @param ws The websocket stream. * @param payload The binary pong payload data, which should be * the decoded payload from the received ping frame. * This may be NULL if @a payload_len is 0. * @param payload_len The length of the payload data in bytes. * This may not exceed 125 bytes. * @param[out] frame This variable receives a buffer with * the encoded pong frame data. * This is what you typically send via `send()` * to the recipient. * If no encoded frame is available this is NULL. * When this variable is not NULL then the buffer * contains always @a frame_len bytes plus one * terminating NUL character. * The caller must free this buffer * using #MHD_websocket_free(). * @param[out] frame_len The length of the result frame buffer in bytes. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_pong (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len); /** * Encodes a websocket close frame * * @param ws The websocket stream. * @param reason_code The reason for close. * You can use `enum MHD_WEBSOCKET_CLOSEREASON` * for typical reasons, * but you are not limited to these values. * The allowed values are specified in RFC 6455 7.4. * If you don't want to enter a reason, you can specify * #MHD_WEBSOCKET_CLOSEREASON_NO_REASON then * no reason is encoded. * @param reason_utf8 An UTF-8 encoded text reason why the connection is closed. * This may be NULL if @a reason_utf8_len is 0. * This must be NULL if @a reason_code is * #MHD_WEBSOCKET_CLOSEREASON_NO_REASON (= 0). * @param reason_utf8_len The length of the UTF-8 encoded text reason in bytes. * This may not exceed 123 bytes. * @param[out] frame This variable receives a buffer with * the encoded close frame. * This is what you typically send via `send()` * to the recipient. * If no encoded frame is available this is NULL. * When this variable is not NULL then the buffer * contains always @a frame_len bytes plus * one terminating NUL character. * The caller must free this buffer * using #MHD_websocket_free(). * @param[out] frame_len The length of the result frame buffer in bytes. * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_close (struct MHD_WebSocketStream *ws, unsigned short reason_code, const char *reason_utf8, size_t reason_utf8_len, char **frame, size_t *frame_len); /** * Allocates memory with the associated 'malloc' function * of the websocket stream * * @param ws The websocket stream. * @param buf_len The length of the memory to allocate in bytes * * @return The allocated memory on success or NULL on failure. * @ingroup websocket */ _MHD_EXTERN void * MHD_websocket_malloc (struct MHD_WebSocketStream *ws, size_t buf_len); /** * Reallocates memory with the associated 'realloc' function * of the websocket stream * * @param ws The websocket stream. * @param buf The previously allocated memory or NULL * @param new_buf_len The new length of the memory in bytes * * @return The allocated memory on success or NULL on failure. * If NULL is returned the previously allocated buffer * remains valid. * @ingroup websocket */ _MHD_EXTERN void * MHD_websocket_realloc (struct MHD_WebSocketStream *ws, void *buf, size_t new_buf_len); /** * Frees memory with the associated 'free' function * of the websocket stream * * @param ws The websocket stream. * @param buf The previously allocated memory or NULL * * @return A value of `enum MHD_WEBSOCKET_STATUS`. * This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success * or a value less than 0 on errors. * @ingroup websocket */ _MHD_EXTERN int MHD_websocket_free (struct MHD_WebSocketStream *ws, void *buf); #if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus } #endif #endif libmicrohttpd-1.0.2/src/include/Makefile.in0000644000175000017500000005737115035216310015567 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @HAVE_EXPERIMENTAL_TRUE@am__append_1 = microhttpd_ws.h subdir = src/include ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__include_HEADERS_DIST) \ $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__include_HEADERS_DIST = microhttpd.h microhttpd_ws.h am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(includedir)" HEADERS = $(include_HEADERS) $(noinst_HEADERS) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . include_HEADERS = microhttpd.h $(am__append_1) noinst_HEADERS = microhttpd2.h microhttpd_tls.h EXTRA_DIST = platform.h autoinit_funcs.h mhd_options.h all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/include/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/include/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(HEADERS) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-includeHEADERS install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-includeHEADERS .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-includeHEADERS install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am uninstall-includeHEADERS .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/include/platform.h0000644000175000017500000000726014760713577015534 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file platform.h * @brief platform-specific includes for libmicrohttpd * @author Christian Grothoff * * This file is included by the libmicrohttpd code * before "microhttpd.h"; it provides the required * standard headers (which are platform-specific).

* * Note that this file depends on our configure.ac * build process and the generated config.h file. * Hence you cannot include it directly in applications * that use libmicrohttpd. */ #ifndef MHD_PLATFORM_H #define MHD_PLATFORM_H #include "mhd_options.h" #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include #include #ifdef HAVE_UNISTD_H #include #endif #include #include #include #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ /* different OSes have fd_set in a broad range of header files; we just include most of them (if they are available) */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #include #include #ifdef HAVE_SOCKLIB_H #include #endif /* HAVE_SOCKLIB_H */ #ifdef HAVE_INETLIB_H #include #endif /* HAVE_INETLIB_H */ #endif /* __VXWORKS__ */ #ifdef HAVE_MEMORY_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_SYS_MSG_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #ifdef HAVE_TIME_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #include #endif /* _WIN32 && !__CYGWIN__ */ #if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET) /* Do not define __USE_W32_SOCKETS under Cygwin! */ #error Cygwin with winsock fd_set is not supported #endif #if defined(_WIN32) && ! defined(__CYGWIN__) #define sleep(seconds) ((SleepEx ((seconds) * 1000, 1)==0) ? 0 : (seconds)) #define usleep(useconds) ((SleepEx ((useconds) / 1000, 1)==0) ? 0 : -1) #endif #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #if ! defined(_WIN32) || defined(__CYGWIN__) typedef time_t _MHD_TIMEVAL_TV_SEC_TYPE; #else /* _WIN32 && ! __CYGWIN__ */ typedef long _MHD_TIMEVAL_TV_SEC_TYPE; #endif /* _WIN32 && ! __CYGWIN__ */ #if ! defined(IPPROTO_IPV6) && defined(_MSC_FULL_VER) && _WIN32_WINNT >= 0x0501 /* VC use IPPROTO_IPV6 as part of enum */ #define IPPROTO_IPV6 IPPROTO_IPV6 #endif #endif libmicrohttpd-1.0.2/src/include/microhttpd_tls.h0000644000175000017500000001152414760713577016745 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2018 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd_tls.h * @brief interface for TLS plugins of libmicrohttpd * @author Christian Grothoff */ #ifndef MICROHTTPD_TLS_H #define MICROHTTPD_TLS_H #include /** * Version of the TLS ABI. */ #define MHD_TLS_ABI_VERSION 0 /** * Version of the TLS ABI as a string. * Must match #MHD_TLS_ABI_VERSION! */ #define MHD_TLS_ABI_VERSION_STR "0" /** * Data structure kept per TLS client by the plugin. */ struct MHD_TLS_ConnectionState; /** * Callback functions to use for TLS operations. */ struct MHD_TLS_Plugin { /** * Closure with plugin's internal state, opaque to MHD. */ void *cls; /** * Destroy the plugin, we are done with it. */ void (*done)(struct MHD_TLS_Plugin *plugin); /** * Initialize key and certificate data from memory. * * @param cls the @e cls of this struct * @param mem_key private key (key.pem) to be used by the * HTTPS daemon. Must be the actual data in-memory, not a filename. * @param mem_cert certificate (cert.pem) to be used by the * HTTPS daemon. Must be the actual data in-memory, not a filename. * @param pass passphrase phrase to decrypt 'key.pem', NULL * if @param mem_key is in cleartext already * @return #MHD_SC_OK upon success; TODO: define failure modes */ enum MHD_StatusCode (*init_kcp)(void *cls, const char *mem_key, const char *mem_cert, const char *pass); /** * Initialize DH parameters. * * @param cls the @e cls of this struct * @param dh parameters to use * @return #MHD_SC_OK upon success; TODO: define failure modes */ enum MHD_StatusCode (*init_dhparams)(void *cls, const char *dh); /** * Initialize certificate to use for client authentication. * * @param cls the @e cls of this struct * @param mem_trust client certificate * @return #MHD_SC_OK upon success; TODO: define failure modes */ enum MHD_StatusCode (*init_mem_trust)(void *cls, const char *mem_trust); /** * Function called when we receive a connection and need * to initialize our TLS state for it. * * @param cls the @e cls of this struct * @param ... TBD * @return NULL on error */ struct MHD_TLS_ConnectionState * (*setup_connection)(void *cls, ...); enum MHD_Bool (*handshake)(void *cls, struct MHD_TLS_ConnectionState *cs); enum MHD_Bool (*idle_ready)(void *cls, struct MHD_TLS_ConnectionState *cs); enum MHD_Bool (*update_event_loop_info)(void *cls, struct MHD_TLS_ConnectionState *cs, enum MHD_RequestEventLoopInfo *eli); ssize_t (*send)(void *cls, struct MHD_TLS_ConnectionState *cs, const void *buf, size_t buf_size); ssize_t (*recv)(void *cls, struct MHD_TLS_ConnectionState *cs, void *buf, size_t buf_size); const char * (*strerror)(void *cls, int ec); enum MHD_Bool (*check_record_pending)(void *cls, struct MHD_TLS_ConnectionState *cs); enum MHD_Bool (*shutdown_connection)(void *cls, struct MHD_TLS_ConnectionState *cs); void (*teardown_connection)(void *cls, struct MHD_TLS_ConnectionState *cs); /** * TODO: More functions here.... */ }; /** * Signature of the initialization function each TLS plugin must * export. * * @param ciphers desired cipher suite * @return NULL on errors (in particular, invalid cipher suite) */ typedef struct MHD_TLS_Plugin * (*MHD_TLS_PluginInit) (const char *ciphers); /** * Define function to be exported from the TLS plugin. * * @a body function body that receives `ciphers` argument * and must return the plugin API, or NULL on error. */ #define MHD_TLS_INIT(body) \ struct MHD_TLS_Plugin * \ MHD_TLS_init_ ## MHD_TLS_ABI_VERSION (const char *ciphers) \ \ { body } #endif libmicrohttpd-1.0.2/src/include/mhd_options.h0000644000175000017500000002424715035214301016210 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file include/mhd_options.h * @brief additional automatic macros for MHD_config.h * @author Karlson2k (Evgeny Grin) * * This file includes MHD_config.h and adds automatic macros based on values * in MHD_config.h, compiler built-in macros and commandline-defined macros * (but not based on values defined in other headers). Works also as a guard * to prevent double inclusion of MHD_config.h */ #ifndef MHD_OPTIONS_H #define MHD_OPTIONS_H 1 #include "MHD_config.h" /** * Macro to make it easy to mark text for translation. Note that * we do not actually call gettext() in MHD, but we do make it * easy to create a ".po" file so that applications that do want * to translate error messages can do so. */ #define _(String) (String) #if defined(_MHD_EXTERN) && ! defined(BUILDING_MHD_LIB) #undef _MHD_EXTERN #endif /* _MHD_EXTERN && ! BUILDING_MHD_LIB */ #ifndef _MHD_EXTERN #if defined(BUILDING_MHD_LIB) && defined(_WIN32) && \ (defined(DLL_EXPORT) || defined(MHD_W32DLL)) #define _MHD_EXTERN __declspec(dllexport) extern #else /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */ #define _MHD_EXTERN extern #endif /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */ #endif /* ! _MHD_EXTERN */ /* Some platforms (FreeBSD, Solaris, W32) allow to override default FD_SETSIZE by defining it before including headers. */ #ifdef FD_SETSIZE /* FD_SETSIZE defined in command line or in MHD_config.h */ #elif defined(_WIN32) || defined(__CYGWIN__) /* Platform with WinSock and without overridden FD_SETSIZE */ #define FD_SETSIZE 2048 /* Override default small value (64) */ #else /* !FD_SETSIZE && !W32 */ /* System default value of FD_SETSIZE is used */ #define _MHD_FD_SETSIZE_IS_DEFAULT 1 #endif /* !FD_SETSIZE && !W32 */ #if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_FREEBSD_SENDFILE) || \ defined(HAVE_DARWIN_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE) /* Have any supported sendfile() function. */ #define _MHD_HAVE_SENDFILE #endif /* HAVE_LINUX_SENDFILE || HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE || HAVE_SOLARIS_SENDFILE */ #if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE) #define MHD_LINUX_SOLARIS_SENDFILE 1 #endif /* HAVE_LINUX_SENDFILE || HAVE_SOLARIS_SENDFILE */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */ #if defined(OS390) #define _OPEN_THREADS #define _OPEN_SYS_SOCK_IPV6 #define _OPEN_MSGQ_EXT #define _LP64 #endif #if defined(_WIN32) && ! defined(__CYGWIN__) /* Declare POSIX-compatible names */ #define _CRT_DECLARE_NONSTDC_NAMES 1 /* Do not warn about POSIX name usage */ #define _CRT_NONSTDC_NO_WARNINGS 1 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #else /* _WIN32_WINNT */ #if _WIN32_WINNT < 0x0501 #error "Headers for Windows XP or later are required" #endif /* _WIN32_WINNT < 0x0501 */ #endif /* _WIN32_WINNT */ #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #endif /* _WIN32 && ! __CYGWIN__ */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #define RESTRICT __restrict__ #endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */ #if defined(LINUX) && (defined(HAVE_SENDFILE64) || defined(HAVE_LSEEK64)) && \ ! defined(_LARGEFILE64_SOURCE) /* On Linux, special macro is required to enable definitions of some xxx64 functions */ #define _LARGEFILE64_SOURCE 1 #endif #ifdef HAVE_C11_GMTIME_S /* Special macro is required to enable C11 definition of gmtime_s() function */ #define __STDC_WANT_LIB_EXT1__ 1 #endif /* HAVE_C11_GMTIME_S */ #if defined(MHD_FAVOR_FAST_CODE) && defined(MHD_FAVOR_SMALL_CODE) #error \ MHD_FAVOR_FAST_CODE and MHD_FAVOR_SMALL_CODE are both defined. Cannot favor speed and size at the same time. #endif /* MHD_FAVOR_FAST_CODE && MHD_FAVOR_SMALL_CODE */ /* Define MHD_FAVOR_FAST_CODE to force fast code path or define MHD_FAVOR_SMALL_CODE to choose compact code path */ #if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE) /* Try to detect user preferences */ /* Defined by GCC and many compatible compilers */ #if defined(__OPTIMIZE_SIZE__) #define MHD_FAVOR_SMALL_CODE 1 #elif defined(__OPTIMIZE__) #define MHD_FAVOR_FAST_CODE 1 #endif /* __OPTIMIZE__ */ #endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */ #if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE) /* Use faster code by default */ #define MHD_FAVOR_FAST_CODE 1 #endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */ #ifndef MHD_ASAN_ACTIVE #if (defined(__GNUC__) || defined(_MSC_VER)) && defined(__SANITIZE_ADDRESS__) #define MHD_ASAN_ACTIVE 1 #elif defined(__has_feature) #if __has_feature (address_sanitizer) #define MHD_ASAN_ACTIVE 1 #endif /* __has_feature(address_sanitizer) */ #endif /* __has_feature */ #endif /* MHD_ASAN_ACTIVE */ #if defined(MHD_ASAN_ACTIVE) && defined(HAVE_SANITIZER_ASAN_INTERFACE_H) && \ (defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS) || \ (defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \ defined(FUNC_ATTR_PTRSUBTRACT_WORKS)) || \ defined(FUNC_ATTR_NOSANITIZE_WORKS)) #ifndef MHD_ASAN_POISON_ACTIVE /* User ASAN poisoning could be used */ #warning User memory poisoning is not active #endif /* ! MHD_ASAN_POISON_ACTIVE */ #else /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H && (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS)) */ #ifdef MHD_ASAN_POISON_ACTIVE #error User memory poisoning is active, but conditions are not suitable #endif /* MHD_ASAN_POISON_ACTIVE */ #endif /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H && (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS)) */ #ifndef _MSC_FULL_VER # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /* empty */ # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /* empty */ #else /* _MSC_FULL_VER */ # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ \ __pragma(runtime_checks("c", off)) # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ \ __pragma(runtime_checks("c", restore)) #endif /* _MSC_FULL_VER */ /** * Automatic string with the name of the current function */ #if defined(HAVE___FUNC__) #define MHD_FUNC_ __func__ #define MHD_HAVE_MHD_FUNC_ 1 #elif defined(HAVE___FUNCTION__) #define MHD_FUNC_ __FUNCTION__ #define MHD_HAVE_MHD_FUNC_ 1 #elif defined(HAVE___PRETTY_FUNCTION__) #define MHD_FUNC_ __PRETTY_FUNCTION__ #define MHD_HAVE_MHD_FUNC_ 1 #else #define MHD_FUNC_ "**name unavailable**" #ifdef MHD_HAVE_MHD_FUNC_ #undef MHD_HAVE_MHD_FUNC_ #endif /* MHD_HAVE_MHD_FUNC_ */ #endif /* Un-define some HAVE_DECL_* macro if they equal zero. This should allow safely use #ifdef in the code. Define HAS_DECL_* macros only if matching HAVE_DECL_* macro has non-zero value. Unlike HAVE_DECL_*, macros HAS_DECL_* cannot have zero value. */ #ifdef HAVE_DECL__SC_NPROCESSORS_ONLN # if 0 == HAVE_DECL__SC_NPROCESSORS_ONLN # undef HAVE_DECL__SC_NPROCESSORS_ONLN # else /* 0 != HAVE_DECL__SC_NPROCESSORS_ONLN */ # define HAS_DECL__SC_NPROCESSORS_ONLN 1 # endif /* 0 != HAVE_DECL__SC_NPROCESSORS_ONLN */ #endif /* HAVE_DECL__SC_NPROCESSORS_ONLN */ #ifdef HAVE_DECL__SC_NPROCESSORS_CONF # if 0 == HAVE_DECL__SC_NPROCESSORS_CONF # undef HAVE_DECL__SC_NPROCESSORS_CONF # else /* 0 != HAVE_DECL__SC_NPROCESSORS_CONF */ # define HAS_DECL__SC_NPROCESSORS_CONF 1 # endif /* 0 != HAVE_DECL__SC_NPROCESSORS_CONF */ #endif /* HAVE_DECL__SC_NPROCESSORS_CONF */ #ifdef HAVE_DECL__SC_NPROC_ONLN # if 0 == HAVE_DECL__SC_NPROC_ONLN # undef HAVE_DECL__SC_NPROC_ONLN # else /* 0 != HAVE_DECL__SC_NPROC_ONLN */ # define HAS_DECL__SC_NPROC_ONLN 1 # endif /* 0 != HAVE_DECL__SC_NPROC_ONLN */ #endif /* HAVE_DECL__SC_NPROC_ONLN */ #ifdef HAVE_DECL__SC_CRAY_NCPU # if 0 == HAVE_DECL__SC_CRAY_NCPU # undef HAVE_DECL__SC_CRAY_NCPU # else /* 0 != HAVE_DECL__SC_CRAY_NCPU */ # define HAS_DECL__SC_CRAY_NCPU 1 # endif /* 0 != HAVE_DECL__SC_CRAY_NCPU */ #endif /* HAVE_DECL__SC_CRAY_NCPU */ #ifdef HAVE_DECL_CTL_HW # if 0 == HAVE_DECL_CTL_HW # undef HAVE_DECL_CTL_HW # else /* 0 != HAVE_DECL_CTL_HW */ # define HAS_DECL_CTL_HW 1 # endif /* 0 != HAVE_DECL_CTL_HW */ #endif /* HAVE_DECL_CTL_HW */ #ifdef HAVE_DECL_HW_NCPUONLINE # if 0 == HAVE_DECL_HW_NCPUONLINE # undef HAVE_DECL_HW_NCPUONLINE # else /* 0 != HAVE_DECL_HW_NCPUONLINE */ # define HAS_DECL_HW_NCPUONLINE 1 # endif /* 0 != HAVE_DECL_HW_NCPUONLINE */ #endif /* HAVE_DECL_HW_NCPUONLINE */ #ifdef HAVE_DECL_HW_AVAILCPU # if 0 == HAVE_DECL_HW_AVAILCPU # undef HAVE_DECL_HW_AVAILCPU # else /* 0 != HAVE_DECL_HW_AVAILCPU */ # define HAS_DECL_HW_AVAILCPU 1 # endif /* 0 != HAVE_DECL_HW_AVAILCPU */ #endif /* HAVE_DECL_HW_AVAILCPU */ #ifdef HAVE_DECL_HW_NCPU # if 0 == HAVE_DECL_HW_NCPU # undef HAVE_DECL_HW_NCPU # else /* 0 != HAVE_DECL_HW_NCPU */ # define HAS_DECL_HW_NCPU 1 # endif /* 0 != HAVE_DECL_HW_NCPU */ #endif /* HAVE_DECL_HW_NCPU */ #ifdef HAVE_DECL_CPU_SETSIZE # if 0 == HAVE_DECL_CPU_SETSIZE # undef HAVE_DECL_CPU_SETSIZE # else /* 0 != HAVE_DECL_CPU_SETSIZE */ # define HAS_DECL_CPU_SETSIZE 1 # endif /* 0 != HAVE_DECL_CPU_SETSIZE */ #endif /* HAVE_DECL_CPU_SETSIZE */ #ifndef MHD_DAUTH_DEF_TIMEOUT_ # define MHD_DAUTH_DEF_TIMEOUT_ 90 #endif /* ! MHD_DAUTH_DEF_TIMEOUT_ */ #ifndef MHD_DAUTH_DEF_MAX_NC_ # define MHD_DAUTH_DEF_MAX_NC_ 1000 #endif /* ! MHD_DAUTH_DEF_MAX_NC_ */ #endif /* MHD_OPTIONS_H */ libmicrohttpd-1.0.2/src/include/Makefile.am0000644000175000017500000000037615035214301015545 00000000000000# This Makefile.am is in the public domain SUBDIRS = . include_HEADERS = microhttpd.h noinst_HEADERS = microhttpd2.h microhttpd_tls.h if HAVE_EXPERIMENTAL include_HEADERS += microhttpd_ws.h endif EXTRA_DIST = platform.h autoinit_funcs.h mhd_options.h libmicrohttpd-1.0.2/src/testcurl/0000755000175000017500000000000015035216652014020 500000000000000libmicrohttpd-1.0.2/src/testcurl/test_termination.c0000644000175000017500000001011614760713574017504 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_termination.c * @brief Testcase for libmicrohttpd tolerating client not closing immediately * @author hollosig * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #include #include #include #ifndef __MINGW32__ #include #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif static enum MHD_Result connection_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int i; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (*req_cls == NULL) { *req_cls = &i; return MHD_YES; } if (*upload_data_size != 0) { (*upload_data_size) = 0; return MHD_YES; } response = MHD_create_response_from_buffer_static (strlen ("Response"), "Response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static size_t write_data (void *ptr, size_t size, size_t nmemb, void *stream) { (void) ptr; (void) stream; /* Unused. Silent compiler warning. */ return size * nmemb; } int main (void) { struct MHD_Daemon *daemon; uint16_t port; char url[255]; CURL *curl; CURLcode success; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1490; daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, connection_handler, NULL, MHD_OPTION_END); if (daemon == NULL) { fprintf (stderr, "Daemon cannot be started!"); exit (1); } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (daemon); return 32; } port = dinfo->port; } curl = curl_easy_init (); /* curl_easy_setopt(curl, CURLOPT_POST, 1L); */ snprintf (url, sizeof (url), "http://127.0.0.1:%u", (unsigned int) port); curl_easy_setopt (curl, CURLOPT_URL, url); curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data); success = curl_easy_perform (curl); if (success != 0) { fprintf (stderr, "CURL Error"); exit (1); } /* CPU used to go crazy here */ (void) sleep (1); curl_easy_cleanup (curl); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.2/src/testcurl/test_put_header_fold.c0000644000175000017500000011476714760713574020320 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_put_header_fold.c * @brief Testcase for requests with header fold * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #endif #include "internal.h" #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* The next macros are borrowed from memorypool.c Keep them in sync! */ /** * Align to 2x word size (as GNU libc does). */ #define ALIGN_SIZE (2 * sizeof(void*)) /** * Round up 'n' to a multiple of ALIGN_SIZE. */ #define ROUND_TO_ALIGN(n) (((n) + (ALIGN_SIZE - 1)) \ / (ALIGN_SIZE) *(ALIGN_SIZE)) #ifndef MHD_ASAN_POISON_ACTIVE #define _MHD_RED_ZONE_SIZE (0) #else /* MHD_ASAN_POISON_ACTIVE */ #define _MHD_RED_ZONE_SIZE (ALIGN_SIZE) #endif /* MHD_ASAN_POISON_ACTIVE */ #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) (ROUND_TO_ALIGN(n) + _MHD_RED_ZONE_SIZE) /* The previous macros are borrowed from memorypool.c Keep them in sync! */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define TEST_UPLOAD_DATA_SIZE 2048U #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST_PATH URL_SCHEME URL_HOST EXPECTED_URI_BASE_PATH #define RP_HEADER1_NAME "First" #define RP_HEADER1_VALUE "1st" #define RP_HEADER1 RP_HEADER1_NAME ": " RP_HEADER1_VALUE #define RP_HEADER1_CRLF RP_HEADER1 "\r\n" #define RP_HEADER2_NAME "Normal" #define RP_HEADER2_VALUE "it's fine" #define RP_HEADER2 RP_HEADER2_NAME ": " RP_HEADER2_VALUE #define RP_HEADER2_CRLF RP_HEADER2 "\r\n" #define HDR_FOLD "\r\n " #define RQ_HEADER1_NAME RP_HEADER1_NAME #define RQ_HEADER1_VALUE RP_HEADER1_VALUE #define RQ_HEADER1 RQ_HEADER1_NAME ": " RQ_HEADER1_VALUE #define RQ_HEADER2_NAME "Folded" #define RQ_HEADER2_VALUE_S "start" #define RQ_HEADER2_VALUE_E "end" #define RQ_HEADER2_VALUE \ RQ_HEADER2_VALUE_S HDR_FOLD RQ_HEADER2_VALUE_E #define RQ_HEADER2_VALUE_DF \ RQ_HEADER2_VALUE_S HDR_FOLD HDR_FOLD RQ_HEADER2_VALUE_E #define RQ_HEADER2 RQ_HEADER2_NAME ": " RQ_HEADER2_VALUE #define RQ_HEADER2_DF RQ_HEADER2_NAME ": " RQ_HEADER2_VALUE_DF #define RQ_HEADER3_NAME RP_HEADER2_NAME #define RQ_HEADER3_VALUE RP_HEADER2_VALUE #define RQ_HEADER3 RQ_HEADER3_NAME ": " RQ_HEADER3_VALUE /** * The number of request headers: 3 custom headers + 2 automatic headers */ #define RQ_NUM_HEADERS (3 + 2) /** * The extra size in the memory pool for pointers to the headers */ #define HEADERS_POINTERS_SIZE \ RQ_NUM_HEADERS * \ ROUND_TO_ALIGN_PLUS_RED_ZONE(sizeof(struct MHD_HTTP_Req_Header)) #define PAGE \ "libmicrohttpd demo page" \ "Success!" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static int use_get; static int use_put; static int use_put_large; static int use_double_fold; static int use_hdr_last; /**< If non-zero, folded header is placed last */ static int use_hdr_large; /**< If non-zero, folded header is large */ /* Static data */ static struct curl_slist *libcurl_headers = NULL; static char *put_data = NULL; /** * Initialise headers for libcurl * * @return non-zero if succeed, * zero if failed */ static void libcurl_headers_init (void) { libcurl_headers = curl_slist_append (NULL, RQ_HEADER1); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); if (use_hdr_last) { libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER3); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } if (! use_hdr_large) { if (! use_double_fold) libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER2); else libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER2_DF); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } else { char *buf; size_t pos; buf = malloc (TEST_UPLOAD_DATA_SIZE + 1); if (NULL == buf) externalErrorExitDesc ("malloc() failed"); pos = 0; memcpy (buf, RQ_HEADER2_NAME, MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME); buf[pos++] = ':'; buf[pos++] = ' '; memcpy (buf + pos, RQ_HEADER2_VALUE_S, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S); memcpy (buf + pos, HDR_FOLD, MHD_STATICSTR_LEN_ (HDR_FOLD)); pos += MHD_STATICSTR_LEN_ (HDR_FOLD); if (use_double_fold) { memcpy (buf + pos, HDR_FOLD, MHD_STATICSTR_LEN_ (HDR_FOLD)); pos += MHD_STATICSTR_LEN_ (HDR_FOLD); } memset (buf + pos, 'a', TEST_UPLOAD_DATA_SIZE - pos - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E) - 1); pos += TEST_UPLOAD_DATA_SIZE - pos - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E) - 1; buf[pos++] = ' '; memcpy (buf + pos, RQ_HEADER2_VALUE_E, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E); if (TEST_UPLOAD_DATA_SIZE != pos) externalErrorExitDesc ("Position miscalculation"); buf[pos] = 0; libcurl_headers = curl_slist_append (libcurl_headers, buf); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); free (buf); } if (! use_hdr_last) { libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER3); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } } static void init_put_data (void) { size_t i; put_data = malloc (TEST_UPLOAD_DATA_SIZE + 1); if (NULL == put_data) externalErrorExit (); for (i = 0; i < (TEST_UPLOAD_DATA_SIZE - 1); ++i) { if (0 == (i % 7)) put_data[i] = ' '; else if (0 == (i % 47)) put_data[i] = '\n'; else if (0 == (i % 11)) put_data[i] = (char) ('A' + i % ('Z' - 'A' + 1)); else put_data[i] = (char) ('a' + i % ('z' - 'a' + 1)); } put_data[TEST_UPLOAD_DATA_SIZE - 1] = '\n'; put_data[TEST_UPLOAD_DATA_SIZE] = 0; } static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); init_put_data (); libcurl_headers_init (); } static void test_global_cleanup (void) { curl_slist_free_all (libcurl_headers); curl_global_cleanup (); if (NULL != put_data) free (put_data); put_data = NULL; } struct headers_check_result { unsigned int expected_size; int header1_found; int header2_found; unsigned int size_found; unsigned int size_broken_found; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((MHD_STATICSTR_LEN_ (RP_HEADER1_CRLF) == data_size) && (0 == memcmp (RP_HEADER1_CRLF, buffer, data_size))) check_res->header1_found++; else if ((MHD_STATICSTR_LEN_ (RP_HEADER2_CRLF) == data_size) && (0 == memcmp (RP_HEADER2_CRLF, buffer, data_size))) check_res->header2_found++; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ") < data_size) && (0 == memcmp (MHD_HTTP_HEADER_CONTENT_LENGTH ": ", buffer, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")))) { char cmpbuf[256]; int res; const unsigned int numbers_pos = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); res = snprintf (cmpbuf, sizeof(cmpbuf), "%u", check_res->expected_size); if ((res <= 0) || (res > ((int) (sizeof(cmpbuf) - 1)))) externalErrorExit (); if (data_size - numbers_pos <= 2) { fprintf (stderr, "Broken Content-Length.\n"); check_res->size_broken_found++; } else if ((((size_t) res + 2) != data_size - numbers_pos) || (0 != memcmp (buffer + numbers_pos, cmpbuf, (size_t) res))) { fprintf (stderr, "Wrong Content-Length. " "Expected: %u. " "Received: %.*s.\n", check_res->expected_size, (int) (data_size - numbers_pos - 2), buffer + numbers_pos); check_res->size_broken_found++; } else if (0 != memcmp ("\r\n", buffer + data_size - 2, 2)) { fprintf (stderr, "The Content-Length header is not " "terminated by CRLF.\n"); check_res->size_broken_found++; } else check_res->size_found++; } return data_size; } struct CBC { /* Upload members */ size_t up_pos; size_t up_size; /* Download members */ char *dn_buf; size_t dn_pos; size_t dn_buf_size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->dn_pos + size * nmemb > cbc->dn_buf_size) return 0; /* overflow */ memcpy (&cbc->dn_buf[cbc->dn_pos], ptr, size * nmemb); cbc->dn_pos += size * nmemb; return size * nmemb; } static size_t libcurlUploadDataCB (void *stream, size_t item_size, size_t nitems, void *ctx) { size_t to_fill; struct CBC *cbc = ctx; to_fill = cbc->up_size - cbc->up_pos; if (to_fill > item_size * nitems) to_fill = item_size * nitems; /* Avoid libcurl magic numbers */ #ifdef CURL_READFUNC_PAUSE if (CURL_READFUNC_PAUSE == to_fill) to_fill = (CURL_READFUNC_PAUSE - 2); #endif /* CURL_READFUNC_PAUSE */ #ifdef CURL_READFUNC_ABORT if (CURL_READFUNC_ABORT == to_fill) to_fill = (CURL_READFUNC_ABORT - 1); #endif /* CURL_READFUNC_ABORT */ memcpy (stream, put_data + cbc->up_pos, to_fill); cbc->up_pos += to_fill; return to_fill; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST_PATH)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, libcurl_headers)) libcurlErrorExitDesc ("Failed to set request headers"); if (use_put) { if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, libcurlUploadDataCB)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, cbc))) libcurlErrorExitDesc ("Failed to configure the PUT upload"); } return c; } struct ahc_cls_type { const char *rq_method; const char *rq_url; unsigned int num_req; /* Position in the upload data, not compatible with parallel requests */ size_t up_pos; size_t expected_upload_size; unsigned int req_check_error; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (NULL != upload_data) { size_t report_processed_size; if (0 == *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is zero"); report_processed_size = *upload_data_size; /* The next checks are not compatible with parallel requests */ if (*upload_data_size > param->expected_upload_size - param->up_pos) { fprintf (stderr, "Unexpected *upload_data_size value: %lu. " "Already processed data size: %lu. " "Total expected upload size: %lu. " "Expected unprocessed upload size: %lu. " "The upload data cannot be checked.\n", (unsigned long) *upload_data_size, (unsigned long) param->up_pos, (unsigned long) param->expected_upload_size, (unsigned long) (param->expected_upload_size - param->up_pos)); param->req_check_error++; } else { if (0 != memcmp (upload_data, put_data + param->up_pos, *upload_data_size)) { fprintf (stderr, "Wrong upload data.\n" "Expected: '%.*s'\n" "Received: '%.*s'.\n", (int) *upload_data_size, upload_data, (int) *upload_data_size, put_data + param->up_pos); param->req_check_error++; } if (use_put_large && (report_processed_size > param->expected_upload_size / 10)) report_processed_size = param->expected_upload_size / 10; param->up_pos += report_processed_size; } *upload_data_size -= report_processed_size; return MHD_YES; } else { if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); } if (1) { /* Check headers */ const char *value; size_t value_len; unsigned int header_check_error; header_check_error = 0; value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, RQ_HEADER1_NAME); if (NULL == value) { fprintf (stderr, "Request header '" RQ_HEADER1_NAME "' not found.\n"); header_check_error++; } else { if (0 != strcmp (value, RQ_HEADER1_VALUE)) { fprintf (stderr, "Wrong header '" RQ_HEADER1_NAME "'value. " "Expected: '%s'. Received: '%s'.\n", RQ_HEADER1_VALUE, value); header_check_error++; } } if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, RQ_HEADER2_NAME, MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME), &value, &value_len)) { fprintf (stderr, "Request header '" RQ_HEADER2_NAME "' not found.\n"); header_check_error++; } else { if (NULL == value) mhdErrorExitDesc ("The 'value' pointer is NULL"); if (strlen (value) != value_len) mhdErrorExitDesc ("The 'value' length does not match strlen(value)"); if (value_len < MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S) + MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E)) { fprintf (stderr, "The value_len is too short. The value: '%s'.\n", value); header_check_error++; } if (0 != memcmp (value, RQ_HEADER2_VALUE_S, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S))) { fprintf (stderr, "The 'value' does not start with '" RQ_HEADER2_VALUE_S "'. The 'value' is '%s'. ", value); header_check_error++; } if (0 != memcmp (value + value_len - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E), RQ_HEADER2_VALUE_E, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E))) { fprintf (stderr, "The 'value' does not end with '" RQ_HEADER2_VALUE_E "'. The 'value' is '%s'. ", value); header_check_error++; } } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, RQ_HEADER3_NAME); if (NULL == value) { fprintf (stderr, "Request header '" RQ_HEADER3_NAME "' not found.\n"); header_check_error++; } else { if (0 != strcmp (value, RQ_HEADER3_VALUE)) { fprintf (stderr, "Wrong header '" RQ_HEADER3_NAME "'value. " "Expected: '%s'. Received: '%s'.\n", RQ_HEADER3_VALUE, value); header_check_error++; } } param->req_check_error += header_check_error; } if (&marker != *req_cls) { *req_cls = ▮ if (param->num_req) mhdErrorExitDesc ("Got unexpected second request"); param->num_req++; return MHD_YES; } *req_cls = NULL; if (0 != strcmp (url, EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "Unexpected URI: '%s'. ", url); mhdErrorExitDesc ("Unexpected URI found"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); if (MHD_YES != MHD_add_response_header (response, RP_HEADER1_NAME, RP_HEADER1_VALUE)) mhdErrorExitDesc ("Cannot add header1"); if (MHD_YES != MHD_add_response_header (response, RP_HEADER2_NAME, RP_HEADER2_VALUE)) mhdErrorExitDesc ("Cannot add header2"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; int libcurl_finished; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); libcurl_finished = 0; start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! libcurl_finished) { int running; curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); libcurl_finished = ! 0; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (libcurl_finished) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct CBC *pcbc, struct headers_check_result *hdr_res, struct ahc_cls_type *ahc_cls) { long code; unsigned int ret; fflush (stderr); fflush (stdout); if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); ret = 1; if (ahc_cls->req_check_error) { fprintf (stderr, "One or more errors have been detected by access " "handler callback.\n"); ret = 0; } if (ahc_cls->expected_upload_size != ahc_cls->up_pos) { fprintf (stderr, "Upload size does not match expected. " "Expected: %lu. " "Received: %lu.\n", (unsigned long) ahc_cls->expected_upload_size, (unsigned long) ahc_cls->up_pos); ret = 0; } if (1 != hdr_res->header1_found) { if (0 == hdr_res->header1_found) fprintf (stderr, "Response header1 was not found.\n"); else fprintf (stderr, "Response header1 was found %d times " "instead of one time only.\n", hdr_res->header1_found); ret = 0; } else if (verbose) printf ("Header1 is present in the response.\n"); if (1 != hdr_res->header2_found) { if (0 == hdr_res->header2_found) fprintf (stderr, "Response header2 was not found.\n"); else fprintf (stderr, "Response header2 was found %d times " "instead of one time only.\n", hdr_res->header2_found); ret = 0; } else if (verbose) printf ("Header2 is present in the response.\n"); if (1 != hdr_res->size_found) { if (0 == hdr_res->size_found) fprintf (stderr, "Correct response 'Content-Length' header " "was not found.\n"); else fprintf (stderr, "Correct response 'Content-Length' header " "was found %u times instead of one time only.\n", hdr_res->size_found); ret = 0; } else if (verbose) printf ("'Content-Length' header with correct value " "is present in the response.\n"); if (0 != hdr_res->size_broken_found) { fprintf (stderr, "Wrong response 'Content-Length' header was found " "%u times.\n", hdr_res->size_broken_found); ret = 0; } if (pcbc->dn_pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->dn_pos, (int) pcbc->dn_pos, pcbc->dn_buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->dn_buf, pcbc->dn_pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->dn_pos, pcbc->dn_buf); mhdErrorExitDesc ("Wrong returned data"); } fflush (stderr); fflush (stdout); return ret; } static unsigned int performCheck (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; struct headers_check_result rp_headers_check; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = UINT16_C (4220); if (! oneone) port += UINT16_C (1); if (use_put) port += UINT16_C (2); if (use_put_large) port += UINT16_C (4); if (use_hdr_last) port += UINT16_C (8); if (use_hdr_large) port += UINT16_C (16); } if (1) { size_t mem_limit; if (use_put_large) mem_limit = (size_t) (TEST_UPLOAD_DATA_SIZE / 2 + HEADERS_POINTERS_SIZE); else mem_limit = (size_t) ((TEST_UPLOAD_DATA_SIZE * 4) / 3 + 2 + HEADERS_POINTERS_SIZE); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = use_put ? MHD_HTTP_METHOD_PUT : MHD_HTTP_METHOD_GET; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; ahc_param.expected_upload_size = use_put ? TEST_UPLOAD_DATA_SIZE : 0; ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; cbc.dn_buf = buf; cbc.dn_buf_size = sizeof (buf); cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_size = TEST_UPLOAD_DATA_SIZE; cbc.up_pos = 0; c = setupCURL (&cbc, port, &rp_headers_check); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; /* Reset buffer position */ cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_pos = 0; if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; /* Reset buffer position */ cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_pos = 0; if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); use_get = has_in_name (argv[0], "_get"); use_put = has_in_name (argv[0], "_put"); use_double_fold = has_in_name (argv[0], "_double_fold"); use_put_large = has_in_name (argv[0], "_put_large"); use_hdr_last = has_in_name (argv[0], "_last"); use_hdr_large = has_in_name (argv[0], "_fold_large"); if (1 != ((use_get ? 1 : 0) + (use_put ? 1 : 0))) { fprintf (stderr, "Wrong test name '%s': no or multiple indications " "for the test type.\n", argv[0] ? argv[0] : "(NULL)"); return 99; } test_global_init (); errorCount += performCheck (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_process_headers.c0000644000175000017500000003760614760713574020341 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_process_headers.c * @brief Testcase for HTTP header access * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result kv_cb (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { if ((0 == strcmp (key, MHD_HTTP_HEADER_HOST)) && (0 == strncmp (value, "127.0.0.1", strlen ("127.0.0.1"))) && (kind == MHD_HEADER_KIND)) { *((int *) cls) = 1; return MHD_NO; } return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *hdr; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = 0; MHD_get_connection_values (connection, MHD_HEADER_KIND, &kv_cb, &ret); if (ret != 1) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, "NotFound"); if (hdr != NULL) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT); if ((hdr == NULL) || (0 != strcmp (hdr, "*/*"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST); if ((hdr == NULL) || (0 != strncmp (hdr, "127.0.0.1", strlen ("127.0.0.1")))) abort (); MHD_set_connection_value (connection, MHD_HEADER_KIND, "FakeHeader", "NowPresent"); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, "FakeHeader"); if ((hdr == NULL) || (0 != strcmp (hdr, "NowPresent"))) abort (); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) abort (); MHD_add_response_header (response, "MyHeader", "MyValue"); hdr = MHD_get_response_header (response, "MyHeader"); if (0 != strcmp ("MyValue", hdr)) abort (); MHD_add_response_header (response, "MyHeader", "MyValueToo"); if (MHD_YES != MHD_del_response_header (response, "MyHeader", "MyValue")) abort (); hdr = MHD_get_response_header (response, "MyHeader"); if (0 != strcmp ("MyValueToo", hdr)) abort (); if (1 != MHD_get_response_headers (response, NULL, NULL)) abort (); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1420; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1421; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1422; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1423; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_process_arguments.c0000644000175000017500000002104414760713574020720 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_process_arguments.c * @brief Testcase for HTTP URI arguments * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *hdr; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "k"); if ((hdr == NULL) || (0 != strcmp (hdr, "v x"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "hash"); if ((hdr == NULL) || (0 != strcmp (hdr, "#foo"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "space"); if ((hdr == NULL) || (0 != strcmp (hdr, "\240bar"))) abort (); if (3 != MHD_get_connection_values (connection, MHD_GET_ARGUMENT_KIND, NULL, NULL)) abort (); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1410; if (oneone) port += 5; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello+world?k=v+x&hash=%23foo&space=%A0bar"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello+world")) return 8192; if (0 != strncmp ("/hello+world", cbc.buf, strlen ("/hello+world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/perf_get.c0000644000175000017500000004560114760713574015716 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file perf_get.c * @brief benchmark simple GET operations (sequential access). * Note that we run libcurl in the same process at the * same time, so the execution time given is the combined * time for both MHD and libcurl; it is quite possible * that more time is spend with libcurl than with MHD, * so the performance scores calculated with this code * should NOT be used to compare with other HTTP servers * (since MHD is actually better); only the relative * scores between MHD versions are meaningful. * Furthermore, this code ONLY tests MHD processing * a single request at a time. This is again * not universally meaningful (i.e. when comparing * multithreaded vs. single-threaded or select/poll). * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test? */ #if MHD_CPU_COUNT > 8 #ifndef _WIN32 #define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT) #else /* _WIN32 */ #define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT) #endif /* _WIN32 */ #else #define ROUNDS 500 #endif /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Time this round was started. */ static unsigned long long start_time; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } /** * Start the timer. */ static void start_timer (void) { start_time = now (); } /** * Stop the timer and report performance * * @param desc description of the threading mode we used */ static void stop (const char *desc) { double rps = ((double) (ROUNDS * 1000)) / ((double) (now () - start_time)); fprintf (stderr, "Sequential GETs using %s: %f %s\n", desc, rps, "requests/s"); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); } stop (poll_flag == MHD_USE_AUTO ? "internal thread with 'auto'" : poll_flag == MHD_USE_POLL ? "internal thread with poll()" : poll_flag == MHD_USE_EPOLL ? "internal thread with epoll" : "internal thread with select()"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); } stop ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto' and thread per connection" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll() and thread per connection" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll and thread per connection" : "internal thread with select() and thread per connection"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); } stop (0 != (poll_flag & MHD_USE_AUTO) ? "internal thread pool with 'auto'" : 0 != (poll_flag & MHD_USE_POLL) ? "internal thread pool with poll()" : 0 != (poll_flag & MHD_USE_EPOLL) ? "internal thread pool with epoll" : "internal thread pool with select()"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (uint16_t port) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; multi = NULL; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); multi = curl_multi_init (); if (multi == NULL) { MHD_stop_daemon (d); return 512; } for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (c != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); c = NULL; break; } /* two possibilities here; as select sets are tiny, this makes virtually no difference in actual runtime right now, even though the number of select calls is virtually cut in half (and 'select' is the most expensive of our system calls according to 'strace') */ if (0) MHD_run (d); else MHD_run_from_select (d, &rs, &ws, &es); } if (NULL != c) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); fprintf (stderr, "Timeout!?\n"); } } stop ("external select"); if (multi != NULL) { curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port = 1130; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 15; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testExternalGet (port++); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO); errorCount += testInternalGet (port++, 0); errorCount += testMultithreadedGet (port++, 0); errorCount += testMultithreadedPoolGet (port++, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (port++, MHD_USE_POLL); errorCount += testMultithreadedGet (port++, MHD_USE_POLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (port++, MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL); } } MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_head.c0000644000175000017500000006242514760713574016066 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_head.c * @brief Testcase for HEAD requests * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/" #define EXISTING_URI EXPECTED_URI_BASE_PATH #define EXPECTED_URI_BASE_PATH_MISSING "/wrong_uri" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define HEADER1_NAME "First" #define HEADER1_VALUE "1st" #define HEADER1 HEADER1_NAME ": " HEADER1_VALUE #define HEADER1_CRLF HEADER1 "\r\n" #define HEADER2_NAME "Normal" #define HEADER2_VALUE "it's fine" #define HEADER2 HEADER2_NAME ": " HEADER2_VALUE #define HEADER2_CRLF HEADER2 "\r\n" #define PAGE \ "libmicrohttpd demo page" \ "Success!" #define PAGE_404 \ "404 error" \ "Error 404: The requested URI does not exist" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { unsigned int expected_size; int header1_found; int header2_found; int size_found; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((MHD_STATICSTR_LEN_ (HEADER1_CRLF) == data_size) && (0 == memcmp (HEADER1_CRLF, buffer, data_size))) check_res->header1_found++; else if ((MHD_STATICSTR_LEN_ (HEADER2_CRLF) == data_size) && (0 == memcmp (HEADER2_CRLF, buffer, data_size))) check_res->header2_found++; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ") < data_size) && (0 == memcmp (MHD_HTTP_HEADER_CONTENT_LENGTH ": ", buffer, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")))) { char cmpbuf[256]; int res; const unsigned int numbers_pos = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); res = snprintf (cmpbuf, sizeof(cmpbuf), "%u", check_res->expected_size); if ((res <= 0) || (res > ((int) (sizeof(cmpbuf) - 1)))) externalErrorExit (); if (data_size - numbers_pos <= 2) mhdErrorExitDesc ("Broken Content-Length"); else if ((((size_t) res + 2) != data_size - numbers_pos) || (0 != memcmp (buffer + numbers_pos, cmpbuf, (size_t) res))) { fprintf (stderr, "Wrong Content-Length.\n" "Expected:\n%u\n" "Received:\n%s", check_res->expected_size, buffer + numbers_pos); mhdErrorExitDesc ("Wrong Content-Length"); } else if (0 != memcmp ("\r\n", buffer + data_size - 2, 2)) { mhdErrorExitDesc ("The Content-Length header is not " \ "terminated by CRLF"); } check_res->size_found++; } return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; /* Unused, mute compiler warning */ (void) ctx; /* Unused, mute compiler warning */ if ((0 != size) && (0 != nmemb)) libcurlErrorExitDesc ("Received unexpected body data"); return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int http_code; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; if (0 == strcmp (url, EXISTING_URI)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); http_code = MHD_HTTP_OK; } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404), PAGE_404); http_code = MHD_HTTP_NOT_FOUND; } if (NULL == response) mhdErrorExitDesc ("Failed to create response"); if (MHD_YES != MHD_add_response_header (response, HEADER1_NAME, HEADER1_VALUE)) mhdErrorExitDesc ("Cannot add header1"); if (MHD_YES != MHD_add_response_header (response, HEADER2_NAME, HEADER2_VALUE)) mhdErrorExitDesc ("Cannot add header2"); ret = MHD_queue_response (connection, http_code, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } /** * Set required URI for the request * @param c the CURL handle to use * @param uri_exist if non-zero use request for "existing" URI */ static void setCURL_rq_path (CURL *c, int uri_exist) { if (uri_exist) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URL"); } else { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH_MISSING)) libcurlErrorExitDesc ("Cannot set request URL"); } } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); /* When 'CURLOPT_NOBODY' is set, libcurl should use HEAD request. */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_NOBODY, (long) 1)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct headers_check_result *hdr_res) { long code; unsigned int ret; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); ret = 1; if (1 != hdr_res->header1_found) { if (0 == hdr_res->header1_found) fprintf (stderr, "Response header1 was not found.\n"); else fprintf (stderr, "Response header1 was found %d times " "instead of one time only.\n", hdr_res->header1_found); ret = 0; } else if (verbose) printf ("Header1 is present in the response.\n"); if (1 != hdr_res->header2_found) { if (0 == hdr_res->header2_found) fprintf (stderr, "Response header2 was not found.\n"); else fprintf (stderr, "Response header2 was found %d times " "instead of one time only.\n", hdr_res->header2_found); ret = 0; } else if (verbose) printf ("Header2 is present in the response.\n"); if (1 != hdr_res->size_found) { if (0 == hdr_res->size_found) fprintf (stderr, "Response 'Content-Length' header was not found.\n"); else fprintf (stderr, "Response 'Content-Length' header was found %d times " "instead of one time only.\n", hdr_res->size_found); ret = 0; } else if (verbose) printf ("'Content-Length' header with correct value " "is present in the response.\n"); return ret; } static unsigned int testHead (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; struct headers_check_result rp_headers_check; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4220 + oneone ? 0 : 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = MHD_HTTP_METHOD_HEAD; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, &rp_headers_check); setCURL_rq_path (c, 1); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE_404); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.pos = 0; /* Reset buffer position */ ahc_param.rq_url = EXPECTED_URI_BASE_PATH_MISSING; setCURL_rq_path (c, 0); if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_NOT_FOUND, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.pos = 0; /* Reset buffer position */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_NOT_FOUND, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); test_global_init (); errorCount += testHead (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_patch.c0000644000175000017500000003223014760713574016253 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2020 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_patch.c * @brief Testcase for libmicrohttpd PATCH operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PATCH", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static CURL * setup_curl (long port, struct CBC *cbc, size_t *pos) { CURL *c; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); return c; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1450; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1451; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1452; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1453; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_timeout.c0000644000175000017500000002621115035214304016623 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_timeout.c * @brief Testcase for libmicrohttpd PUT operations * @author Matthias Wachs * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #include "mhd_has_in_name.h" /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else fprintf (stderr, "No sleep function available on this system.\n"); #endif } static int oneone; static int withTimeout = 0; static int withoutTimeout = 0; struct CBC { char *buf; size_t pos; size_t size; }; static void termination_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { int *test = cls; (void) connection; (void) req_cls; /* Unused. Silent compiler warning. */ switch (toe) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: if (test == &withoutTimeout) { withoutTimeout = 1; } else { fprintf (stderr, "Connection completed without errors while " "timeout is expected.\n"); } break; case MHD_REQUEST_TERMINATED_WITH_ERROR: fprintf (stderr, "Connection terminated with error.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_READ_ERROR: fprintf (stderr, "Connection terminated with read error.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: if (test == &withTimeout) { withTimeout = 1; } else { fprintf (stderr, "Connection terminated with timeout while expected " "to be successfully completed.\n"); } break; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: fprintf (stderr, "Connection terminated by daemon shutdown.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: fprintf (stderr, "Connection terminated by client.\n"); exit (4); break; } } static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t putBuffer_fail (void *stream, size_t size, size_t nmemb, void *ptr) { (void) stream; (void) size; (void) nmemb; (void) ptr; /* Unused. Silent compiler warning. */ _MHD_sleep (100); /* Avoid busy-waiting */ return 0; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_PUT, method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testWithoutTimeout (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1500; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_TIMEOUT, 2, MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withoutTimeout, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); withoutTimeout = 0; if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (0 == withoutTimeout) { fprintf (stderr, "Request wasn't processed successfully.\n"); return 2; } if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testWithTimeout (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1501; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_TIMEOUT, 2, MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withTimeout, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer_fail); curl_easy_setopt (c, CURLOPT_READDATA, &testWithTimeout); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); withTimeout = 0; if (CURLE_OK != (errornum = curl_easy_perform (c))) { curl_easy_cleanup (c); MHD_stop_daemon (d); if ((errornum == CURLE_GOT_NOTHING) || (CURLE_READ_ERROR == errornum)) { if (0 != withTimeout) { /* mhd had the timeout */ return 0; } else { fprintf (stderr, "Timeout wasn't detected.\n"); return 8; } } else { fprintf (stderr, "libcurl reported error: %s (%u)\n", curl_easy_strerror (errornum), errornum); return 32; } } curl_easy_cleanup (c); MHD_stop_daemon (d); return 64; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 16; errorCount += testWithoutTimeout (); errorCount += testWithTimeout (); if (errorCount != 0) fprintf (stderr, "Error during test execution (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_add_conn.c0000644000175000017500000011116614760713574016727 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) - large rework, multithreading. libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_add_conn.c * @brief Testcase for libmicrohttpd GET operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_PTHREAD_H #include #endif /* HAVE_PTHREAD_H */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Number of requests per daemon in cleanup test, * the number must be more than one as the first connection * will be processed and the rest will stay in the list of unprocessed */ #define CLEANUP_NUM_REQS_PER_DAEMON 6 /* Cleanup test: max number of concurrent daemons depending on maximum number * of open FDs. */ #define CLEANUP_MAX_DAEMONS(max_fds) (unsigned int) \ ( ((max_fds) < 10) ? \ 0 : ( (((max_fds) - 10) / (CLEANUP_NUM_REQS_PER_DAEMON * 5 + 3)) ) ) #define EXPECTED_URI_BASE_PATH "/hello_world" #define EXPECTED_URI_QUERY "a=%26&b=c" #define EXPECTED_URI_FULL_PATH EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY /* Global parameters */ static int oneone; /**< Use HTTP/1.1 instead of HTTP/1.0 */ static int no_listen; /**< Start MHD daemons without listen socket */ static uint16_t global_port; /**< MHD daemons listen port number */ static int cleanup_test; /**< Test for final cleanup */ static int slow_reply = 0; /**< Slowdown MHD replies */ static int ignore_response_errors = 0; /**< Do not fail test if CURL returns error */ static int response_timeout_val = TIMEOUTS_VAL; static int sys_max_fds; /**< Current system limit for number of open files. */ struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_FULL_PATH)) { fprintf (stderr, "Wrong URI: `%s'\n", uri); _exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *v; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; v = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "a"); if ( (NULL == v) || (0 != strcmp ("&", v)) ) { fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n", NULL == v ? "NULL" : v); _exit (17); } v = NULL; if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_GET_ARGUMENT_KIND, "b", 1, &v, NULL)) { fprintf (stderr, "Not found 'b' GET argument.\n"); _exit (18); } if ( (NULL == v) || (0 != strcmp ("c", v)) ) { fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n", NULL == v ? "NULL" : v); _exit (19); } if (slow_reply) usleep (200000); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (19); } return ret; } _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); _exit (99); } #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #endif /* Static const value, indicates that result value was not set yet */ static const unsigned int eMarker = 0xCE; static MHD_socket createListeningSocket (uint16_t *pport) { MHD_socket skt; struct sockaddr_in sin; socklen_t sin_len; #ifdef MHD_POSIX_SOCKETS static int on = 1; #endif /* MHD_POSIX_SOCKETS */ skt = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == skt) externalErrorExitDesc ("socket() failed"); #ifdef MHD_POSIX_SOCKETS setsockopt (skt, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on)); /* Ignore possible error */ #endif /* MHD_POSIX_SOCKETS */ memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (*pport); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != bind (skt, (struct sockaddr *) &sin, sizeof(sin))) externalErrorExitDesc ("bind() failed"); if (0 != listen (skt, SOMAXCONN)) externalErrorExitDesc ("listen() failed"); if (0 == *pport) { memset (&sin, 0, sizeof(sin)); sin_len = (socklen_t) sizeof(sin); if (0 != getsockname (skt, (struct sockaddr *) &sin, &sin_len)) externalErrorExitDesc ("getsockname() failed"); if (sizeof(sin) < (size_t) sin_len) externalErrorExitDesc ("getsockname() failed"); if (AF_INET != sin.sin_family) externalErrorExitDesc ("getsockname() returned wrong socket family"); *pport = ntohs (sin.sin_port); } return skt; } static MHD_socket acceptTimeLimited (MHD_socket lstn_sk, struct sockaddr *paddr, socklen_t *paddr_len) { fd_set rs; struct timeval timeoutval; MHD_socket accepted; FD_ZERO (&rs); FD_SET (lstn_sk, &rs); timeoutval.tv_sec = TIMEOUTS_VAL; timeoutval.tv_usec = 0; if (1 != select (((int) lstn_sk) + 1, &rs, NULL, NULL, &timeoutval)) externalErrorExitDesc ("select() failed"); accepted = accept (lstn_sk, paddr, paddr_len); if (MHD_INVALID_SOCKET == accepted) externalErrorExitDesc ("accept() failed"); return accepted; } struct addConnParam { struct MHD_Daemon *d; MHD_socket lstn_sk; MHD_socket clent_sk; /* Non-zero indicate error */ volatile unsigned int result; #ifdef HAVE_PTHREAD_H pthread_t addConnThread; #endif /* HAVE_PTHREAD_H */ }; static unsigned int doAcceptAndAddConnInThread (struct addConnParam *p) { struct sockaddr addr; socklen_t addr_len = sizeof(addr); p->clent_sk = acceptTimeLimited (p->lstn_sk, &addr, &addr_len); p->result = (MHD_YES == MHD_add_connection (p->d, p->clent_sk, &addr, addr_len)) ? 0 : 1; if (p->result) fprintf (stderr, "MHD_add_connection() failed, errno=%d.\n", errno); return p->result; } #ifdef HAVE_PTHREAD_H static void * doAcceptAndAddConn (void *param) { struct addConnParam *p = param; (void) doAcceptAndAddConnInThread (p); return (void *) p; } static void startThreadAddConn (struct addConnParam *param) { /* thread must reset this value to zero if succeed */ param->result = eMarker; if (0 != pthread_create (¶m->addConnThread, NULL, &doAcceptAndAddConn, (void *) param)) externalErrorExitDesc ("pthread_create() failed"); } static unsigned int finishThreadAddConn (struct addConnParam *param) { struct addConnParam *result; if (0 != pthread_join (param->addConnThread, (void **) &result)) externalErrorExitDesc ("pthread_join() failed"); if (param != result) abort (); /* Test used in a wrong way */ if (eMarker == param->result) abort (); /* Test used in a wrong way */ return result->result; } #endif /* HAVE_PTHREAD_H */ struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Destination port for CURL query */ uint16_t queryPort; /* CURL query result error flag */ volatile unsigned int queryError; #ifdef HAVE_PTHREAD_H pthread_t queryThread; #endif /* HAVE_PTHREAD_H */ }; static CURL * curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); _exit (99); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); _exit (99); } return c; } static unsigned int doCurlQueryInThread (struct curlQueryParams *p) { CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc); errornum = curl_easy_perform (c); if (ignore_response_errors) { p->queryError = 0; curl_easy_cleanup (c); return p->queryError; } if (CURLE_OK != errornum) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); p->queryError = 2; } else { if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "curl reports wrong size of MHD reply body data.\n"); p->queryError = 4; } else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf, strlen (EXPECTED_URI_BASE_PATH))) { fprintf (stderr, "curl reports wrong MHD reply body data.\n"); p->queryError = 4; } else p->queryError = 0; } curl_easy_cleanup (c); return p->queryError; } #ifdef HAVE_PTHREAD_H static void * doCurlQuery (void *param) { struct curlQueryParams *p = (struct curlQueryParams *) param; (void) doCurlQueryInThread (p); return param; } static void startThreadCurlQuery (struct curlQueryParams *param) { /* thread must reset this value to zero if succeed */ param->queryError = eMarker; if (0 != pthread_create (¶m->queryThread, NULL, &doCurlQuery, (void *) param)) externalErrorExitDesc ("pthread_create() failed"); } static unsigned int finishThreadCurlQuery (struct curlQueryParams *param) { struct curlQueryParams *result; if (0 != pthread_join (param->queryThread, (void **) &result)) externalErrorExitDesc ("pthread_join() failed"); if (param != result) abort (); /* Test used in wrong way */ if (eMarker == param->queryError) abort (); /* Test used in wrong way */ return result->queryError; } /* Perform test queries and shut down MHD daemon */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port) { struct curlQueryParams qParam; struct addConnParam aParam; uint16_t a_port; /* Additional listening socket port */ unsigned int ret = 0; /* Return value */ qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; a_port = 0; /* auto-assign */ aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ /* Test of adding connection in the same thread */ qParam.queryError = eMarker; /* to be zeroed in new thread */ qParam.queryPort = a_port; /* Connect to additional socket */ startThreadCurlQuery (&qParam); ret |= doAcceptAndAddConnInThread (&aParam); ret |= finishThreadCurlQuery (&qParam); if (! no_listen) { /* Test of the daemon itself can accept and process new connection. */ ret <<= 3; /* Remember errors for each step */ qParam.queryPort = d_port; /* Connect to the daemon */ ret |= doCurlQueryInThread (&qParam); } /* Test of adding connection in an external thread */ ret <<= 3; /* Remember errors for each step */ aParam.result = eMarker; /* to be zeroed in new thread */ qParam.queryPort = a_port; /* Connect to the daemon */ startThreadAddConn (&aParam); ret |= doCurlQueryInThread (&qParam); ret |= finishThreadAddConn (&aParam); (void) MHD_socket_close_ (aParam.lstn_sk); MHD_stop_daemon (d); return ret; } /* Perform test for cleanup and shutdown MHD daemon */ static unsigned int performTestCleanup (struct MHD_Daemon *d, unsigned int num_queries) { struct curlQueryParams *qParamList; struct addConnParam aParam; MHD_socket lstn_sk; /* Additional listening socket */ MHD_socket *clntSkList; uint16_t a_port; /* Additional listening socket port */ unsigned int i; unsigned int ret = 0; /* Return value */ a_port = 0; /* auto-assign */ if (0 >= num_queries) abort (); /* Test's API violation */ lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ qParamList = malloc (sizeof(struct curlQueryParams) * num_queries); clntSkList = malloc (sizeof(MHD_socket) * num_queries); if ((NULL == qParamList) || (NULL == clntSkList)) externalErrorExitDesc ("malloc failed"); /* Start CURL queries */ for (i = 0; i < num_queries; i++) { qParamList[i].queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; qParamList[i].queryError = 0; qParamList[i].queryPort = a_port; startThreadCurlQuery (qParamList + i); } /* Accept and add required number of client sockets */ aParam.d = d; aParam.lstn_sk = lstn_sk; for (i = 0; i < num_queries; i++) { aParam.clent_sk = MHD_INVALID_SOCKET; ret |= doAcceptAndAddConnInThread (&aParam); clntSkList[i] = aParam.clent_sk; } /* Stop daemon while some of new connection are not yet * processed because of slow response to the first queries. */ MHD_stop_daemon (d); (void) MHD_socket_close_ (aParam.lstn_sk); /* Check whether all client sockets were closed by MHD. * Closure of socket by MHD indicate valid cleanup performed. */ for (i = 0; i < num_queries; i++) { if (MHD_INVALID_SOCKET != clntSkList[i]) { /* Check whether socket could be closed one more time. */ if (MHD_socket_close_ (clntSkList[i])) { ret |= 2; fprintf (stderr, "Client socket was not closed by MHD during" \ "cleanup process.\n"); } } } /* Wait for CURL threads to complete. */ /* Ignore soft CURL errors as many connection shouldn't get any response. * Hard failures are detected in processing function. */ for (i = 0; i < num_queries; i++) (void) finishThreadCurlQuery (qParamList + i); free (clntSkList); free (qParamList); return ret; } #endif /* HAVE_PTHREAD_H */ enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; if (! cleanup_test) return numThreads; /* No practical limit for non-cleanup test */ if (CLEANUP_MAX_DAEMONS (sys_max_fds) < numThreads) numThreads = CLEANUP_MAX_DAEMONS (sys_max_fds); if ((testMhdPollBySelect == pollType) && (CLEANUP_MAX_DAEMONS (FD_SETSIZE) < numThreads)) numThreads = CLEANUP_MAX_DAEMONS (FD_SETSIZE); if (2 > numThreads) abort (); return (unsigned int) numThreads; } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 1550; if (oneone) *pport += 1; if (no_listen) *pport += 2; if (cleanup_test) *pport += 4; } switch (thrType) { case testMhdThreadExternal: d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_NO_THREAD_SAFETY | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); break; case testMhdThreadInternalPool: d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | MHD_USE_ITC | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); break; case testMhdThreadInternal: case testMhdThreadInternalPerConnection: d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ITC | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); break; default: abort (); break; } if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if ((! no_listen) && (0 == *pport)) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c_d; char buf_d[2048]; struct CBC cbc_d; CURL *c_a; char buf_a[2048]; struct CBC cbc_a; CURLM *multi; time_t start; struct timeval tv; uint16_t d_port = global_port; /* Daemon's port */ uint16_t a_port = 0; /* Additional listening socket port */ struct addConnParam aParam; unsigned int ret = 0; /* Return value of the test */ const int c_no_listen = no_listen; /* Local const value to mute analyzer */ d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port); aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); multi = NULL; cbc_d.buf = buf_d; cbc_d.size = sizeof(buf_d); cbc_d.pos = 0; cbc_a.buf = buf_a; cbc_a.size = sizeof(buf_a); cbc_a.pos = 0; if (cleanup_test) abort (); /* Not possible with "external poll" as connections are directly added to the daemon processing in the mode. */ if (! c_no_listen) c_d = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, d_port, &cbc_d); else c_d = NULL; /* To mute compiler warning only */ c_a = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, a_port, &cbc_a); multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed.\n"); _exit (99); } if (! c_no_listen) { if (CURLM_OK != curl_multi_add_handle (multi, c_d)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); _exit (99); } } if (CURLM_OK != curl_multi_add_handle (multi, c_a)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); _exit (99); } start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) { fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n"); _exit (99); } totalMsgs++; if (CURLMSG_DONE == msg->msg) { if (CURLE_OK != msg->data.result) { fprintf (stderr, "curl_multi_info_read failed, error: '%s'\n", curl_easy_strerror (msg->data.result)); ret |= 2; } } } while (msgLeft > 0); if ((no_listen ? 1 : 2) != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); _exit (99); } break; /* All transfers have finished. */ } if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) { fprintf (stderr, "curl_multi_fdset() failed.\n"); _exit (99); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) { ret |= 8; break; } FD_SET (aParam.lstn_sk, &rs); if (maxMhdSk < aParam.lstn_sk) maxMhdSk = aParam.lstn_sk; tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (FD_ISSET (aParam.lstn_sk, &rs)) ret |= doAcceptAndAddConnInThread (&aParam); if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) { fprintf (stderr, "MHD_run_from_select() failed.\n"); ret |= 1; break; } } MHD_stop_daemon (d); (void) MHD_socket_close_ (aParam.lstn_sk); if (! c_no_listen) { curl_multi_remove_handle (multi, c_d); curl_easy_cleanup (c_d); if (cbc_d.pos != strlen ("/hello_world")) { fprintf (stderr, "curl reports wrong size of MHD reply body data at line %d.\n", __LINE__); ret |= 4; } if (0 != strncmp ("/hello_world", cbc_d.buf, strlen ("/hello_world"))) { fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", __LINE__); ret |= 4; } } curl_multi_remove_handle (multi, c_a); curl_easy_cleanup (c_a); curl_multi_cleanup (multi); if (cbc_a.pos != strlen ("/hello_world")) { fprintf (stderr, "curl reports wrong size of MHD reply body data at line %d.\n", __LINE__); ret |= 4; } if (0 != strncmp ("/hello_world", cbc_a.buf, strlen ("/hello_world"))) { fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", __LINE__); ret |= 4; } return ret; } #ifdef HAVE_PTHREAD_H static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); if (cleanup_test) return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON); return performTestQueries (d, d_port); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port); if (cleanup_test) abort (); /* Cannot be tested as main daemon thread cannot be slowed down by slow responses, so it processes all new connections before daemon could be stopped. */ return performTestQueries (d, d_port); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port); if (cleanup_test) return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON * testNumThreadsForPool (pollType)); return performTestQueries (d, d_port); } static unsigned int testStopRace (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ uint16_t a_port = 0; /* Additional listening socket port */ struct sockaddr_in sin; MHD_socket fd1; MHD_socket fd2; struct addConnParam aParam; unsigned int ret = 0; /* Return value of the test */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); if (! no_listen) { fd1 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == fd1) externalErrorExitDesc ("socket() failed"); memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (d_port); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (connect (fd1, (struct sockaddr *) (&sin), sizeof(sin)) < 0) externalErrorExitDesc ("socket() failed"); } else fd1 = MHD_INVALID_SOCKET; aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ startThreadAddConn (&aParam); fd2 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == fd2) externalErrorExitDesc ("socket() failed"); memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (a_port); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (connect (fd2, (struct sockaddr *) (&sin), sizeof(sin)) < 0) externalErrorExitDesc ("socket() failed"); ret |= finishThreadAddConn (&aParam); /* Let the thread get going. */ usleep (500000); MHD_stop_daemon (d); if (MHD_INVALID_SOCKET != fd1) (void) MHD_socket_close_ (fd1); (void) MHD_socket_close_ (aParam.lstn_sk); (void) MHD_socket_close_ (fd2); return ret; } #endif /* HAVE_PTHREAD_H */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); /* Whether to test MHD daemons without listening socket. */ no_listen = has_in_name (argv[0], "_nolisten"); /* Whether to test for correct final cleanup instead of * of test of normal processing. */ cleanup_test = has_in_name (argv[0], "_cleanup"); /* There are almost nothing that could be tested externally * for final cleanup. Cleanup test actually just tests that * all added client connections were closed by MHD and * nothing fails or crashes when final cleanup is performed. * Mostly useful when configured with '--enable-asserts. */ slow_reply = cleanup_test; ignore_response_errors = cleanup_test; #ifndef HAVE_PTHREAD_H if (cleanup_test) return 77; /* Cannot run without threads */ #endif /* HAVE_PTHREAD_H */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (cleanup_test) { #ifndef _WIN32 /* Find system limit for number of open FDs. */ #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) sys_max_fds = sysconf (_SC_OPEN_MAX) > 500000 ? 500000 : (int) sysconf (_SC_OPEN_MAX); #else /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ sys_max_fds = -1; #endif /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ if (0 > sys_max_fds) { #if defined(OPEN_MAX) && (0 < ((OPEN_MAX) +1)) sys_max_fds = OPEN_MAX > 500000 ? 500000 : (int) OPEN_MAX; #else /* ! OPEN_MAX */ sys_max_fds = 256; /* Use reasonable value */ #endif /* ! OPEN_MAX */ if (2 > CLEANUP_MAX_DAEMONS (sys_max_fds)) return 77; /* Multithreaded test cannot be run */ } #else /* _WIN32 */ sys_max_fds = 120; /* W32 has problems with ports exhaust */ #endif /* _WIN32 */ } if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 99; /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; if (! cleanup_test) { test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; } #ifdef HAVE_PTHREAD_H if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; if (! cleanup_test) { test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testStopRace (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testStopRace (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (testMhdPollBySelect).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollByPoll).\n"); errorCount += test_result; if (! cleanup_test) { test_result = testMultithreadedGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollByPoll).\n"); errorCount += test_result; test_result = testStopRace (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testStopRace (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (testMhdPollByPoll).\n"); errorCount += test_result; } } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollByEpoll).\n"); errorCount += test_result; } } #endif /* HAVE_PTHREAD_H */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); curl_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_iplimit.c0000644000175000017500000002220714760713574016626 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_iplimit.c * @brief Testcase for libmicrohttpd limits per IP * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; char buf[2048]; int k; unsigned int success; unsigned int failure; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1260; if (oneone) port += 5; } /* Test only valid for HTTP/1.1 (uses persistent connections) */ if (! oneone) return 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (k = 0; k < 3; ++k) { struct CBC cbc[3]; CURL *cenv[3]; int i; success = 0; failure = 0; for (i = 0; i < 3; ++i) { CURL *c; CURLcode errornum; cenv[i] = c = curl_easy_init (); cbc[i].buf = buf; cbc[i].size = 2048; cbc[i].pos = 0; curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); errornum = curl_easy_perform (c); if (CURLE_OK == errornum) success++; else failure++; } /* Cleanup the environments */ for (i = 0; i < 3; ++i) curl_easy_cleanup (cenv[i]); if ( (2 != success) || (1 != failure) ) { fprintf (stderr, "Unexpected number of success (%u) or failure (%u)\n", success, failure); MHD_stop_daemon (d); return 32; } (void) sleep (2); for (i = 0; i < 2; ++i) { if (cbc[i].pos != strlen ("/hello_world")) { MHD_stop_daemon (d); return 64; } if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world"))) { MHD_stop_daemon (d); return 128; } } } MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; char buf[2048]; int k; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1261; if (oneone) port += 5; } /* Test only valid for HTTP/1.1 (uses persistent connections) */ if (! oneone) return 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (k = 0; k < 3; ++k) { struct CBC cbc[3]; CURL *cenv[3]; int i; for (i = 0; i < 3; ++i) { CURL *c; CURLcode errornum; cenv[i] = c = curl_easy_init (); cbc[i].buf = buf; cbc[i].size = 2048; cbc[i].pos = 0; curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); errornum = curl_easy_perform (c); if ( ( (CURLE_OK != errornum) && (i < 2) ) || ( (CURLE_OK == errornum) && (i == 2) ) ) { int j; /* First 2 should succeed */ if (i < 2) fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); /* Last request should have failed */ else fprintf (stderr, "No error on IP address over limit\n"); for (j = 0; j < i; ++j) curl_easy_cleanup (cenv[j]); MHD_stop_daemon (d); return 32; } } /* Cleanup the environments */ for (i = 0; i < 3; ++i) curl_easy_cleanup (cenv[i]); (void) sleep (2); for (i = 0; i < 2; ++i) { if (cbc[i].pos != strlen ("/hello_world")) { MHD_stop_daemon (d); return 64; } if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world"))) { MHD_stop_daemon (d); return 128; } } } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount |= testMultithreadedGet (); errorCount |= testMultithreadedPoolGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_post_loop.c0000644000175000017500000004520114760713574017174 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_post_loop.c * @brief Testcase for libmicrohttpd POST operations using URL-encoding * @author Christian Grothoff (inspired by bug report #1296) * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define POST_DATA \ "\n\n1\n\n" #ifndef __APPLE__ #define LOOPCOUNT 1000 #else /* __APPLE__ */ /* FIXME: macOS may fail in this test with "unable to connect". Investigate deeper? */ #define LOOPCOUNT 200 #endif /* __APPLE__ */ static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { printf ("METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } if ((*req_cls != NULL) && (0 == *upload_data_size)) { if (*req_cls != &marker) abort (); response = MHD_create_response_from_buffer_static (2, "OK"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); *req_cls = NULL; return ret; } if (strlen (POST_DATA) != *upload_data_size) return MHD_YES; *upload_data_size = 0; *req_cls = ▮ return MHD_YES; } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1350; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 4; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1351; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 64; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1352; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 64; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; int i; uint64_t timeout64; long ctimeout; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1353; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } multi = curl_multi_init (); if (multi == NULL) { MHD_stop_daemon (d); return 512; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform (multi, &running)) ; mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } if (MHD_NO == MHD_get_timeout64 (d, &timeout64)) timeout64 = 100; /* 100ms == INFTY -- CURL bug... */ if ((CURLM_OK == curl_multi_timeout (multi, &ctimeout)) && (ctimeout >= 0) && ((uint64_t) ctimeout < timeout64)) timeout64 = (uint64_t) ctimeout; if (0 == running) timeout64 = 0; /* terminate quickly... */ #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (timeout64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (timeout64 / 1000); #endif /* Native W32 */ tv.tv_usec = (long) (1000 * (timeout64 % 1000)); if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform (multi, &running)) ; if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } break; } MHD_run (d); } if (NULL != c) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); } if ((buf[0] != 'O') || (buf[1] != 'K')) { curl_multi_cleanup (multi); MHD_stop_daemon (d); return 8192; } } curl_multi_cleanup (multi); MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } /** * Time this round was started. */ static unsigned long long start_time; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { start_time = now (); errorCount += testInternalPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "internal select", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); start_time = now (); errorCount += testMultithreadedPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "multithreaded post", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); start_time = now (); errorCount += testMultithreadedPoolPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "thread with pool", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); } start_time = now (); errorCount += testExternalPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "external select", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_put.c0000644000175000017500000003721114760713574015770 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_put.c * @brief Testcase for libmicrohttpd PUT operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PUT", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1450; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1451; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1452; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1453; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_urlparse.c0000644000175000017500000001363514760713574017021 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_urlparse.c * @brief Testcase for libmicrohttpd url parsing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include "mhd_has_in_name.h" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif static int oneone; static int matches; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result test_values (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { (void) cls; (void) kind; /* Unused. Silent compiler warning. */ if ( (0 == strcmp (key, "a")) && (0 == strcmp (value, "b")) ) matches += 1; if ( (0 == strcmp (key, "c")) && (0 == strcmp (value, "")) ) matches += 2; if ( (0 == strcmp (key, "d")) && (NULL == value) ) matches += 4; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } MHD_get_connection_values (connection, MHD_GET_ARGUMENT_KIND, &test_values, NULL); *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1510; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world?a=b&c=&d"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; if (matches != 7) return 16; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testInternalGet (0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_get_chunked.c0000644000175000017500000005305314760713574017442 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_chunked.c * @brief Testcase for libmicrohttpd GET operations with chunked content encoding * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define HDR_CHUNKED_ENCODING MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked" #define RESP_FOOTER_NAME "Footer" #define RESP_FOOTER_VALUE "working" #define RESP_FOOTER RESP_FOOTER_NAME ": " RESP_FOOTER_VALUE #define RESP_BLOCK_SIZE 128 #define RESP_BLOCK_QUANTIY 10 #define RESP_SIZE (RESP_BLOCK_SIZE * RESP_BLOCK_QUANTIY) /** * Use "Connection: close" header? */ static int conn_close; /** * Use static string response instead of callback-generated? */ static int resp_string; /** * Use response with known size? */ static int resp_sized; /** * Use empty (zero-sized) response? */ static int resp_empty; /** * Force chunked response by response header? */ static int chunked_forced; /** * MHD port used for testing */ static uint16_t port_global; struct headers_check_result { int found_chunked; int found_footer; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((data_size == strlen (HDR_CHUNKED_ENCODING) + 2) && (0 == memcmp (buffer, HDR_CHUNKED_ENCODING "\r\n", data_size))) check_res->found_chunked = 1; if ((data_size == strlen (RESP_FOOTER) + 2) && (0 == memcmp (buffer, RESP_FOOTER "\r\n", data_size))) check_res->found_footer = 1; return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * MHD content reader callback that returns data in chunks. */ static ssize_t crc (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response **responseptr = cls; if (resp_empty || (pos == RESP_SIZE - RESP_BLOCK_SIZE)) { /* Add footer with the last block */ if (MHD_YES != MHD_add_response_footer (*responseptr, RESP_FOOTER_NAME, RESP_FOOTER_VALUE)) abort (); } if (resp_empty || (pos == RESP_SIZE)) return MHD_CONTENT_READER_END_OF_STREAM; if (max < RESP_BLOCK_SIZE) abort (); /* should not happen in this testcase... */ memset (buf, 'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE), RESP_BLOCK_SIZE); return RESP_BLOCK_SIZE; } /** * Dummy function that frees the "responseptr". */ static void crcf (void *ptr) { free (ptr); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } if (! resp_string) { struct MHD_Response **responseptr; responseptr = malloc (sizeof (struct MHD_Response *)); if (NULL == responseptr) _exit (99); response = MHD_create_response_from_callback (resp_sized ? RESP_SIZE : MHD_SIZE_UNKNOWN, 1024, &crc, responseptr, &crcf); *responseptr = response; } else { if (! resp_empty) { size_t pos; static const size_t resp_size = RESP_SIZE; char *buf = malloc (resp_size); if (NULL == buf) _exit (99); for (pos = 0; pos < resp_size; pos += RESP_BLOCK_SIZE) memset (buf + pos, 'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE), RESP_BLOCK_SIZE); response = MHD_create_response_from_buffer_copy (resp_size, buf); free (buf); } else response = MHD_create_response_empty (MHD_RF_NONE); } if (NULL == response) abort (); if (chunked_forced) { if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) abort (); } if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRAILER, RESP_FOOTER_NAME)) abort (); if (resp_string || (resp_sized && resp_empty)) { /* There is no chance to add footer later */ if (MHD_YES != MHD_add_response_footer (response, RESP_FOOTER_NAME, RESP_FOOTER_VALUE)) abort (); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int validate (struct CBC cbc, unsigned int ebase) { int i; char buf[RESP_BLOCK_SIZE]; if (resp_empty) { if (0 != cbc.pos) { fprintf (stderr, "Got %u bytes instead of zero!\n", (unsigned int) cbc.pos); return 1; } return 0; } if (cbc.pos != RESP_SIZE) { fprintf (stderr, "Got %u bytes instead of 1280!\n", (unsigned int) cbc.pos); return ebase; } for (i = 0; i < RESP_BLOCK_QUANTIY; i++) { memset (buf, 'A' + i, RESP_BLOCK_SIZE); if (0 != memcmp (buf, &cbc.buf[i * RESP_BLOCK_SIZE], RESP_BLOCK_SIZE)) { fprintf (stderr, "Got `%.*s'\nWant `%.*s'\n", RESP_BLOCK_SIZE, &cbc.buf[i * RESP_BLOCK_SIZE], RESP_BLOCK_SIZE, buf); return ebase * 2; } } return 0; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } hdr_check.found_chunked = 0; hdr_check.found_footer = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 4); } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 64); } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 64); } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); h_list = NULL; c = NULL; multi = NULL; } MHD_run (d); } MHD_stop_daemon (d); if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } curl_slist_free_all (h_list); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 8192); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; conn_close = has_in_name (argv[0], "_close"); resp_string = has_in_name (argv[0], "_string"); resp_sized = has_in_name (argv[0], "_sized"); resp_empty = has_in_name (argv[0], "_empty"); chunked_forced = has_in_name (argv[0], "_forced"); if (resp_string) resp_sized = ! 0; if (resp_sized) chunked_forced = ! 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port_global = 0; else { port_global = 4100; if (conn_close) port_global += 1 << 0; if (resp_string) port_global += 1 << 1; if (resp_sized) port_global += 1 << 2; if (resp_empty) port_global += 1 << 3; if (chunked_forced) port_global += 1 << 4; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/mhd_has_in_name.h0000644000175000017500000000410714760713577017220 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file testcurl/mhd_has_in_name.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ static int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } libmicrohttpd-1.0.2/src/testcurl/test_tricky.c0000644000175000017500000011047215035214304016445 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2025 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_toolarge.c * @brief Testcase for handling of untypical data. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/a" #define EXPECTED_URI_BASE_PATH_TRICKY "/one\rtwo" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define HEADER1_NAME "First" #define HEADER1_VALUE "1st" #define HEADER1 HEADER1_NAME ": " HEADER1_VALUE #define HEADER2_NAME "Second" #define HEADER2CR_VALUE "2\rnd" #define HEADER2CR HEADER2_NAME ": " HEADER2CR_VALUE /* Use headers when it would be properly supported by MHD #define HEADER3CR_NAME "Thi\rrd" #define HEADER3CR_VALUE "3r\rd" #define HEADER3CR HEADER3CR_NAME ": " HEADER3CR_VALUE */ #define HEADER4_NAME "Normal" #define HEADER4_VALUE "it's fine" #define HEADER4 HEADER4_NAME ": " HEADER4_VALUE /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int response_timeout_val = TIMEOUTS_VAL; static int tricky_url; /**< Tricky request URL */ static int tricky_header2; /**< Tricky request header2 */ /* Current test parameters */ /* * Moved to local variables * */ /* Static helper variables */ /* * None for this test * */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { int dummy; /* no checks in this test */ }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; /* no checks in this test */ (void) check_res; (void) buffer; return data_size; } struct lcurl_data_cb_param { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct lcurl_data_cb_param *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct check_uri_cls { const char *volatile uri; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; (void) con; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: '%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } struct mhd_header_checker_param { int found_header1; int found_header2; int found_header4; }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((strlen (HEADER1_NAME) == key_size) && (0 == memcmp (key, HEADER1_NAME, key_size))) { if ((strlen (HEADER1_VALUE) == value_size) && (0 == memcmp (value, HEADER1_VALUE, value_size))) param->found_header1 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER1_VALUE); } else if ((strlen (HEADER2_NAME) == key_size) && (0 == memcmp (key, HEADER2_NAME, key_size))) { if ((strlen (HEADER2CR_VALUE) == value_size) && (0 == memcmp (value, HEADER2CR_VALUE, value_size))) param->found_header2 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER2CR_VALUE); } else if ((strlen (HEADER4_NAME) == key_size) && (0 == memcmp (key, HEADER4_NAME, key_size))) { if ((strlen (HEADER4_VALUE) == value_size) && (0 == memcmp (value, HEADER4_VALUE, value_size))) param->found_header4 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER4_VALUE); } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; struct mhd_header_checker_param header_check_param; const char *volatile rq_method; const char *volatile rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, ¶m->header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); response = MHD_create_response_from_buffer_copy (param->rp_data_size, (const void *) param->rp_data); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; #if CURL_AT_LEAST_VERSION (7, 62, 0) CURLU *url; #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ #if CURL_AT_LEAST_VERSION (7, 55, 0) /* A string used as the request target directly, without modifications */ const char *queryTarget; #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ /* Custom query method, NULL for default */ const char *method; /* Destination port for CURL query */ uint16_t queryPort; /* List of additional request headers */ struct curl_slist *headers; /* CURL query result error flag */ volatile unsigned int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; static CURL * curlEasyInitForTest (struct curlQueryParams *p, struct lcurl_data_cb_param *dcbp, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); #if CURL_AT_LEAST_VERSION (7, 62, 0) if (NULL != p->url) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CURLU, p->url)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); } else /* combined with the next 'if()' */ #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, p->queryPath)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) p->queryPort)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || #if CURL_AT_LEAST_VERSION (7, 42, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PATH_AS_IS, (long) 1)) || #endif /* CURL_AT_LEAST_VERSION(7, 42, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, p->method)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, p->headers)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); #if CURL_AT_LEAST_VERSION (7, 55, 0) if (NULL != p->queryTarget) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_REQUEST_TARGET, p->queryTarget)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); } #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /* Returns zero for successful response and non-zero for failed response */ static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, struct headers_check_result *hdr_res, const char *expected_data, size_t expected_data_size) { const union MHD_DaemonInfo *dinfo; CURL *c; struct lcurl_data_cb_param dcbp; CURLcode errornum; int use_external_poll; long resp_code; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath #if CURL_AT_LEAST_VERSION (7, 62, 0) && NULL == p->url #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ ) abort (); if (0 == p->queryPort) abort (); /* Test must not fail due to test's internal buffer shortage */ dcbp.size = expected_data_size * 2 + 1; dcbp.buf = malloc (dcbp.size); if (NULL == dcbp.buf) externalErrorExit (); dcbp.pos = 0; memset (hdr_res, 0, sizeof(*hdr_res)); c = curlEasyInitForTest (p, &dcbp, hdr_res); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code)) libcurlErrorExitDesc ("curl_easy_getinfo() failed"); p->responseCode = (int) resp_code; if ((CURLE_OK == errornum) && (200 != resp_code)) { fprintf (stderr, "Got reply with unexpected status code: %d\n", p->responseCode); mhdErrorExit (); } if (CURLE_OK != errornum) { if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum) && (CURLE_HTTP_RETURNED_ERROR != errornum)) { if (CURLE_OPERATION_TIMEDOUT == errornum) mhdErrorExitDesc ("Request was aborted due to timeout"); fprintf (stderr, "libcurl returned unexpected error: %s\n", curl_easy_strerror (errornum)); mhdErrorExitDesc ("Request failed due to unexpected error"); } p->queryError = 1; if ((0 != resp_code) && ((499 < resp_code) || (400 > resp_code))) /* TODO: add all expected error codes */ { fprintf (stderr, "Got reply with unexpected status code: %ld\n", resp_code); mhdErrorExit (); } } else { if (dcbp.pos != expected_data_size) mhdErrorExit ("libcurl reports wrong size of MHD reply body data"); else if (0 != memcmp (expected_data, dcbp.buf, expected_data_size)) mhdErrorExit ("libcurl reports wrong MHD reply body data"); else p->queryError = 0; } curl_easy_cleanup (c); free (dcbp.buf); return p->queryError; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ struct headers_check_result rp_headers_check; struct curl_slist *curl_headers; curl_headers = NULL; /* Common parameters, to be individually overridden by specific test cases */ qParam.queryPort = d_port; qParam.method = NULL; /* Use libcurl default: GET */ qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH; #if CURL_AT_LEAST_VERSION (7, 55, 0) qParam.queryTarget = NULL; #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ #if CURL_AT_LEAST_VERSION (7, 62, 0) qParam.url = NULL; #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ qParam.headers = NULL; /* No additional headers */ uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = "GET"; /* Default expected method */ ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; curl_headers = curl_slist_append (curl_headers, HEADER1); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER4); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (tricky_url) { #if CURL_AT_LEAST_VERSION (7, 55, 0) #if CURL_AT_LEAST_VERSION (7, 62, 0) unsigned int urlu_flags = CURLU_PATH_AS_IS; CURLU *url; url = curl_url (); if (NULL == url) externalErrorExit (); qParam.url = url; #ifdef CURLU_ALLOW_SPACE urlu_flags |= CURLU_ALLOW_SPACE; #endif /* CURLU_ALLOW_SPACE */ if ((CURLUE_OK != curl_url_set (qParam.url, CURLUPART_SCHEME, "http", 0)) || (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_HOST, URL_HOST, urlu_flags)) || (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_PATH, EXPECTED_URI_BASE_PATH_TRICKY, urlu_flags))) libcurlErrorExit (); #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ qParam.queryTarget = EXPECTED_URI_BASE_PATH_TRICKY; uri_cb_param->uri = EXPECTED_URI_BASE_PATH_TRICKY; ahc_param->rq_url = EXPECTED_URI_BASE_PATH_TRICKY; if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { /* TODO: Allow fail only if relevant MHD mode set */ if (0 == qParam.responseCode) { fprintf (stderr, "Request failed without any valid response.\n"); ret = 1; } else { if (verbose) printf ("Request failed with %d response code.\n", qParam.responseCode); (void) qParam.responseCode; /* TODO: check for the right response code */ ret = 0; } } else { if (200 != qParam.responseCode) { fprintf (stderr, "Request succeed with wrong response code: %d.\n", qParam.responseCode); ret = 1; } else { ret = 0; if (verbose) printf ("Request succeed.\n"); } if (! ahc_param->header_check_param.found_header1) mhdErrorExitDesc ("Required header1 was not detected in request"); if (! ahc_param->header_check_param.found_header4) mhdErrorExitDesc ("Required header4 was not detected in request"); } #if CURL_AT_LEAST_VERSION (7, 62, 0) curl_url_cleanup (url); #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ #else fprintf (stderr, "This test requires libcurl version 7.55.0 or newer.\n"); abort (); #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ } else if (tricky_header2) { /* Reset libcurl headers */ qParam.headers = NULL; curl_slist_free_all (curl_headers); curl_headers = NULL; /* Set special libcurl headers */ curl_headers = curl_slist_append (curl_headers, HEADER1); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER2CR); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER4); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { /* TODO: Allow fail only if relevant MHD mode set */ if (0 == qParam.responseCode) { fprintf (stderr, "Request failed without any valid response.\n"); ret = 1; } else { if (verbose) printf ("Request failed with %d response code.\n", qParam.responseCode); (void) qParam.responseCode; /* TODO: check for the right response code */ ret = 0; } } else { if (200 != qParam.responseCode) { fprintf (stderr, "Request succeed with wrong response code: %d.\n", qParam.responseCode); ret = 1; } else { ret = 0; if (verbose) printf ("Request succeed.\n"); } if (! ahc_param->header_check_param.found_header1) mhdErrorExitDesc ("Required header1 was not detected in request"); if (! ahc_param->header_check_param.found_header2) mhdErrorExitDesc ("Required header2 was not detected in request"); if (! ahc_param->header_check_param.found_header4) mhdErrorExitDesc ("Required header4 was not detected in request"); } } else externalErrorExitDesc ("No valid test test was selected"); MHD_stop_daemon (d); curl_slist_free_all (curl_headers); free (uri_cb_param); free (ahc_param); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param)) abort (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4150; if (tricky_url) *pport += 1; if (tricky_header2) *pport += 2; if (! oneone) *pport += 16; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static void check_test_can_be_used (void) { #if ! CURL_AT_LEAST_VERSION (7, 55, 0) if (tricky_url) { fprintf (stderr, "This test requires libcurl version 7.55.0 or newer.\n"); exit (77); } #endif /* ! CURL_AT_LEAST_VERSION(7, 55, 0) */ return; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); tricky_url = has_in_name (argv[0], "_url") ? 1 : 0; tricky_header2 = has_in_name (argv[0], "_header2") ? 1 : 0; if (1 != tricky_url + tricky_header2) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); check_test_can_be_used (); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/https/0000755000175000017500000000000015035216652015162 500000000000000libmicrohttpd-1.0.2/src/testcurl/https/test_https_get_select.c0000644000175000017500000001764214760713574021670 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_select.c * @brief Testcase for libmicrohttpd HTTPS GET operations using external select * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" static int oneone; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testExternalGet (unsigned int flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3030; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS | flags, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); /* TLS options */ curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 != maxposixs) { if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) abort (); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws. fd_count) || (0 != es.fd_count) ) abort (); Sleep (1000); #endif } } else (void) sleep (1); curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ oneone = 1; if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } #ifdef EPOLL_SUPPORT errorCount += testExternalGet (MHD_USE_EPOLL); #endif if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) errorCount += testExternalGet (MHD_NO_FLAG); errorCount += testExternalGet (MHD_USE_NO_THREAD_SAFETY); curl_global_cleanup (); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_https_time_out.c0000644000175000017500000001557014760713574021375 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_time_out.c * @brief: daemon TLS timeout test * * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "tls_test_common.h" #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #include "mhd_sockets.h" /* only macros used */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "tls_test_keys.h" static const unsigned int timeout_val = 2; static volatile unsigned int num_connects = 0; static volatile unsigned int num_disconnects = 0; /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else sleep ((ms + 999) / 1000); #endif } static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { if (NULL == socket_context) abort (); if (NULL == c) abort (); if (NULL != cls) abort (); if (MHD_CONNECTION_NOTIFY_STARTED == toe) { num_connects++; #ifdef _DEBUG fprintf (stderr, "MHD: Connection has started.\n"); #endif /* _DEBUG */ } else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) { num_disconnects++; #ifdef _DEBUG fprintf (stderr, "MHD: Connection has closed.\n"); #endif /* _DEBUG */ } else abort (); } static unsigned int test_tls_session_time_out (gnutls_session_t session, uint16_t port) { int ret; MHD_socket sd; struct sockaddr_in sa; sd = socket (AF_INET, SOCK_STREAM, 0); if (sd == MHD_INVALID_SOCKET) { fprintf (stderr, "Failed to create socket: %s\n", strerror (errno)); return 2; } memset (&sa, '\0', sizeof (struct sockaddr_in)); sa.sin_family = AF_INET; sa.sin_port = htons (port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); ret = connect (sd, (struct sockaddr *) &sa, sizeof (struct sockaddr_in)); if (ret < 0) { fprintf (stderr, "Error: %s\n", MHD_E_FAILED_TO_CONNECT); MHD_socket_close_chk_ (sd); return 2; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (session, (int) (sd)); #else /* GnuTLS before 3.1.9 or Win64 */ gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) (intptr_t) (sd)); #endif /* GnuTLS before 3.1.9 or Win64 */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "Handshake failed\n"); MHD_socket_close_chk_ (sd); return 2; } _MHD_sleep (timeout_val * 1000 + 1700); if (0 == num_connects) { fprintf (stderr, "MHD has not detected any connection attempt.\n"); MHD_socket_close_chk_ (sd); return 4; } /* check that server has closed the connection */ if (0 == num_disconnects) { fprintf (stderr, "MHD has not detected any disconnections.\n"); MHD_socket_close_chk_ (sd); return 1; } MHD_socket_close_chk_ (sd); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; struct MHD_Daemon *d; gnutls_session_t session; gnutls_certificate_credentials_t xcred; uint16_t port; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3070; #ifdef MHD_SEND_SPIPE_SUPPRESS_NEEDED #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) { fprintf (stderr, "Error suppressing SIGPIPE signal.\n"); exit (99); } #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (GNUTLS_E_SUCCESS != gnutls_global_init ()) { fprintf (stderr, "Cannot initialize GnuTLS.\n"); exit (99); } gnutls_global_set_log_level (11); d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_dummy_ahc, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout_val, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, MHD_E_SERVER_INIT); return -1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 99; } port = dinfo->port; } if (0 != setup_session (&session, &xcred)) { fprintf (stderr, "failed to setup session\n"); return 1; } errorCount += test_tls_session_time_out (session, port); teardown_session (session, xcred); print_test_result (errorCount, argv[0]); MHD_stop_daemon (d); gnutls_global_deinit (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/mhdhost2.crt0000644000175000017500000000346614674632555017371 00000000000000-----BEGIN CERTIFICATE----- MIIFJjCCAw6gAwIBAgIBBjANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4 NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o ZGhvc3QyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy2v1c39RQPgG EqhYisiQX5QDTJFCr93B/KC96AqxXfUqxYHQZHHByeh2yHX5XeY+cwiza9Pb8kB5 Wyu5IV7pHYbLXetUQ7Ha8oCXcXZBihzMGjdTQApBvKES2rotkgxIArzFRk/KnO3D 2r87E2/fHqlHjg0Y8d58i846m7GSFpH2uAYogm2Zhi2ojE4O/qfaO6cSTdjUhDbM iDkQlf/fkq9o3ZeGzKXdzLC5PeIJ/7HbEcBJ0e6lyAFbYZtpTAtQ6/tuqAZTs3tM G5Yq3cAZY7x4vGECZaAWZAlgstBpCYd8b/dlXa8qvx4JuMF4q+7vVbgwHVoXsAzm ZAxSNy+dmQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QyMB0GA1Ud DgQWBBSB0kA6mqq1/wMzKke35+L6aZym9zAnBglghkgBhvhCAQ0EGhYYVGVzdCBs aWJtaWNyb2h0dHBkIGhvc3QyMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAhEeSsKYb KWVhC3bVxXX4EynaHVWwrQaqNMtogt2akKBfZRzM6CHVvts8IrvcMdS4ZvXB2kL8 wDsYpVsNVgLLuSKXH2xJPZmYrGsUu++UcR4umvuV1kwFcA/Dc5XkW1EMcMvSPDs2 /gJFRCpx3UAs2/KCL2KASHGiOcNSf8aRLxI6KqWqQLxsZdK02HUNodqiG2UXIaHg shD7rAMSDN4CdG4cdSX3l45aL+BoYcEKi5XUoJMRjNrAGKMWUku089hr1gI617Jx gHKZxvSizGxCHhMkAPTT+9UyNFzd+3dS6cHx8oTFpnamNgMin3C88GCmu5YN6gCi af3imb8OaHFJ0k9M9acM++5sRfvRgZ/tQWnPdyg5TlLwwF14yLbz6e/DbxlmP7PG 3W3FbVST/creb2KTtwWFu187uKl4v1Xe5DC0I2gcOzq2g0GHbu8WjuD45Os/lc4v cqGctYRMUfqshmsK9PQCZmPcC5nqXf6iO8L1P9Gi0VDwT/WeHUvi87UVYsUgVuVt 0RxCE5Nqad8S7ziQj9Aa3xspPf7CKw6Obbp/UNui/YwaDufJho7qsBpp1lMnG5f4 qA8+yKUVADTnV5tJqgcDiRyBxOzb2CaGezTqNshUkVIpkHZsCpSdu9QrEOIzcaaA WXmQOPOpxW5QVf22mPJh/GZaqZ3/ZMmFabI= -----END CERTIFICATE----- libmicrohttpd-1.0.2/src/testcurl/https/mhdhost1.crt0000644000175000017500000000346614674632555017370 00000000000000-----BEGIN CERTIFICATE----- MIIFJjCCAw6gAwIBAgIBBTANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4 NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o ZGhvc3QxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxb5LkwTfvNtW eFSYAPoEzqwVARWxDDR2PfQmmBtrHhMNEQyUCTg+Na00hEQbcZbz7fgS0FOY1hjy MFJamNGP031HvMS7zHNQJ4HbEz0d1EuePgjEvWaFMFncTKGn07Cn9e3Rcv2ihJ/I I8wf3ph/k/UTOv62YhIs2fMQM5LD6oX9ulKJhAaOvFT6hyrB1xe3nVhPT0PsrUXl ky253k7XXEAIWO6dLZnK377UiRDJInFS9FN/hojFb+8gcByo/n39LHMBtp5WGM5+ xGwEHyYkwtnaM8IEKofbUNERQT3cgPv4zN7ny3LwljR2A1c5gHXmKO7G245tbfqb VtOh3+1bJQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QxMB0GA1Ud DgQWBBTTxzQ/fcuT83JlCzPx8qJzuHCG4jAnBglghkgBhvhCAQ0EGhYYVGVzdCBs aWJtaWNyb2h0dHBkIGhvc3QxMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAMdHjWHxt 51LH3V8Um3djUh+QYVnYhxFVX4CIXMq2DAg7iYw6tg2S1SOm3R+qEB/rAHxRw/cd nekjx0zm2rAnn4SsIQg5rXzniM4dJ2UQJrn7m88fb/czjXCrvf6hGIXCSAw/YyU0 IkxXlOYv1mYNZBuVvFREUbqqK2Fn+ooIi816Q2UCQFMd+QI8+mn8eqK8XeJElKkt SR0WCLW7UkwYxOk73FCdrr1TlX9hAF76gTAK71OJN3F35hzg+pTAEe3nwFMZbG/k xHmVob51L+Op4Y15j1HoJxW0Ox+PuxVcp9EpC7Qb8UmtExAsYOuN2PP8hU+pmtE4 iYpCDckx6kT66ssjndaKziRmoxX/czvKCAwVDder6Ofl4SwGUEpE+0oO2ux6iNrl iKxRCvyBqErFlzlEj7oO3agqe83jtTH8bXzOCtx36lNVjCuADYI4o7r5NVHaGIx6 1q5BiZ5pj22EYgBZbRAgE1ZPxVBIZJKoHewmQqpcR5WsSeBIf8XDuytnadhv8NDN tpLMDry8KkUh7rtjrQIGb66BqCt0n1tz1/6nLlL9OF5kUt4902wCtN3SbotssfV3 NCX9X4udquRdcFwNLCSfZ505FqhYbeSLraDHJ46/96V//Vx4oAnULdcCm4QgGQmP EGEJDJkaCKKTGMHAvZAtgRchc/RTf59jhoc= -----END CERTIFICATE----- libmicrohttpd-1.0.2/src/testcurl/https/test_https_get_parallel.c0000644000175000017500000001415214760713574022176 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_parallel.c * @brief Testcase for libmicrohttpd HTTPS GET operations with single-threaded * MHD daemon and several clients working in parallel * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 4 #endif /** * used when spawning multiple threads executing curl server requests * */ static void * https_transfer_thread_adapter (void *args) { static int nonnull; struct https_test_data *cargs = args; unsigned int ret; ret = test_https_transfer (NULL, cargs->port, cargs->cipher_suite, cargs->proto_version); if (ret == 0) return NULL; return &nonnull; } /** * Test non-parallel requests. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_single_client (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { void *client_thread_ret; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ client_thread_ret = https_transfer_thread_adapter (&client_args); if (client_thread_ret != NULL) return 1; return 0; } /** * Test parallel request handling. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { int i; int client_count = (MHD_CPU_COUNT - 1); void *client_thread_ret; pthread_t client_arr[client_count]; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ for (i = 0; i < client_count; ++i) { if (pthread_create (&client_arr[i], NULL, &https_transfer_thread_adapter, &client_args) != 0) { fprintf (stderr, "Error: failed to spawn test client threads.\n"); return 1; } } /* check all client requests fulfilled correctly */ for (i = 0; i < client_count; ++i) { if ((pthread_join (client_arr[i], &client_thread_ret) != 0) || (client_thread_ret != NULL)) return 1; } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port; unsigned int iseed; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3020; /* initialize random seed used by curl clients */ iseed = (unsigned int) time (NULL); srand (iseed); if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); return 77; } #ifdef EPOLL_SUPPORT errorCount += test_wrap ("single threaded daemon, single client, epoll", &test_single_client, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_EPOLL, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #endif errorCount += test_wrap ("single threaded daemon, single client", &test_single_client, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #ifdef EPOLL_SUPPORT errorCount += test_wrap ("single threaded daemon, parallel clients, epoll", &test_parallel_clients, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_EPOLL, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #endif errorCount += test_wrap ("single threaded daemon, parallel clients", &test_parallel_clients, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); curl_global_cleanup (); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_https_get_iovec.c0000644000175000017500000002625414760713574021515 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2021 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_iovec.c * @brief Testcase for libmicrohttpd HTTPS GET operations using an iovec * @author Sagie Amir * @author Karlson2k (Evgeny Grin) * @author Lawrence Sebald */ /* * This testcase is derived from the test_https_get.c testcase. This version * adds the usage of a scatter/gather array for storing the response data. */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" static uint16_t global_port; /* Use large enough pieces (>16KB) to test partially consumed * data as TLS doesn't take more than 16KB by a single call. */ #define TESTSTR_IOVLEN 20480 #define TESTSTR_IOVCNT 30 #define TESTSTR_SIZE (TESTSTR_IOVCNT * TESTSTR_IOVLEN) static void iov_free_callback (void *cls) { free (cls); } static int check_read_data (const void *ptr, size_t len) { const int *buf; size_t i; if (len % sizeof(int)) return -1; buf = (const int *) ptr; for (i = 0; i < len / sizeof(int); ++i) { if (buf[i] != (int) i) return -1; } return 0; } static enum MHD_Result iovec_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; int *data; struct MHD_IoVec iov[TESTSTR_IOVCNT]; int i; int j; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* Create some test data. */ if (NULL == (data = malloc (TESTSTR_SIZE))) return MHD_NO; for (j = 0; j < TESTSTR_IOVCNT; ++j) { int *chunk; /* Assign chunks of memory area in the reverse order * to make non-continous set of data therefore * possible buffer overruns could be detected */ chunk = data + (((TESTSTR_IOVCNT - 1) - (unsigned int) j) * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int))); iov[j].iov_base = chunk; iov[j].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT; for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i) chunk[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int))); } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iov_free_callback, data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int test_iovec_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version) { size_t len; unsigned int ret = 0; struct CBC cbc; char url[255]; (void) cls; /* Unused. Silent compiler warning. */ len = TESTSTR_SIZE; if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return 1; } cbc.size = len; cbc.pos = 0; if (gen_test_uri (url, sizeof (url), port)) { ret = 1; goto cleanup; } if (CURLE_OK != send_curl_req (url, &cbc, cipher_suite, proto_version)) { ret = 1; goto cleanup; } if ((cbc.pos != TESTSTR_SIZE) || (0 != check_read_data (cbc.buf, cbc.pos))) { fprintf (stderr, "Error: local file & received file differ.\n"); ret = 1; } cleanup: free (cbc.buf); return ret; } /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (FILE *test_fd, const char *cipher_suite, int proto_version) { unsigned int ret; struct MHD_Daemon *d; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3045; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &iovec_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_iovec_transfer (test_fd, port, cipher_suite, proto_version); MHD_stop_daemon (d); return ret; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_IoVec iov; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; iov.iov_base = NULL; iov.iov_len = 0; response = MHD_create_response_from_iovec (&iov, 1, NULL, NULL); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silence compiler warning. */ #ifdef _DEBUG if ((CURLINFO_TEXT == type) || (CURLINFO_HEADER_IN == type) || (CURLINFO_HEADER_OUT == type)) fprintf (stderr, "%.*s", (int) size, data); #endif /* _DEBUG */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (unsigned int poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag | MHD_USE_TLS, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT); errorCount += testEmptyGet (0); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_empty_response.c0000644000175000017500000001576114760713574021404 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_empty_response.c * @brief Testcase for libmicrohttpd HTTPS GET operations with empty reply * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" static int oneone; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalSelectGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3000; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS | MHD_USE_INTERNAL_POLLING_THREAD, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); /* TLS options */ curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 != maxposixs) { if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) abort (); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws. fd_count) || (0 != es.fd_count) ) abort (); Sleep (1000); #endif } } else (void) sleep (1); curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != 0) return 8192; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ oneone = 1; if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } if (0 != (errorCount = testInternalSelectGet ())) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/tls_test_common.c0000644000175000017500000004765614760713574020512 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2017-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file tls_test_common.c * @brief Common tls test functions * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include #include "tls_test_common.h" #include "tls_test_keys.h" /** * Map @a know_gnutls_tls_ids values to printable names. */ const char *tls_names[KNOW_TLS_IDS_COUNT] = { "Bad value", "SSL version 3", "TLS version 1.0", "TLS version 1.1", "TLS version 1.2", "TLS version 1.3" }; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings. */ const char *priorities_map[KNOW_TLS_IDS_COUNT] = { "NONE", "NORMAL:!VERS-ALL:+VERS-SSL3.0", "NORMAL:!VERS-ALL:+VERS-TLS1.0", "NORMAL:!VERS-ALL:+VERS-TLS1.1", "NORMAL:!VERS-ALL:+VERS-TLS1.2", "NORMAL:!VERS-ALL:+VERS-TLS1.3" }; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings. */ const char *priorities_append_map[KNOW_TLS_IDS_COUNT] = { "NONE", "!VERS-ALL:+VERS-SSL3.0", "!VERS-ALL:+VERS-TLS1.0", "!VERS-ALL:+VERS-TLS1.1", "!VERS-ALL:+VERS-TLS1.2", "!VERS-ALL:+VERS-TLS1.3" }; /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value. */ const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT] = { CURL_SSLVERSION_LAST, /* bad value */ CURL_SSLVERSION_SSLv3, #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_0, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_TLSv1, /* TLS 1.0 or later */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_1, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_2, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,52,0) CURL_SSLVERSION_TLSv1_3 #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ }; #if CURL_AT_LEAST_VERSION (7,54,0) /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value * for maximum supported TLS version. */ const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT] = { CURL_SSLVERSION_MAX_DEFAULT, /* bad value */ CURL_SSLVERSION_MAX_DEFAULT, /* SSLv3 */ CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_3 }; #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ /* * test HTTPS transfer */ enum test_get_result test_daemon_get (void *cls, const char *cipher_suite, int proto_version, uint16_t port, int ver_peer) { CURL *c; struct CBC cbc; CURLcode errornum; CURLcode e; char url[255]; size_t len; (void) cls; /* Unused. Silence compiler warning. */ len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return TEST_GET_HARD_ERROR; } cbc.size = len; cbc.pos = 0; /* construct url - this might use doc_path */ gen_test_uri (url, sizeof (url), port); c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_GEN_ERROR; } /* TLS options */ if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version))) || ((NULL != cipher_suite) && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite)))) || /* perform peer authentication */ /* TODO merge into send_curl_req */ (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, ver_peer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_GEN_ERROR; } if (ver_peer && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CAINFO, ca_cert_file_name)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_CA_ERROR; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free (cbc.buf); if ((CURLE_SSL_CACERT_BADFILE == errornum) #if CURL_AT_LEAST_VERSION (7,21,5) || (CURLE_NOT_BUILT_IN == errornum) #endif /* CURL_AT_LEAST_VERSION (7,21,5) */ ) return TEST_GET_CURL_CA_ERROR; if (CURLE_OUT_OF_MEMORY == errornum) return TEST_GET_HARD_ERROR; return TEST_GET_ERROR; } curl_easy_cleanup (c); if (memcmp (cbc.buf, test_data, len) != 0) { fprintf (stderr, "Error: local data & received data differ.\n"); free (cbc.buf); return TEST_GET_TRANSFER_ERROR; } free (cbc.buf); return TEST_GET_OK; } void print_test_result (unsigned int test_outcome, const char *test_name) { if (test_outcome != 0) fprintf (stderr, "running test: %s [fail: %u]\n", test_name, test_outcome); #if 0 else fprintf (stdout, "running test: %s [pass]\n", test_name); #endif } size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) { fprintf (stderr, "Server data does not fit buffer.\n"); return 0; /* overflow */ } memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * HTTP access handler call back */ enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (test_data), test_data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /* HTTP access handler call back */ enum MHD_Result http_dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return 0; } /** * send a test http request to the daemon * @param url * @param cbc - may be null * @param cipher_suite * @param proto_version * @return */ /* TODO have test wrap consider a NULL cbc */ CURLcode send_curl_req (char *url, struct CBC *cbc, const char *cipher_suite, int proto_version) { CURL *c; CURLcode errornum; CURLcode e; c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 60L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 60L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } if (cbc != NULL) { if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } } /* TLS options */ if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version))) || ((NULL != cipher_suite) && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite)))) || /* currently skip any peer authentication */ (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); return errornum; } curl_easy_cleanup (c); return CURLE_OK; } /** * compile test URI * * @param[out] uri - char buffer into which the url is compiled * @param uri_len number of bytes available in @a url * @param port port to use for the test * @return 1 on error */ unsigned int gen_test_uri (char *uri, size_t uri_len, uint16_t port) { int res; res = snprintf (uri, uri_len, "https://127.0.0.1:%u/urlpath", (unsigned int) port); if (res <= 0) return 1; if ((size_t) res >= uri_len) return 1; return 0; } /** * test HTTPS data transfer */ unsigned int test_https_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version) { size_t len; unsigned int ret = 0; struct CBC cbc; char url[255]; (void) cls; /* Unused. Silent compiler warning. */ len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return 1; } cbc.size = len; cbc.pos = 0; if (gen_test_uri (url, sizeof (url), port)) { ret = 1; goto cleanup; } if (CURLE_OK != send_curl_req (url, &cbc, cipher_suite, proto_version)) { ret = 1; goto cleanup; } /* compare test data & daemon response */ if ( (len != strlen (test_data)) || (memcmp (cbc.buf, test_data, len) != 0) ) { fprintf (stderr, "Error: original data & received data differ.\n"); ret = 1; } cleanup: free (cbc.buf); return ret; } /** * setup test case * * @param d * @param daemon_flags * @param arg_list * @return port number on success or zero on failure */ static uint16_t setup_testcase (struct MHD_Daemon **d, uint16_t port, unsigned int daemon_flags, va_list arg_list) { *d = MHD_start_daemon_va (daemon_flags, port, NULL, NULL, &http_ahc, NULL, arg_list); if (*d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 0; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (*d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (*d); return 0; } port = dinfo->port; } return port; } static void teardown_testcase (struct MHD_Daemon *d) { MHD_stop_daemon (d); } unsigned int setup_session (gnutls_session_t *session, gnutls_certificate_credentials_t *xcred) { if (GNUTLS_E_SUCCESS == gnutls_init (session, GNUTLS_CLIENT)) { if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (*session)) { if (GNUTLS_E_SUCCESS == gnutls_certificate_allocate_credentials (xcred)) { if (GNUTLS_E_SUCCESS == gnutls_credentials_set (*session, GNUTLS_CRD_CERTIFICATE, *xcred)) { return 0; } gnutls_certificate_free_credentials (*xcred); } } gnutls_deinit (*session); } return 1; } unsigned int teardown_session (gnutls_session_t session, gnutls_certificate_credentials_t xcred) { gnutls_deinit (session); gnutls_certificate_free_credentials (xcred); return 0; } /* TODO test_wrap: change sig to (setup_func, test, va_list test_arg) */ unsigned int test_wrap (const char *test_name, unsigned int (*test_function)(void *cls, uint16_t port, const char *cipher_suite, int proto_version), void *cls, uint16_t port, unsigned int daemon_flags, const char *cipher_suite, int proto_version, ...) { unsigned int ret; va_list arg_list; struct MHD_Daemon *d; (void) cls; /* Unused. Silent compiler warning. */ va_start (arg_list, proto_version); port = setup_testcase (&d, port, daemon_flags, arg_list); if (0 == port) { va_end (arg_list); fprintf (stderr, "Failed to setup testcase %s\n", test_name); return 1; } #if 0 fprintf (stdout, "running test: %s ", test_name); #endif ret = test_function (NULL, port, cipher_suite, proto_version); #if 0 if (ret == 0) { fprintf (stdout, "[pass]\n"); } else { fprintf (stdout, "[fail]\n"); } #endif teardown_testcase (d); va_end (arg_list); return ret; } static int inited_tls_is_gnutls = 0; static int inited_tls_is_openssl = 0; int curl_tls_is_gnutls (void) { const char *tlslib; if (inited_tls_is_gnutls) return 1; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "GnuTLS/", 7)) return 1; /* Multi-backends handled during initialization by setting variable */ return 0; } int curl_tls_is_openssl (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 1; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "OpenSSL/", 8)) return 1; /* Multi-backends handled during initialization by setting variable */ return 0; } int curl_tls_is_nss (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "NSS/", 4)) return 1; /* Handle multi-backends with selected backend */ if (NULL != strstr (tlslib," NSS/")) return 1; return 0; } int curl_tls_is_schannel (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if ((0 == strncmp (tlslib, "Schannel", 8)) || (0 == strncmp (tlslib, "WinSSL", 6))) return 1; /* Handle multi-backends with selected backend */ if ((NULL != strstr (tlslib," Schannel")) || (NULL != strstr (tlslib, " WinSSL"))) return 1; return 0; } int curl_tls_is_sectransport (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "SecureTransport", 15)) return 1; /* Handle multi-backends with selected backend */ if (NULL != strstr (tlslib," SecureTransport")) return 1; return 0; } int testsuite_curl_global_init (void) { CURLcode res; #if LIBCURL_VERSION_NUM >= 0x073800 if (CURLSSLSET_OK != curl_global_sslset (CURLSSLBACKEND_GNUTLS, NULL, NULL)) { CURLsslset e; e = curl_global_sslset (CURLSSLBACKEND_OPENSSL, NULL, NULL); if (CURLSSLSET_TOO_LATE == e) fprintf (stderr, "WARNING: libcurl was already initialised.\n"); else if (CURLSSLSET_OK == e) inited_tls_is_openssl = 1; } else inited_tls_is_gnutls = 1; #endif /* LIBCURL_VERSION_NUM >= 0x07380 */ res = curl_global_init (CURL_GLOBAL_ALL); if (CURLE_OK != res) { fprintf (stderr, "libcurl initialisation error: %s\n", curl_easy_strerror (res)); return 0; } return 1; } /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_https_multi_daemon.c0000644000175000017500000001250114760713574022214 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_multi_daemon.c * @brief Testcase for libmicrohttpd multiple HTTPS daemon scenario * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* * assert initiating two separate daemons and having one shut down * doesn't affect the other */ static unsigned int test_concurent_daemon_pair (void *cls, const char *cipher_suite, int proto_version) { unsigned int ret; enum test_get_result res; struct MHD_Daemon *d1; struct MHD_Daemon *d2; uint16_t port1, port2; (void) cls; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port1 = port2 = 0; else { port1 = 3050; port2 = 3051; } d1 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port1, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d1 == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port1) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d1, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "Cannot detect daemon bind port.\n"); MHD_stop_daemon (d1); return 1; } port1 = dinfo->port; } d2 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port2, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d2 == NULL) { MHD_stop_daemon (d1); fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port2) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d2, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "Cannot detect daemon bind port.\n"); MHD_stop_daemon (d1); MHD_stop_daemon (d2); return 1; } port2 = dinfo->port; } res = test_daemon_get (NULL, cipher_suite, proto_version, port1, 0); ret = (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d2); MHD_stop_daemon (d1); return 99; } res = test_daemon_get (NULL, cipher_suite, proto_version, port2, 0); ret += (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d2); MHD_stop_daemon (d1); return 99; } MHD_stop_daemon (d2); res = test_daemon_get (NULL, cipher_suite, proto_version, port1, 0); ret += (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d1); return 99; } MHD_stop_daemon (d1); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_concurent_daemon_pair (NULL, NULL, CURL_SSLVERSION_DEFAULT); print_test_result (errorCount, "concurent_daemon_pair"); curl_global_cleanup (); if (99 == errorCount) return 99; return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_https_get.c0000644000175000017500000001654414760713574020331 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get.c * @brief Testcase for libmicrohttpd HTTPS GET operations * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" static uint16_t global_port; /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (const char *cipher_suite, int proto_version) { unsigned int ret; struct MHD_Daemon *d; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3041; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_https_transfer (NULL, port, cipher_suite, proto_version); MHD_stop_daemon (d); return ret; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silence compiler warning. */ #ifdef _DEBUG if ((CURLINFO_TEXT == type) || (CURLINFO_HEADER_IN == type) || (CURLINFO_HEADER_OUT == type)) fprintf (stderr, "%.*s", (int) size, data); #endif /* _DEBUG */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (unsigned int poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag | MHD_USE_TLS, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_secure_get (NULL, CURL_SSLVERSION_DEFAULT); errorCount += testEmptyGet (0); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_tls_options.c0000644000175000017500000003403414760713574020677 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_tls_options.c * @brief Testcase for libmicrohttpd HTTPS TLS version match/mismatch * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* * HTTP access handler call back * used to query negotiated security parameters */ static enum MHD_Result simple_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { *req_cls = (void *) &simple_ahc; return MHD_YES; } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } enum check_result { CHECK_RES_OK = 0, CHECK_RES_ERR = 1, CHECK_RES_MHD_START_FAILED = 17, CHECK_RES_CURL_TLS_INIT_FAIL = 18, CHECK_RES_CURL_TLS_CONN_FAIL = 19, CHECK_RES_HARD_ERROR = 99 }; static enum check_result check_tls_match_inner (enum know_gnutls_tls_id tls_ver_mhd, enum know_gnutls_tls_id tls_ver_libcurl, uint16_t *pport, struct MHD_Daemon **d_ptr, struct CBC *pcbc, CURL **c_ptr) { CURLcode errornum; char url[256]; int libcurl_tls_set; CURL *c; struct MHD_Daemon *d; /* setup test */ d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &simple_ahc, NULL, MHD_OPTION_HTTPS_PRIORITIES, priorities_map[tls_ver_mhd], MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); fflush (stderr); fflush (stdout); *d_ptr = d; if (d == NULL) { fprintf (stderr, "MHD_start_daemon() with %s failed.\n", tls_names[tls_ver_mhd]); return CHECK_RES_MHD_START_FAILED; } if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); return CHECK_RES_ERR; } *pport = dinfo->port; /* Use the same port for rest of the checks */ } if (0 != gen_test_uri (url, sizeof (url), *pport)) { fprintf (stderr, "failed to generate URI.\n"); return CHECK_RES_CURL_TLS_INIT_FAIL; } c = curl_easy_init (); fflush (stderr); fflush (stdout); *c_ptr = c; if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); return CHECK_RES_HARD_ERROR; } #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc))) || /* TLS options */ /* currently skip any peer authentication */ (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fflush (stderr); fflush (stdout); fprintf (stderr, "Error setting libcurl option: %s.\n", curl_easy_strerror (errornum)); return CHECK_RES_HARD_ERROR; } libcurl_tls_set = 0; #if CURL_AT_LEAST_VERSION (7,54,0) if (CURL_SSLVERSION_MAX_DEFAULT != libcurl_tls_max_vers_map[tls_ver_libcurl]) { errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION, libcurl_tls_vers_map[tls_ver_libcurl] | libcurl_tls_max_vers_map[tls_ver_libcurl]); if (CURLE_OK == errornum) libcurl_tls_set = 1; else { fprintf (stderr, "Error setting libcurl TLS version range: " "%s.\nRetrying with minimum TLS version only.\n", curl_easy_strerror (errornum)); } } #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ if (! libcurl_tls_set && (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION, libcurl_tls_vers_map[tls_ver_libcurl])))) { fprintf (stderr, "Error setting libcurl minimum TLS version: %s.\n", curl_easy_strerror (errornum)); return CHECK_RES_CURL_TLS_INIT_FAIL; } errornum = curl_easy_perform (c); fflush (stderr); fflush (stdout); if (CURLE_OK != errornum) { if ((CURLE_SSL_CONNECT_ERROR == errornum) || (CURLE_SSL_CIPHER == errornum)) { fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n", curl_easy_strerror (errornum)); return CHECK_RES_CURL_TLS_CONN_FAIL; } else { fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); return CHECK_RES_ERR; } } return CHECK_RES_OK; } /** * negotiate a secure connection with server with specific TLS versions * set for MHD and for libcurl */ static enum check_result check_tls_match (enum know_gnutls_tls_id tls_ver_mhd, enum know_gnutls_tls_id tls_ver_libcurl, uint16_t *pport) { CURL *c; struct CBC cbc; enum check_result ret; struct MHD_Daemon *d; if (NULL == (cbc.buf = malloc (sizeof (char) * 255))) return CHECK_RES_HARD_ERROR; cbc.size = 255; cbc.pos = 0; d = NULL; c = NULL; ret = check_tls_match_inner (tls_ver_mhd, tls_ver_libcurl, pport, &d, &cbc, &c); fflush (stderr); fflush (stdout); if (NULL != d) MHD_stop_daemon (d); if (NULL != c) curl_easy_cleanup (c); free (cbc.buf); return ret; } static unsigned int test_first_supported_versions (void) { enum know_gnutls_tls_id ver_for_check; /**< TLS version used for test */ const gnutls_protocol_t *vers_list; /**< The list of GnuTLS supported TLS versions */ uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else port = 3080; /* Use predefined port, may break parallel testing of another MHD build */ vers_list = gnutls_protocol_list (); if (NULL == vers_list) { fprintf (stderr, "Error getting GnuTLS supported TLS versions"); return 99; } for (ver_for_check = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_check; ++ver_for_check) { const gnutls_protocol_t *ver_ptr; /**< The pointer to the position on the @a vers_list */ enum check_result res; for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr) { if (ver_for_check == (enum know_gnutls_tls_id) *ver_ptr) break; } if (0 == *ver_ptr) { printf ("%s is not supported by GnuTLS, skipping.\n\n", tls_names[ver_for_check]); fflush (stdout); continue; } if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check]) { printf ("%s is not supported by libcurl, skipping.\n\n", tls_names[ver_for_check]); fflush (stdout); continue; } /* Found some TLS version that supported by GnuTLS and should be supported by libcurl (but in practice support depends on used TLS library) */ if (KNOWN_TLS_MIN != ver_for_check) printf ("\n"); printf ("Starting check with MHD set to '%s' and " "libcurl set to '%s' (successful connection is expected)...\n", tls_names[ver_for_check], tls_names[ver_for_check]); fflush (stdout); /* Check with MHD and libcurl set to the same TLS version */ res = check_tls_match (ver_for_check, ver_for_check, &port); if (CHECK_RES_HARD_ERROR == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (CHECK_RES_ERR == res) { printf ("Test failed.\n"); fflush (stdout); return 2; } else if (CHECK_RES_MHD_START_FAILED == res) { printf ("Skipping '%s' as MHD cannot be started with this setting.\n", tls_names[ver_for_check]); fflush (stdout); continue; } else if (CHECK_RES_CURL_TLS_INIT_FAIL == res) { printf ("Skipping '%s' as libcurl rejected this setting.\n", tls_names[ver_for_check]); fflush (stdout); continue; } else if (CHECK_RES_CURL_TLS_CONN_FAIL == res) { printf ("Skipping '%s' as it is not supported by current libcurl " "and GnuTLS combination.\n", tls_names[ver_for_check]); fflush (stdout); continue; } printf ("Connection succeeded for MHD set to '%s' and " "libcurl set to '%s'.\n\n", tls_names[ver_for_check], tls_names[ver_for_check]); /* Check with libcurl set to the next TLS version relative to MHD setting */ if (KNOWN_TLS_MAX == ver_for_check) { printf ("Test is incomplete as the latest known TLS version ('%s') " "was found as minimum working version.\nThere is no space to " "advance to the next version.\nAssuming that test is fine.\n", tls_names[ver_for_check]); fflush (stdout); return 0; } if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check + 1]) { printf ("Test is incomplete as '%s' is the latest version supported " "by libcurl.\nThere is no space to " "advance to the next version.\nAssuming that test is fine.\n", tls_names[ver_for_check]); fflush (stdout); return 0; } printf ("Starting check with MHD set to '%s' and " "minimum libcurl TLS version set to '%s' " "(failed connection is expected)...\n", tls_names[ver_for_check], tls_names[ver_for_check + 1]); fflush (stdout); res = check_tls_match (ver_for_check, ver_for_check + 1, &port); if (CHECK_RES_HARD_ERROR == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (CHECK_RES_ERR == res) { printf ("Test failed.\n"); fflush (stdout); return 2; } else if (CHECK_RES_MHD_START_FAILED == res) { printf ("MHD cannot be started for the second time with " "the same setting.\n"); fflush (stdout); return 4; } else if (CHECK_RES_CURL_TLS_INIT_FAIL == res) { printf ("'%s' has been rejected by libcurl.\n" "Assuming that test is fine.\n", tls_names[ver_for_check + 1]); fflush (stdout); return 0; } else if (CHECK_RES_CURL_TLS_CONN_FAIL == res) { printf ("As expected, libcurl cannot connect to MHD when libcurl " "minimum TLS version is set to '%s' while MHD TLS version set " "to '%s'.\n" "Test succeeded.\n", tls_names[ver_for_check + 1], tls_names[ver_for_check]); fflush (stdout); return 0; } } fprintf (stderr, "The test skipped: No know TLS versions are supported by " "both MHD and libcurl.\n"); fflush (stderr); return 77; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_first_supported_versions (); fflush (stderr); fflush (stdout); curl_global_cleanup (); if (77 == errorCount) return 77; else if (99 == errorCount) return 99; print_test_result (errorCount, argv[0]); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/test_https_sni.c0000644000175000017500000002213114760713574020330 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2013, 2016 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_sni.c * @brief Testcase for libmicrohttpd HTTPS with SNI operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include /* This test only works with GnuTLS >= 3.0 */ #if GNUTLS_VERSION_MAJOR >= 3 #include /** * A hostname, server key and certificate. */ struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; /** * Linked list of supported TLDs and respective certificates. */ static struct Hosts *hosts; /* Load the certificate and the private key. * (This code is largely taken from GnuTLS). */ static void load_keys (const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); if (NULL == host) abort (); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit (1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit (1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit (1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit (1); } gnutls_free (data.data); } /** * @param session the session we are giving a cert for * @param req_ca_dn NULL on server side * @param nreqs length of req_ca_dn, and thus 0 on server side * @param pk_algos NULL on server side * @param pk_algos_length 0 on server side * @param pcert list of certificates (to be set) * @param pcert_length length of pcert (to be set) * @param pkey the private key (to be set) */ static int sni_callback (gnutls_session_t session, const gnutls_datum_t *req_ca_dn, int nreqs, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_length, gnutls_pcert_st **pcert, unsigned int *pcert_length, gnutls_privkey_t *pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; (void) req_ca_dn; (void) nreqs; (void) pk_algos; (void) pk_algos_length; /* Unused. Silent compiler warning. */ name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } #if 0 fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); #endif *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } /* perform a HTTP GET request via SSL/TLS */ static int do_get (const char *url, uint16_t port) { CURL *c; struct CBC cbc; CURLcode errornum; size_t len; struct curl_slist *dns_info; char buf[256]; len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return -1; } cbc.size = len; cbc.pos = 0; c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_CAINFO, SRCDIR "/test-ca.crt"); /* perform peer authentication */ /* TODO merge into send_curl_req */ curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 2L); sprintf (buf, "mhdhost1:%u:127.0.0.1", (unsigned int) port); dns_info = curl_slist_append (NULL, buf); sprintf (buf, "mhdhost2:%u:127.0.0.1", (unsigned int) port); dns_info = curl_slist_append (dns_info, buf); curl_easy_setopt (c, CURLOPT_RESOLVE, dns_info); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free (cbc.buf); curl_slist_free_all (dns_info); return -1; } curl_easy_cleanup (c); curl_slist_free_all (dns_info); if (memcmp (cbc.buf, test_data, len) != 0) { fprintf (stderr, "Error: local file & received file differ.\n"); free (cbc.buf); return -1; } free (cbc.buf); return 0; } int main (int argc, char *const *argv) { unsigned int error_count = 0; struct MHD_Daemon *d; uint16_t port; const char *tls_backend; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3065; #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; tls_backend = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tls_backend) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } if (! curl_tls_is_gnutls () && ! curl_tls_is_openssl ()) { fprintf (stderr, "This test is reliable only with libcurl with GnuTLS or " "OpenSSL backends.\nSkipping the test as libcurl has '%s' " "backend.\n", tls_backend); curl_global_cleanup (); return 77; } load_keys ("mhdhost1", SRCDIR "/mhdhost1.crt", SRCDIR "/mhdhost1.key"); load_keys ("mhdhost2", SRCDIR "/mhdhost2.crt", SRCDIR "/mhdhost2.key"); d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return -1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return -1; } port = dinfo->port; } if (0 != do_get ("https://mhdhost1/", port)) error_count++; if (0 != do_get ("https://mhdhost2/", port)) error_count++; MHD_stop_daemon (d); curl_global_cleanup (); if (error_count != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], error_count); return (0 != error_count) ? 1 : 0; } #else int main (void) { fprintf (stderr, "SNI not supported by GnuTLS < 3.0\n"); return 77; } #endif libmicrohttpd-1.0.2/src/testcurl/https/test-ca.crt0000644000175000017500000000421314674632555017170 00000000000000-----BEGIN CERTIFICATE----- MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3 MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36 ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/ B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6 6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1 kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9 9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/ nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg 4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA== -----END CERTIFICATE----- libmicrohttpd-1.0.2/src/testcurl/https/test_https_get_parallel_threads.c0000644000175000017500000001304714760713574023712 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_parallel_threads.c * @brief Testcase for libmicrohttpd HTTPS GET operations with multi-threaded * MHD daemon and several clients working in parallel * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * * TODO: add test for external select! */ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 4 #endif /** * used when spawning multiple threads executing curl server requests * */ static void * https_transfer_thread_adapter (void *args) { static int nonnull; struct https_test_data *cargs = args; unsigned int ret; ret = test_https_transfer (cargs->cls, cargs->port, cargs->cipher_suite, cargs->proto_version); if (ret == 0) return NULL; return &nonnull; } /** * Test non-parallel requests. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_single_client (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { void *client_thread_ret; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ client_thread_ret = https_transfer_thread_adapter (&client_args); if (client_thread_ret != NULL) return 1; return 0; } /** * Test parallel request handling. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { int i; int client_count = (MHD_CPU_COUNT - 1); void *client_thread_ret; pthread_t client_arr[client_count]; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ for (i = 0; i < client_count; ++i) { if (pthread_create (&client_arr[i], NULL, &https_transfer_thread_adapter, &client_args) != 0) { fprintf (stderr, "Error: failed to spawn test client threads.\n"); return 1; } } /* check all client requests fulfilled correctly */ for (i = 0; i < client_count; ++i) { if ((pthread_join (client_arr[i], &client_thread_ret) != 0) || (client_thread_ret != NULL)) return 1; } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; uint16_t port; unsigned int iseed; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3010; /* initialize random seed used by curl clients */ iseed = (unsigned int) time (NULL); #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ srand (iseed); if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_wrap ("multi threaded daemon, single client", &test_single_client, NULL, port, MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); errorCount += test_wrap ("multi threaded daemon, parallel client", &test_parallel_clients, NULL, port, MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/Makefile.in0000644000175000017500000021274315035216310017147 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage check_PROGRAMS = test_https_get_select$(EXEEXT) $(am__EXEEXT_5) @USE_THREADS_TRUE@am__append_2 = \ @USE_THREADS_TRUE@ $(THREAD_ONLY_TESTS) subdir = src/testcurl/https ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@am__EXEEXT_1 = test_https_time_out$(EXEEXT) \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel$(EXEEXT) \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel_threads$(EXEEXT) @HAVE_GNUTLS_SNI_TRUE@am__EXEEXT_2 = test_https_sni$(EXEEXT) am__EXEEXT_3 = am__EXEEXT_4 = test_tls_options$(EXEEXT) \ test_tls_authentication$(EXEEXT) $(am__EXEEXT_1) \ $(am__EXEEXT_2) test_https_session_info$(EXEEXT) \ test_https_session_info_append$(EXEEXT) \ test_https_multi_daemon$(EXEEXT) test_https_get$(EXEEXT) \ test_empty_response$(EXEEXT) test_https_get_iovec$(EXEEXT) \ $(am__EXEEXT_3) @USE_THREADS_TRUE@am__EXEEXT_5 = $(am__EXEEXT_4) am_test_empty_response_OBJECTS = test_empty_response.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_empty_response_OBJECTS = $(am_test_empty_response_OBJECTS) test_empty_response_LDADD = $(LDADD) am__DEPENDENCIES_1 = test_empty_response_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_test_https_get_OBJECTS = test_https_get.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_OBJECTS = $(am_test_https_get_OBJECTS) test_https_get_LDADD = $(LDADD) test_https_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_get_iovec_OBJECTS = test_https_get_iovec.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_iovec_OBJECTS = $(am_test_https_get_iovec_OBJECTS) test_https_get_iovec_LDADD = $(LDADD) test_https_get_iovec_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_get_parallel_OBJECTS = \ test_https_get_parallel-test_https_get_parallel.$(OBJEXT) \ test_https_get_parallel-tls_test_common.$(OBJEXT) test_https_get_parallel_OBJECTS = \ $(am_test_https_get_parallel_OBJECTS) am__DEPENDENCIES_2 = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_https_get_parallel_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_https_get_parallel_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_https_get_parallel_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_https_get_parallel_threads_OBJECTS = test_https_get_parallel_threads-test_https_get_parallel_threads.$(OBJEXT) \ test_https_get_parallel_threads-tls_test_common.$(OBJEXT) test_https_get_parallel_threads_OBJECTS = \ $(am_test_https_get_parallel_threads_OBJECTS) test_https_get_parallel_threads_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_https_get_parallel_threads_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_https_get_select_OBJECTS = test_https_get_select.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_select_OBJECTS = $(am_test_https_get_select_OBJECTS) test_https_get_select_LDADD = $(LDADD) test_https_get_select_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_multi_daemon_OBJECTS = \ test_https_multi_daemon.$(OBJEXT) tls_test_common.$(OBJEXT) test_https_multi_daemon_OBJECTS = \ $(am_test_https_multi_daemon_OBJECTS) test_https_multi_daemon_LDADD = $(LDADD) test_https_multi_daemon_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_session_info_OBJECTS = \ test_https_session_info.$(OBJEXT) tls_test_common.$(OBJEXT) test_https_session_info_OBJECTS = \ $(am_test_https_session_info_OBJECTS) test_https_session_info_LDADD = $(LDADD) test_https_session_info_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am__objects_1 = test_https_session_info.$(OBJEXT) \ tls_test_common.$(OBJEXT) am_test_https_session_info_append_OBJECTS = $(am__objects_1) test_https_session_info_append_OBJECTS = \ $(am_test_https_session_info_append_OBJECTS) test_https_session_info_append_LDADD = $(LDADD) test_https_session_info_append_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_sni_OBJECTS = test_https_sni.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_sni_OBJECTS = $(am_test_https_sni_OBJECTS) test_https_sni_LDADD = $(LDADD) test_https_sni_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_time_out_OBJECTS = test_https_time_out.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_time_out_OBJECTS = $(am_test_https_time_out_OBJECTS) test_https_time_out_LDADD = $(LDADD) test_https_time_out_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_tls_authentication_OBJECTS = \ test_tls_authentication.$(OBJEXT) tls_test_common.$(OBJEXT) test_tls_authentication_OBJECTS = \ $(am_test_tls_authentication_OBJECTS) test_tls_authentication_LDADD = $(LDADD) test_tls_authentication_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_tls_options_OBJECTS = test_tls_options.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_tls_options_OBJECTS = $(am_test_tls_options_OBJECTS) test_tls_options_LDADD = $(LDADD) test_tls_options_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/test_empty_response.Po \ ./$(DEPDIR)/test_https_get.Po \ ./$(DEPDIR)/test_https_get_iovec.Po \ ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po \ ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po \ ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po \ ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po \ ./$(DEPDIR)/test_https_get_select.Po \ ./$(DEPDIR)/test_https_multi_daemon.Po \ ./$(DEPDIR)/test_https_session_info.Po \ ./$(DEPDIR)/test_https_sni.Po \ ./$(DEPDIR)/test_https_time_out.Po \ ./$(DEPDIR)/test_tls_authentication.Po \ ./$(DEPDIR)/test_tls_options.Po ./$(DEPDIR)/tls_test_common.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(test_empty_response_SOURCES) $(test_https_get_SOURCES) \ $(test_https_get_iovec_SOURCES) \ $(test_https_get_parallel_SOURCES) \ $(test_https_get_parallel_threads_SOURCES) \ $(test_https_get_select_SOURCES) \ $(test_https_multi_daemon_SOURCES) \ $(test_https_session_info_SOURCES) \ $(test_https_session_info_append_SOURCES) \ $(test_https_sni_SOURCES) $(test_https_time_out_SOURCES) \ $(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES) DIST_SOURCES = $(test_empty_response_SOURCES) \ $(test_https_get_SOURCES) $(test_https_get_iovec_SOURCES) \ $(test_https_get_parallel_SOURCES) \ $(test_https_get_parallel_threads_SOURCES) \ $(test_https_get_select_SOURCES) \ $(test_https_multi_daemon_SOURCES) \ $(test_https_session_info_SOURCES) \ $(test_https_session_info_append_SOURCES) \ $(test_https_sni_SOURCES) $(test_https_time_out_SOURCES) \ $(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ -DSRCDIR=\"$(srcdir)\" \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) @LIBGCRYPT_LIBS@ @LIBCURL@ @HAVE_GNUTLS_SNI_TRUE@TEST_HTTPS_SNI = test_https_sni @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@HTTPS_PARALLEL_TESTS = \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_time_out \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel_threads THREAD_ONLY_TESTS = \ test_tls_options \ test_tls_authentication \ $(HTTPS_PARALLEL_TESTS) \ $(TEST_HTTPS_SNI) \ test_https_session_info \ test_https_session_info_append \ test_https_multi_daemon \ test_https_get \ test_empty_response \ test_https_get_iovec \ $(EMPTY_ITEM) EXTRA_DIST = \ test-ca.crt test-ca.key \ mhdhost1.crt mhdhost1.key \ mhdhost2.crt mhdhost2.key TESTS = \ $(check_PROGRAMS) test_https_time_out_SOURCES = \ test_https_time_out.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_tls_options_SOURCES = \ test_tls_options.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_SOURCES = \ test_https_get_parallel.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_empty_response_SOURCES = \ test_empty_response.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_SOURCES = \ test_https_get_parallel_threads.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_threads_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_tls_authentication_SOURCES = \ test_tls_authentication.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_SOURCES = \ test_https_session_info.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_append_SOURCES = $(test_https_session_info_SOURCES) test_https_multi_daemon_SOURCES = \ test_https_multi_daemon.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_SOURCES = \ test_https_get.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_iovec_SOURCES = \ test_https_get_iovec.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_sni_SOURCES = \ test_https_sni.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_select_SOURCES = \ test_https_get_select.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/https/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testcurl/https/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list test_empty_response$(EXEEXT): $(test_empty_response_OBJECTS) $(test_empty_response_DEPENDENCIES) $(EXTRA_test_empty_response_DEPENDENCIES) @rm -f test_empty_response$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_empty_response_OBJECTS) $(test_empty_response_LDADD) $(LIBS) test_https_get$(EXEEXT): $(test_https_get_OBJECTS) $(test_https_get_DEPENDENCIES) $(EXTRA_test_https_get_DEPENDENCIES) @rm -f test_https_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_OBJECTS) $(test_https_get_LDADD) $(LIBS) test_https_get_iovec$(EXEEXT): $(test_https_get_iovec_OBJECTS) $(test_https_get_iovec_DEPENDENCIES) $(EXTRA_test_https_get_iovec_DEPENDENCIES) @rm -f test_https_get_iovec$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_iovec_OBJECTS) $(test_https_get_iovec_LDADD) $(LIBS) test_https_get_parallel$(EXEEXT): $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_DEPENDENCIES) $(EXTRA_test_https_get_parallel_DEPENDENCIES) @rm -f test_https_get_parallel$(EXEEXT) $(AM_V_CCLD)$(test_https_get_parallel_LINK) $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_LDADD) $(LIBS) test_https_get_parallel_threads$(EXEEXT): $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_DEPENDENCIES) $(EXTRA_test_https_get_parallel_threads_DEPENDENCIES) @rm -f test_https_get_parallel_threads$(EXEEXT) $(AM_V_CCLD)$(test_https_get_parallel_threads_LINK) $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_LDADD) $(LIBS) test_https_get_select$(EXEEXT): $(test_https_get_select_OBJECTS) $(test_https_get_select_DEPENDENCIES) $(EXTRA_test_https_get_select_DEPENDENCIES) @rm -f test_https_get_select$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_select_OBJECTS) $(test_https_get_select_LDADD) $(LIBS) test_https_multi_daemon$(EXEEXT): $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_DEPENDENCIES) $(EXTRA_test_https_multi_daemon_DEPENDENCIES) @rm -f test_https_multi_daemon$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_LDADD) $(LIBS) test_https_session_info$(EXEEXT): $(test_https_session_info_OBJECTS) $(test_https_session_info_DEPENDENCIES) $(EXTRA_test_https_session_info_DEPENDENCIES) @rm -f test_https_session_info$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_session_info_OBJECTS) $(test_https_session_info_LDADD) $(LIBS) test_https_session_info_append$(EXEEXT): $(test_https_session_info_append_OBJECTS) $(test_https_session_info_append_DEPENDENCIES) $(EXTRA_test_https_session_info_append_DEPENDENCIES) @rm -f test_https_session_info_append$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_session_info_append_OBJECTS) $(test_https_session_info_append_LDADD) $(LIBS) test_https_sni$(EXEEXT): $(test_https_sni_OBJECTS) $(test_https_sni_DEPENDENCIES) $(EXTRA_test_https_sni_DEPENDENCIES) @rm -f test_https_sni$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_sni_OBJECTS) $(test_https_sni_LDADD) $(LIBS) test_https_time_out$(EXEEXT): $(test_https_time_out_OBJECTS) $(test_https_time_out_DEPENDENCIES) $(EXTRA_test_https_time_out_DEPENDENCIES) @rm -f test_https_time_out$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_time_out_OBJECTS) $(test_https_time_out_LDADD) $(LIBS) test_tls_authentication$(EXEEXT): $(test_tls_authentication_OBJECTS) $(test_tls_authentication_DEPENDENCIES) $(EXTRA_test_tls_authentication_DEPENDENCIES) @rm -f test_tls_authentication$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tls_authentication_OBJECTS) $(test_tls_authentication_LDADD) $(LIBS) test_tls_options$(EXEEXT): $(test_tls_options_OBJECTS) $(test_tls_options_DEPENDENCIES) $(EXTRA_test_tls_options_DEPENDENCIES) @rm -f test_tls_options$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tls_options_OBJECTS) $(test_tls_options_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_empty_response.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_iovec.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_multi_daemon.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_session_info.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_sni.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_time_out.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_authentication.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_options.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tls_test_common.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< test_https_get_parallel-test_https_get_parallel.o: test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c test_https_get_parallel-test_https_get_parallel.obj: test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi` test_https_get_parallel-tls_test_common.o: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c test_https_get_parallel-tls_test_common.obj: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` test_https_get_parallel_threads-test_https_get_parallel_threads.o: test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c test_https_get_parallel_threads-test_https_get_parallel_threads.obj: test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi` test_https_get_parallel_threads-tls_test_common.o: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c test_https_get_parallel_threads-tls_test_common.obj: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_https_get_select.log: test_https_get_select$(EXEEXT) @p='test_https_get_select$(EXEEXT)'; \ b='test_https_get_select'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tls_options.log: test_tls_options$(EXEEXT) @p='test_tls_options$(EXEEXT)'; \ b='test_tls_options'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tls_authentication.log: test_tls_authentication$(EXEEXT) @p='test_tls_authentication$(EXEEXT)'; \ b='test_tls_authentication'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_time_out.log: test_https_time_out$(EXEEXT) @p='test_https_time_out$(EXEEXT)'; \ b='test_https_time_out'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_parallel.log: test_https_get_parallel$(EXEEXT) @p='test_https_get_parallel$(EXEEXT)'; \ b='test_https_get_parallel'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_parallel_threads.log: test_https_get_parallel_threads$(EXEEXT) @p='test_https_get_parallel_threads$(EXEEXT)'; \ b='test_https_get_parallel_threads'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_sni.log: test_https_sni$(EXEEXT) @p='test_https_sni$(EXEEXT)'; \ b='test_https_sni'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_session_info.log: test_https_session_info$(EXEEXT) @p='test_https_session_info$(EXEEXT)'; \ b='test_https_session_info'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_session_info_append.log: test_https_session_info_append$(EXEEXT) @p='test_https_session_info_append$(EXEEXT)'; \ b='test_https_session_info_append'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_multi_daemon.log: test_https_multi_daemon$(EXEEXT) @p='test_https_multi_daemon$(EXEEXT)'; \ b='test_https_multi_daemon'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get.log: test_https_get$(EXEEXT) @p='test_https_get$(EXEEXT)'; \ b='test_https_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_empty_response.log: test_empty_response$(EXEEXT) @p='test_empty_response$(EXEEXT)'; \ b='test_empty_response'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_iovec.log: test_https_get_iovec$(EXEEXT) @p='test_https_get_iovec$(EXEEXT)'; \ b='test_https_get_iovec'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/test_empty_response.Po -rm -f ./$(DEPDIR)/test_https_get.Po -rm -f ./$(DEPDIR)/test_https_get_iovec.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_select.Po -rm -f ./$(DEPDIR)/test_https_multi_daemon.Po -rm -f ./$(DEPDIR)/test_https_session_info.Po -rm -f ./$(DEPDIR)/test_https_sni.Po -rm -f ./$(DEPDIR)/test_https_time_out.Po -rm -f ./$(DEPDIR)/test_tls_authentication.Po -rm -f ./$(DEPDIR)/test_tls_options.Po -rm -f ./$(DEPDIR)/tls_test_common.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/test_empty_response.Po -rm -f ./$(DEPDIR)/test_https_get.Po -rm -f ./$(DEPDIR)/test_https_get_iovec.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_select.Po -rm -f ./$(DEPDIR)/test_https_multi_daemon.Po -rm -f ./$(DEPDIR)/test_https_session_info.Po -rm -f ./$(DEPDIR)/test_https_sni.Po -rm -f ./$(DEPDIR)/test_https_time_out.Po -rm -f ./$(DEPDIR)/test_tls_authentication.Po -rm -f ./$(DEPDIR)/test_tls_options.Po -rm -f ./$(DEPDIR)/tls_test_common.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile @HEAVY_TESTS_NOTPARALLEL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/testcurl/https/mhdhost1.key0000644000175000017500000000325014674632555017357 00000000000000-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFvkuTBN+821Z4 VJgA+gTOrBUBFbEMNHY99CaYG2seEw0RDJQJOD41rTSERBtxlvPt+BLQU5jWGPIw UlqY0Y/TfUe8xLvMc1AngdsTPR3US54+CMS9ZoUwWdxMoafTsKf17dFy/aKEn8gj zB/emH+T9RM6/rZiEizZ8xAzksPqhf26UomEBo68VPqHKsHXF7edWE9PQ+ytReWT LbneTtdcQAhY7p0tmcrfvtSJEMkicVL0U3+GiMVv7yBwHKj+ff0scwG2nlYYzn7E bAQfJiTC2dozwgQqh9tQ0RFBPdyA+/jM3ufLcvCWNHYDVzmAdeYo7sbbjm1t+ptW 06Hf7VslAgMBAAECggEALshrttezW0oFNijFYY3FL2Q0//Gy1nFe/B9UNi5edFoL gFoad+fvh+F3iEdYutH82fMT+GeexCBYxCfnuTnzLhT4sOdWivNJJl+phe6yrPRK 9uA6M5kar6rC3Ppt6z5jLmLaZ7ssBPaMcjOr4ozvugCEUTPL0H3+UH4Z+imh4kzw MgLsF8QkWPCF/fxsVhCwC3y3Dctl3oLh6qQFudYKtymRjk2I7zFAuQGsGoYonPbF 1LZ6xHOjegXtqhC0pK8Kpn4N7LgYVVNPT1TAckQ9GDDi0IgMYwIsSQb/ncaV5Cwb 9tPqBv1Oi2ayINeXrG5J/G8S1cEbIzdSL8ZqG+CcjQKBgQD1c89Rh/Hbc0zxxgdR eGx6oOtNjAZ3zgnNyVnXiZ7mXtbCcjMHJhcW41RL8lg+mhKfj9MgXamDP/R4X2In H358dEekfN4wjogeXs9lmh48cGC7zez4/RS752OmrwmhOqkKDa7dy+SLR5QJ3L2n 4k/2eQwTlXpuPIMrBT1hUvsA3wKBgQDOPaTy03oXX1bwwX6sHUTrQTKAC52v4hQl bya+6t+VGpj+cdWzxRFoR5mN85b9Kkj1nAFx+6zioOPLUOZhnnqihlQBwm06gH1p v3qkxuXOhnMPJsNg4lltUq/18UlSQwFZuKr7G2vDhckHwZdlu06P/rlA9K5Kxjzi gX3I+XoQewKBgQDrn/YYXXmW4jOuMR0bX5A7lDjuY4pd/iO5Mh6V453vpoFhfoFv zmgB588nbQi7Z+qS1F2nx2IQBhgoaeBukDQ7QuD3jYs6b8lJ5lgQQAfgmzyxbPic +U6rJ3CpNYT4Crj1VrdUYgQOlHMPmKFUBdQfVop6TleOdXaxmMEYqbEdXwKBgQCz xZwQZjJYSSyZc7CdCm5Wul/wqS9sbp6s+rRFWqpFaAfQUx26M582zKKWz6vfRYqP PMsttfk/Gos1YHFQyjmPjZOQbQ+VHQc0tEmNdCpA2YVVwa4wt1zIJHlo4kfNQsbc lFHFzGMk7WsMLb1wWdLjRV/ptN5wI1hTABjKpFu4HQKBgExQNTHMxzpAAh9XFiJ3 oGvf+9+JtjmrgKsR0T7q60xjOYH0E2rznvvBVNeZlAc+tjawmedxiuiitmjQUteG hW4ncX0UcqFPm7Ahqo9+NDemJlV7DYHRcvL/xVNUbr8yV7OpHILd4Hk/s8J4QGl/ bC1zEehy8q0jMywvSR8vsS1v -----END PRIVATE KEY----- libmicrohttpd-1.0.2/src/testcurl/https/test_tls_authentication.c0000644000175000017500000001001314760713574022212 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_tls_authentication.c * @brief Testcase for libmicrohttpd HTTPS GET operations with CA-signed TLS server certificate * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (void *cls, const char *cipher_suite, int proto_version) { enum test_get_result ret; struct MHD_Daemon *d; uint16_t port; (void) cls; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3075; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_daemon_get (NULL, cipher_suite, proto_version, port, 1); MHD_stop_daemon (d); if (TEST_GET_HARD_ERROR == ret) return 99; if (TEST_GET_CURL_GEN_ERROR == ret) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); return 99; } if ((TEST_GET_CURL_CA_ERROR == ret) || (TEST_GET_CURL_NOT_IMPLT == ret)) { fprintf (stderr, "libcurl TLS backend does not support custom CA.\n" "Test skipped.\n"); return 77; } return TEST_GET_OK == ret ? 0 : 1; } int main (int argc, char *const *argv) { unsigned int errorCount; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } #if ! CURL_AT_LEAST_VERSION (7,60,0) if (curl_tls_is_schannel ()) { fprintf (stderr, "libcurl before version 7.60.0 does not support " "custom CA with Schannel backend.\nTest skipped.\n"); curl_global_cleanup (); return 77; } #endif /* ! CURL_AT_LEAST_VERSION(7,60,0) */ errorCount = test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT); print_test_result (errorCount, argv[0]); curl_global_cleanup (); if (77 == errorCount) return 77; if (99 == errorCount) return 77; return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/https/tls_test_keys.h0000644000175000017500000002460714760713577020174 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2006, 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MHD_TLS_TEST_KEYS_H #define MHD_TLS_TEST_KEYS_H /* Test Certificates */ /* Certificate Authority cert */ static const char ca_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3\n\ MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM\n\ Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN\n\ AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G\n\ CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36\n\ ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI\n\ IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/\n\ B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6\n\ 6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP\n\ t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw\n\ Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN\n\ x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH\n\ QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH\n\ KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR\n\ bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR\n\ q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG\n\ AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK\n\ BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB\n\ MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA\n\ A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1\n\ kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay\n\ ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj\n\ ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9\n\ 9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD\n\ TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl\n\ WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s\n\ E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/\n\ nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM\n\ Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg\n\ 4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA==\n\ -----END CERTIFICATE-----"; /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; /* test server self signed certificates */ static const char srv_self_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIDJzCCAg+gAwIBAgIUOKf6e6Heee2XA+yF5St3t+fVM40wDQYJKoZIhvcNAQEF\n" "BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIyMTAxMDA4MzQ0N1oYDzIxMjIw\n" "OTE2MDgzNDQ3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB\n" "AQUAA4IBDwAwggEKAoIBAQClivgF8Xq0ekQli++0l7Q5JFwJCuLf04Cb1UKIS80U\n" "CfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz53vOwVNyiZ+sMGi4bDX4AV9Xd+F83\n" "xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtvqrRRBen30iKOwX7uNF/4dYb9vdin\n" "OldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VMFZM2hwmHyiiw75/j4BhUlLCcMEvK\n" "oN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1SzAltxF2gmI0jzw8r/duz18QXMNsMw\n" "El/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7yg649wHTAgMBAAGjbzBtMB0GA1Ud\n" "DgQWBBROVferD+YYcV1YEnFgC0jYm5X9BjAfBgNVHSMEGDAWgBROVferD+YYcV1Y\n" "EnFgC0jYm5X9BjAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9z\n" "dIcEfwAAATANBgkqhkiG9w0BAQUFAAOCAQEAoRbozsm5xXdNX3VO++s2LMzw5KM9\n" "RpIInHNkMJbnyLJFKJ8DF7nTxSGCA38YMkX3tphPNKZXbg+V64Dqr/XpzOVyiinU\n" "7hIwyUdSSKKyErZxIWR97lY6Q3SOyPAg8ZElbtvSsSzmd772VE23VTXGDi7AW0PQ\n" "hag9N2EEnHURMvID15O+UXyFpDdyUyQIbx3HuswsGDH9xBTm4irLyrZwO0KwKg5a\n" "JBeUiPs0SYRRfn9/MoE6VwAnmOCg3LLR6ZPU3hQtTPLHj2Op1g5fey3X3X6lC+JC\n" "K6dNZc1zBFPz8KANGUsFYbmoP2bvAAA+6KwCnZZEflUgE7/HFEmQhVOezw==\n" "-----END CERTIFICATE-----\n"; /* test server key */ static const char srv_self_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClivgF8Xq0ekQl\n" "i++0l7Q5JFwJCuLf04Cb1UKIS80UCfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz5\n" "3vOwVNyiZ+sMGi4bDX4AV9Xd+F83xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtv\n" "qrRRBen30iKOwX7uNF/4dYb9vdinOldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VM\n" "FZM2hwmHyiiw75/j4BhUlLCcMEvKoN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1Sz\n" "AltxF2gmI0jzw8r/duz18QXMNsMwEl/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7\n" "yg649wHTAgMBAAECggEAERbbCtYGakoy7cNX8Ac3Kiz4OVC/4gZWAQBPeX2FwrtS\n" "9yHIMbK0x1mxIZ6eBpabBpZlW2vDCSOKuxLKiloAWt2qdJnhR5apesSWhe8leT7/\n" "xq5dgZpAlMH6SIRKObknd2yY+qicW0A0licDrVeUcypkueL8xP9wJtiPInOuQXkI\n" "QROhB13eStRuRKYwOn5gtwAHJ+J1DFKKiqpBOkrSYf4625StGegJO9+bjK0ei+0W\n" "tp6unpiwA/lXTgz6Xim1Z3fzWs4XjFgVKzK5s/6yBJjr8spHX6lv7QsahP4w6HZ/\n" "VcRxP6cJNd/otiTEtJXpbxiiyccwXm/AOcOn22P1cQKBgQDAnY/0G/ap/G98pneE\n" "suzNXhWOQ8JoL8d66Io8vwTvfiJggfgUcwblI7pPCrSlaZMR7/q6JImE53lZtPk8\n" "eI3c9lN0ocr8E7+huDpYdk7cMYj9SuxySsXoMLiMqzHFi+NcIhKMF56kk6a5CFCt\n" "yP1Ofy76LVweGE3XvTwpwE7wUQKBgQDcBLyH1cC71s0I0Gz28AyELV9hPhasjAKO\n" "12CVbeBVTPd+28uk/3o80wSrTksc6H5ehAA2aTvrb4OhwssWNL+D0fS8YK2cJ3V0\n" "FJxGAM266+vC4d/8jRTHJnc+6PP3ix5t6vAt+K2Y0fePtefLqf4ebgXx/ODAj3J2\n" "aZKBldjK4wKBgGIRFpTLk/eR/dUyEBHw4x3gdAsdtqJDCUYrlQ4+ly20Q55tLbiD\n" "pBQP77CEm9rH+MgeLcKODbIsBB3HRUojet7wTydHpMhY6a1V1ebqPVZgpgWIGwBJ\n" "z59bBusf0lRo15Y2Bslq0SurvSvh7um8NjO8D1fytj7gUumvgC0lq0sxAoGBAI1+\n" "kkx9IBTtIDER8XGhkTsT/uoHxwcyh5abVmbjIclZ1TUFX2L+Vft17ePJVy8BKfvY\n" "wlY7uShBMBNAteDTDXNV/CGFv0DUc4myk4nFjIkwng9XufeuN3WX/Eo+AF/rXSdt\n" "VwcJjYLhTWdjoe1tppqlQTeN3HCaEA+s92ZVGvXnAoGAMCXGS6WZl1e5wsHRq0Yy\n" "8Ef2Wrk620bBjKHolkTfvgfhlvxeZM1sv1ioZGsOeQ0z7O7wdJhvL0M/WAG+3yQj\n" "HSXp81T1vOICPwNYZf8xcvbLKmvj7rHFt6ZAZF2o4EK8ReZTRyA3DUpBCDY+s3FN\n" "GmBv0D7N3QP0CT3SzfQrPkc=\n" "-----END PRIVATE KEY-----\n"; #endif libmicrohttpd-1.0.2/src/testcurl/https/mhdhost2.key0000644000175000017500000000325014674632555017360 00000000000000-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLa/Vzf1FA+AYS qFiKyJBflANMkUKv3cH8oL3oCrFd9SrFgdBkccHJ6HbIdfld5j5zCLNr09vyQHlb K7khXukdhstd61RDsdrygJdxdkGKHMwaN1NACkG8oRLaui2SDEgCvMVGT8qc7cPa vzsTb98eqUeODRjx3nyLzjqbsZIWkfa4BiiCbZmGLaiMTg7+p9o7pxJN2NSENsyI ORCV/9+Sr2jdl4bMpd3MsLk94gn/sdsRwEnR7qXIAVthm2lMC1Dr+26oBlOze0wb lirdwBljvHi8YQJloBZkCWCy0GkJh3xv92Vdryq/Hgm4wXir7u9VuDAdWhewDOZk DFI3L52ZAgMBAAECggEBAIS8cXFoBpEqRmwuRXhp3ys+3dg8gRNY1JgQG1sqfwoc TEiMqHqicB1b/wZXVNycvOs7JjiaCc9NmuKO6UKJN/v4VQN354g0qfXLSwbSb3m7 yMLijwQerT50rGTlT48ZTHPc0a1Lq54y17YJSncobKMJOpPKoBhTYVmovD2T5Qus EDFg8wLBA79YZnrImbt9hcRsi/bM341V3aSoPFdHz6NTi+5WA08oTiGCv6gThV8T PUCiy1uDJZ1gk3xne+APZfdTutVtwCYVw7mhgTHiL5tL1KCjDjzK3XgnfAWaN+wG ex9EYbn/uAxN57UrvdyvGtuBo01vs/XtsVlpRpmlBnECgYEA+L8D8UY36IubeMAl xFCoFSXSmT+2YtA6ISg4/8a14wpwAskJPW/Nf8CzzwbGA7QaDVeK4rTGDOwNQJV8 /fiTaG6vDI7GS3UkvSKStfJzoMRBTzCYp/TbkG/jW2i8tR1AATlQlGllx0BQVXhC iYpR/WzbxGi5iyB4K6WPbSKboh8CgYEA0VqUR7w+2PEEFXyFRL2drpzkWKk5RiIa cIzQk3VlrHztJp0g6w8MiWCIpzL+7BuBy72byxJwpFmOz4HYsEqc6mOF4xXezfYh oN0P1+/aH4NrpWmjb65TGrtwrmi2sJrmATmr9WKFxEIpgrbotOTDF7pIx9pY2ScA aohOxqb7eUcCgYAHtHL80D3/GAPy05DX6d+q+Abz9ENEAEssp8BMO+16YOJjU7LT klj9MgzfxsfvaW69Jw8IQq03zUAD1h2PCFoYjAUkEHAX+kLvENkWhbILMskLGOhB m5YJfU2/kRj3SzamUw4p6rHaYCWc4CK/e+daQDr2dH/6zUCrqW8t5DqJ5QKBgF8E voIkhV3PXiwmXRJLAXNMEDPRcoZLWja1IsGaqe/0r2o0LMmjBeygHMXOVndxMKL5 RumPUAK4ByJVa7Tv2HJlg1IDDiHq0W6ChvtaCGT/L+9el+hLdbqPUmBGdIyJcVUj CNIRyma+JLsIK2xW29k8GmZiyqqckgrIHQD6ru5nAoGAAcdAHQojvGs5dQ2Agqcn EOgF1dic7VgCjAEG4CNCydzskE92jEOgv2DI+oBPoLrtktHbewFrsxBBNbS+PcHY DyV5/WXf8wwwdkG1VLyw+dPeWNGWanvjllplckDXSGz1ia0s7ENNAt8o2MXdlZrQ MMHn0wo/1rTa1YroHF8cKVA= -----END PRIVATE KEY----- libmicrohttpd-1.0.2/src/testcurl/https/tls_test_common.h0000644000175000017500000001561614760713577020511 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2017-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef TLS_TEST_COMMON_H_ #define TLS_TEST_COMMON_H_ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #define test_data "Hello World\n" #define ca_cert_file_name SRCDIR "/test-ca.crt" #define EMPTY_PAGE \ "Empty pageEmpty page" #define PAGE_NOT_FOUND \ "File not foundFile not found" #define MHD_E_MEM "Error: memory error\n" #define MHD_E_SERVER_INIT "Error: failed to start server\n" #define MHD_E_TEST_FILE_CREAT "Error: failed to setup test file\n" #define MHD_E_CERT_FILE_CREAT "Error: failed to setup test certificate\n" #define MHD_E_KEY_FILE_CREAT "Error: failed to setup test certificate\n" #define MHD_E_FAILED_TO_CONNECT \ "Error: server connection could not be established\n" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /* The local copy if GnuTLS IDs to avoid long #ifdefs list with various * GnuTLS versions */ /** * The list of know (at the moment of writing) GnuTLS IDs of TLS versions. * Can be safely casted to/from @a gnutls_protocol_t. */ enum know_gnutls_tls_id { KNOWN_BAD = 0, /**< No TLS */ KNOWN_TLS_SSLv3 = 1, /**< GNUTLS_SSL3 */ KNOWN_TLS_V1_0 = 2, /**< GNUTLS_TLS1_0 */ KNOWN_TLS_V1_1 = 3, /**< GNUTLS_TLS1_1 */ KNOWN_TLS_V1_2 = 4, /**< GNUTLS_TLS1_2 */ KNOWN_TLS_V1_3 = 5, /**< GNUTLS_TLS1_3 */ KNOWN_TLS_MIN = KNOWN_TLS_SSLv3, /**< Minimum valid value */ KNOWN_TLS_MAX = KNOWN_TLS_V1_3 /**< Maximum valid value */ }; #define KNOW_TLS_IDS_COUNT 6 /* KNOWN_TLS_MAX + 1 */ /** * Map @a know_gnutls_tls_ids values to printable names. */ extern const char *tls_names[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings. */ extern const char *priorities_map[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings. */ extern const char *priorities_append_map[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value. */ extern const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT]; #if CURL_AT_LEAST_VERSION (7,54,0) /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value * for maximum supported TLS version. */ extern const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT]; #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ struct https_test_data { void *cls; uint16_t port; const char *cipher_suite; int proto_version; }; struct CBC { char *buf; size_t pos; size_t size; }; int curl_tls_is_gnutls (void); int curl_tls_is_openssl (void); int curl_tls_is_nss (void); int curl_tls_is_schannel (void); int curl_tls_is_sectransport (void); enum test_get_result { TEST_GET_OK = 0, TEST_GET_ERROR = 1, TEST_GET_MHD_ERROR = 16, TEST_GET_TRANSFER_ERROR = 17, TEST_GET_CURL_GEN_ERROR = 32, TEST_GET_CURL_CA_ERROR = 33, TEST_GET_CURL_NOT_IMPLT = 34, TEST_GET_HARD_ERROR = 999 }; /** * perform cURL request for file */ enum test_get_result test_daemon_get (void *cls, const char *cipher_suite, int proto_version, uint16_t port, int ver_peer); void print_test_result (unsigned int test_outcome, const char *test_name); size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx); enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, const char *version, size_t *upload_data_size, void **req_cls); enum MHD_Result http_dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, const char *version, size_t *upload_data_size, void **req_cls); /** * compile test URI * * @param[out] uri - char buffer into which the url is compiled * @param uri_len number of bytes available in @a url * @param port port to use for the test * @return 1 on error */ unsigned int gen_test_uri (char *uri, size_t uri_len, uint16_t port); CURLcode send_curl_req (char *url, struct CBC *cbc, const char *cipher_suite, int proto_version); unsigned int test_https_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version); unsigned int setup_session (gnutls_session_t *session, gnutls_certificate_credentials_t *xcred); unsigned int teardown_session (gnutls_session_t session, gnutls_certificate_credentials_t xcred); unsigned int test_wrap (const char *test_name, unsigned int (*test_function)(void *cls, uint16_t port, const char *cipher_suite, int proto_version), void *cls, uint16_t port, unsigned int daemon_flags, const char *cipher_suite, int proto_version, ...); int testsuite_curl_global_init (void); /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ int has_in_name (const char *prog_name, const char *marker); #endif /* TLS_TEST_COMMON_H_ */ libmicrohttpd-1.0.2/src/testcurl/https/test-ca.key0000644000175000017500000000625714674632555017202 00000000000000-----BEGIN RSA PRIVATE KEY----- MIIJKgIBAAKCAgEA3WlrqQOKmYwgTZCaCTpucZwmos5d+mS1MKeMQS/2H1z1hNy5 JgERIlSP2JwG/JehuwiZ8/HU7DiVpDVxuk9SlT+f9kbwSCGmmrn0SAJe4RJ49Y/R NoUJVdn8RdmTYc/p6otC6ileCyUqXJZFwA39hQPR7FUT/we82Ifgz9H0lPFem7Lv FwnkRrIa6AD63PKx/JRRBF6TSzSKkK/MisekpnQeoX42uukkNPvqgYZdGibZ+Cx1 maIYIwZpCGhhT2CCS4MUP8cqdhq89qu5RiifswZARfIjj7d8fhdYUggZ6/wxmFpo xJubWJvu6crq4j3XV3QnPPqmti8TGaNxF8S6OWCEqTwssGe1d2ADmU695tQtuC4m Lz3oQqtQkyJIYZqrZVSV1OyEg+PHMfcvuT4t+MLW0yP4DceL6MkywH8mryjJiKcc SEbFpXYhdp9Oh3bwkVXYoQ0FGnddMoE5ln9Sf7NmREwLR0GknezA9/Pbep0BbUyF 4oLDSp5wz5a7cbe6zi7y0HkdCtOBs63/7HIXjmp0QHzlxyjQRVO2JAxRvK6os5Qu ua8fanlxWF0HB2U7qsSu7YGZ0oCWrdxO9FW00grBBBu3kWzV/3woVCgCCKVmoluh w5Si5eptsvgczPdbpgbCjqk757TFRQUhfaVWJVyvOeGiEavANl7o3dNdrHkCAwEA AQKCAgEA2nPJ4j75P9gOgxj5scMx9uve/uDnvkYgszmMW0DL8FPSdd0k3AdPdXTD XC9NgWjGDHhHFXXz44FMu3BzniPnUhQtalrBdhmlfKGeEHIuVJjaOUZFYCpQdKEX k39BN89gdqYiRlC8Vfi8XA90EDJ9gQCs3SVwDj7/JxChUcpQK6gd9TbNSQjcbpgJ jgBxgw/9Zjyb1tjNMPVNBcY95Gtn20dUdXfG3hFrRM+Mp3D/aO8OPhr3iLZyZBRO CxqZcCzDQWe50dda4J4u9J2ntj4cmxC+14Q5a/HYZbv4yy7tDHWOJUiGd/0jf4CS b59isgfb8JBMqpCPbc7yZGhrC81xAZdsw0jvDYgGUf86785983clipdCVJIKMqZm yjoo2DuSaivCGnaWUV1f+W2CgigpSXcDQ1/gDMt7xVoZNpfmdTgZzthUxXK3dFYO Jwem/ls6KD5THKpkHuA9BpnoksnpZqREK5FdMw8hCUpJEe1kXy4ZlQB91Ya74HQ0 tgygL9BwEXDJ2vU14Onq8CH+Ul4kOzXnqMae35eKj1+/QI2PP1Wuk/vypSmrurfm 3YLsnwm7OYSuWrAfFRmGTMhfny3v1xlw1ynmVBvxgQ2v2czxKGw8JG+9LoqbSB5O GP05Gpcys1CwR9Z2EjfExFNcWFIJQjwcZemlgHHwvHCBy1fz0AUCggEBAPSnznDv Wuj3gTkUDfNFTplsa8z3GIyrfBYDUyGJ51YiN5C2myGRcu60r5iMl4hxXC6mL4Cd 5ew8LsXojPmC0sWZ2Cp+uhSH5FZaMNRumg4R8EA0Phwi0iBgDXM5318reMZF3BUr FSTn9a3nBkFpYMw1hxBlLj0o6S0TfZBmviTJUO7eiq6mAdO43l320Pw7E6xSWble QQaXzk2yGr2bV02heZcWfw+Fnui6xLruWZbVdvh+Q5KEJv90y9HcXm14LXiPRMBg zYvbW6tVZSQeXTs4wGC1RAZWZC7MG0XOoVj18WGx8hSZQND6awxFwHbItSlv05TX QkJ9ybZ7bcOQT78CggEBAOetsug2BQejAwRbbAsC078Vlr6PUspHmeT1Efp8ArFq rsmx2n2EoIcZSLkedZK1cXN7HMxVz1U0yx7k/OLIKlsfGNQdAQhCW875mbn0ET0c jUNpeJRXL6U5pwdPrsENyyAPsDyCsBT4ArGuEIFIxPlWtZTBzOAhJN9AwB5KW8g/ zg1mwv1TCNNlQu3Ex46egI3cCUk+6b1BNwPuSKhuP+P22Vg+JBhIY+/iSJvgSRfP 3LCNU0ds2D5xiwJNVwzVtrn3wIaYHj6S7lhfVGWdvQb8RsF9kyR06yJNTUyyybZ0 pTHeRwNtbUoTeBUlwoBac6izNyGGguA42pDYmoAcEccCggEAfXgZrV1zWAqmoOki BmLC3nf2CRWn52yCpJ9r4MVieI/vwy2C/YIkWTsc2rUveW/5gIsFzYYsxixPKHwM 4GExStmNPK3lLGZMueRjKm7WXuTgO20PdUp+TNA11aQWZC5dMAHfzpNbsqOrIVZb pOwwEkpZTBU303HJs65NNOMcHK2J7hb/NHY6daRXlgTgRJrfif5puWEXJBRyXvI6 OIcUDOIFA3EsFH/IcT5nah6Wn342F1ZZvSg8/8GcTbIgUy/Q0gVXkvmSMGl8569R wWY5FggS0QXlLwLbOgy+59wCbycidaHWrq2xyfrDL3YOMFzaW7fX4HtMpeDws781 GZhG7QKCAQEAhCfJTjzCUcDjD7E2yHEsaGvgOYN4Lnr5hmllgAUNZDb+zX7uq3rk NyxtF2wQlUd7F+y6WLT6OBiNZWop9xNHVgM/HoAM/rEbvc0Tq8dVrg6DZljbt4Kk YxOn+7uwa996ZyeL2HiUCOIQZ1prf9QKyFB19A042QEPD2rYLG8uO+RpnatovyiG eE/jBc6iJvCzVDiX83g3zQVOZKegOrPpLhi5kmSgIlno6AWkdYZTK4oe0XdMcgnc sIIEUaPcbC3ctehlomFTn04hN7fpZK2+DiYKFoWTUdB/8Gk4FvBFsBaJxRCOYZ4i IYdJkIahlKYEI89XO4CHV3AW/VkRiNJ6MQKCAQEAhosdYqtpJtdRJ3FWM4i6Miua OBEg7FU4JTH/0cekj0UMYFww3KK9c4KEdgVwRtsvLTZ++CXZ3XF9Er+6nPmC6nAo 46b3Ow7rPzpm18jUNWMW0s+CZwKWkGe1sbek81L8SBCDRJKKhl6XgiPHGB/i8g65 ZQv3B47BPflrjxJCQVADHpdW5vo0xY7xRr9zKYoAl4LQBTwLVMTP229iIcBFvRPp rs4KUecFQfEyXrJLwgQTl0uBItO86BWopCdh7T/0A7BjBk9jdklJNgml8Ctq+Yt9 nqduIeW3c1aNqbNhn+IA27WW+tv+yzA4gNPS/OWr8J67HDGm4WSUAFGMLwmcSw== -----END RSA PRIVATE KEY----- libmicrohttpd-1.0.2/src/testcurl/https/Makefile.am0000644000175000017500000000661215035214301017130 00000000000000# This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . @HEAVY_TESTS_NOTPARALLEL@ AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ -DSRCDIR=\"$(srcdir)\" \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) @LIBGCRYPT_LIBS@ @LIBCURL@ if HAVE_GNUTLS_SNI TEST_HTTPS_SNI = test_https_sni endif if !HAVE_GNUTLS_MTHREAD_BROKEN HTTPS_PARALLEL_TESTS = \ test_https_time_out \ test_https_get_parallel \ test_https_get_parallel_threads endif THREAD_ONLY_TESTS = \ test_tls_options \ test_tls_authentication \ $(HTTPS_PARALLEL_TESTS) \ $(TEST_HTTPS_SNI) \ test_https_session_info \ test_https_session_info_append \ test_https_multi_daemon \ test_https_get \ test_empty_response \ test_https_get_iovec \ $(EMPTY_ITEM) check_PROGRAMS = \ test_https_get_select if USE_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif EXTRA_DIST = \ test-ca.crt test-ca.key \ mhdhost1.crt mhdhost1.key \ mhdhost2.crt mhdhost2.key TESTS = \ $(check_PROGRAMS) test_https_time_out_SOURCES = \ test_https_time_out.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_tls_options_SOURCES = \ test_tls_options.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_SOURCES = \ test_https_get_parallel.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_empty_response_SOURCES = \ test_empty_response.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_SOURCES = \ test_https_get_parallel_threads.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_threads_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_tls_authentication_SOURCES = \ test_tls_authentication.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_SOURCES = \ test_https_session_info.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_append_SOURCES = $(test_https_session_info_SOURCES) test_https_multi_daemon_SOURCES = \ test_https_multi_daemon.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_SOURCES = \ test_https_get.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_iovec_SOURCES = \ test_https_get_iovec.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_sni_SOURCES = \ test_https_sni.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_select_SOURCES = \ test_https_get_select.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c libmicrohttpd-1.0.2/src/testcurl/https/test_https_session_info.c0000644000175000017500000002551714760713574022250 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2016-2021 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_session_info.c * @brief Testcase for libmicrohttpd HTTPS connection querying operations * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" static int test_append_prio; /* * HTTP access handler call back * used to query negotiated security parameters */ static enum MHD_Result query_info_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; const union MHD_ConnectionInfo *conn_info; enum know_gnutls_tls_id *used_tls_ver; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ used_tls_ver = (enum know_gnutls_tls_id *) cls; if (NULL == *req_cls) { *req_cls = (void *) &query_info_ahc; return MHD_YES; } conn_info = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_PROTOCOL); if (NULL == conn_info) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info() failed.\n"); fflush (stderr); return MHD_NO; } if (0 == (unsigned int) conn_info->protocol) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info()->protocol has " "wrong zero value.\n"); fflush (stderr); return MHD_NO; } *used_tls_ver = (enum know_gnutls_tls_id) conn_info->protocol; response = MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE), EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * negotiate a secure connection with server & query negotiated security parameters */ static unsigned int test_query_session (enum know_gnutls_tls_id tls_ver, uint16_t *pport) { CURL *c; struct CBC cbc; CURLcode errornum; char url[256]; enum know_gnutls_tls_id found_tls_ver; struct MHD_Daemon *d; if (NULL == (cbc.buf = malloc (sizeof (char) * 255))) return 99; cbc.size = 255; cbc.pos = 0; /* setup test */ found_tls_ver = KNOWN_BAD; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &query_info_ahc, &found_tls_ver, test_append_prio ? MHD_OPTION_HTTPS_PRIORITIES_APPEND : MHD_OPTION_HTTPS_PRIORITIES, test_append_prio ? priorities_append_map[tls_ver] : priorities_map[tls_ver], MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { free (cbc.buf); fprintf (stderr, "MHD_start_daemon() with %s failed.\n", tls_names[tls_ver]); fflush (stderr); return 77; } if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); free (cbc.buf); fprintf (stderr, "MHD_get_daemon_info() failed.\n"); fflush (stderr); return 10; } *pport = dinfo->port; /* Use the same port for rest of the checks */ } gen_test_uri (url, sizeof (url), *pport); c = curl_easy_init (); fflush (stderr); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); fflush (stderr); MHD_stop_daemon (d); free (cbc.buf); return 99; } #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc))) || /* TLS options */ /* currently skip any peer authentication */ (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); fflush (stderr); fflush (stdout); fprintf (stderr, "Error setting libcurl option: %s.\n", curl_easy_strerror (errornum)); fflush (stderr); return 99; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { unsigned int ret; curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); fflush (stderr); fflush (stdout); if ((CURLE_SSL_CONNECT_ERROR == errornum) || (CURLE_SSL_CIPHER == errornum)) { ret = 77; fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n", curl_easy_strerror (errornum)); } else { ret = 1; fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); } fflush (stderr); return ret; } curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); if (tls_ver != found_tls_ver) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info (conn, " "MHD_CONNECTION_INFO_PROTOCOL) returned unexpected " "protocol version.\n" "\tReturned: %s (%u)\tExpected: %s (%u)\n", ((unsigned int) found_tls_ver) > KNOWN_TLS_MAX ? "[wrong value]" : tls_names[found_tls_ver], (unsigned int) found_tls_ver, tls_names[tls_ver], (unsigned int) tls_ver); fflush (stderr); return 2; } return 0; } static unsigned int test_all_supported_versions (void) { enum know_gnutls_tls_id ver_for_test; /**< TLS version used for test */ const gnutls_protocol_t *vers_list; /**< The list of GnuTLS supported TLS versions */ uint16_t port; unsigned int num_success; /**< Number of tests succeeded */ unsigned int num_failed; /**< Number of tests failed */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else port = 3060; /* Use predefined port, may break parallel testing of another MHD build */ vers_list = gnutls_protocol_list (); if (NULL == vers_list) { fprintf (stderr, "Error getting GnuTLS supported TLS versions"); return 99; } num_success = 0; num_failed = 0; for (ver_for_test = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_test; ++ver_for_test) { const gnutls_protocol_t *ver_ptr; /**< The pointer to the position on the @a vers_list */ unsigned int res; for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr) { if (ver_for_test == (enum know_gnutls_tls_id) *ver_ptr) break; } if (0 == *ver_ptr) { printf ("%s is not supported by GnuTLS, skipping.\n\n", tls_names[ver_for_test]); fflush (stdout); continue; } printf ("Starting check for %s...\n", tls_names[ver_for_test]); fflush (stdout); res = test_query_session (ver_for_test, &port); fflush (stderr); fflush (stdout); if (99 == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (77 == res) { printf ("%s does not work with libcurl client and GnuTLS " "server combination, skipping.\n", tls_names[ver_for_test]); fflush (stdout); } else if (0 != res) { fprintf (stderr, "Check failed for %s.\n", tls_names[ver_for_test]); fflush (stderr); num_failed++; } else { printf ("Check succeeded for %s.\n", tls_names[ver_for_test]); fflush (stdout); num_success++; } printf ("\n"); fflush (stdout); } if (0 == num_failed) { if (0 == num_success) { fprintf (stderr, "No supported TLS version was found.\n"); fflush (stderr); return 77; } return 0; } return num_failed; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ test_append_prio = has_in_name (argv[0], "_append"); if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_all_supported_versions (); fflush (stderr); fflush (stdout); curl_global_cleanup (); if (77 == errorCount) return 77; else if (99 == errorCount) return 99; print_test_result (errorCount, argv[0]); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.2/src/testcurl/test_get_wait.c0000644000175000017500000001472714760713574016772 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_wait.c * @brief Test 'MHD_run_wait()' function. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test. * Check all three types of requests for HTTP/1.1: * * first request, new connection; * * "middle" request, existing connection with stay-alive; * * final request, no data processed after. */ #define ROUNDS 3 /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Set to 1 if the worker threads are done. */ static volatile int signal_done; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; unsigned int i; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); c = curl_easy_init (); if (NULL == c) _exit (99); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 15L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); for (i = 0; i < ROUNDS; i++) { if (CURLE_OK != (errornum = curl_easy_perform (c))) { signal_done = 1; fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); abort (); } } curl_easy_cleanup (c); signal_done = 1; return NULL; } static unsigned int testRunWaitGet (uint16_t port, uint32_t poll_flag) { pthread_t get_tid; struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "MHD_USE_AUTO" : (poll_flag & MHD_USE_POLL) ? "MHD_USE_POLL" : (poll_flag & MHD_USE_EPOLL) ? "MHD_USE_EPOLL" : "select()"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; printf ("Starting MHD_run_wait() test with MHD in %s polling mode.\n", test_desc); signal_done = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) abort (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) abort (); port = dinfo->port; } if (0 != pthread_create (&get_tid, NULL, &thread_gets, (void *) (intptr_t) port)) _exit (99); /* As another thread sets "done" flag after ending of network * activity, it's required to set positive timeout value for MHD_run_wait(). * Alternatively, to use timeout value "-1" here, another thread should start * additional connection to wake MHD after setting "done" flag. */ do { if (MHD_NO == MHD_run_wait (d, 50)) abort (); } while (0 == signal_done); if (0 != pthread_join (get_tid, NULL)) _exit (99); MHD_stop_daemon (d); printf ("Test succeeded.\n"); return 0; } int main (int argc, char *const *argv) { uint16_t port = 1675; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 5; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_static (strlen ("/hello_world"), "/hello_world"); testRunWaitGet (port++, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) testRunWaitGet (port++, MHD_USE_EPOLL); testRunWaitGet (port++, MHD_USE_AUTO); MHD_destroy_response (response); curl_global_cleanup (); return 0; /* Errors produce abort() or _exit() */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth_with_arguments.c0000644000175000017500000002252214760713574022440 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2012 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth_with_arguments.c * @brief Testcase for libmicrohttpd Digest Auth with arguments * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_MD5); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) fprintf (stderr, "MHD_create_response_from_buffer() failed.\n"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) fprintf (stderr, "MHD_queue_auth_fail_response2() failed.\n"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testDigestAuth (void) { CURL *c; CURLcode errornum; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; char url[128]; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1160; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", GetLastError ()); return 1; } b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (b == 0) return 1; } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/bar%%20foo?" "key=value&more=even%%20more&empty&=no_key&&same=one&&same=two", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) return 4; if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) return 8; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing" "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_quiesce_stream.c0000644000175000017500000001513214760713574020167 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_quiesce_stream.c * @brief Testcase for libmicrohttpd quiescing * @author Markus Doppelbauer * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include #include #ifdef HAVE_UNISTD_H #include #elif defined(_WIN32) #include #define sleep(s) (Sleep ((s) * 1000), 0) #endif /* _WIN32 */ static volatile unsigned int request_counter; _MHD_NORETURN static void http_PanicCallback (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; /* Unused. Silent compiler warning. */ fprintf (stderr, "PANIC: exit process: %s at %s:%u\n", reason, file, line); exit (EXIT_FAILURE); } static void * resume_connection (void *arg) { struct MHD_Connection *connection = arg; /* fprintf (stderr, "Calling resume\n"); */ MHD_resume_connection (connection); return NULL; } static void suspend_connection (struct MHD_Connection *connection) { pthread_t thread_id; int status; /* fprintf (stderr, "Calling suspend\n"); */ MHD_suspend_connection (connection); status = pthread_create (&thread_id, NULL, &resume_connection, connection); if (0 != status) { fprintf (stderr, "Could not create thead\n"); exit (EXIT_FAILURE); } pthread_detach (thread_id); } struct ContentReaderUserdata { size_t bytes_written; struct MHD_Connection *connection; }; static ssize_t http_ContentReaderCallback (void *cls, uint64_t pos, char *buf, size_t max) { static const char alphabet[] = "\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; struct ContentReaderUserdata *userdata = cls; (void) pos; (void) max; /* Unused. Silent compiler warning. */ if (userdata->bytes_written >= 1024) { fprintf (stderr, "finish: %u\n", request_counter); return MHD_CONTENT_READER_END_OF_STREAM; } userdata->bytes_written++; buf[0] = alphabet[userdata->bytes_written % (sizeof(alphabet) - 1)]; suspend_connection (userdata->connection); return 1; } static void free_crc_data (void *crc_data) { struct ContentReaderUserdata *userdata = crc_data; free (userdata); } static enum MHD_Result http_AccessHandlerCallback (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ /* Never respond on first call */ if (NULL == *req_cls) { struct ContentReaderUserdata *userdata; fprintf (stderr, "start: %u\n", ++request_counter); userdata = malloc (sizeof(struct ContentReaderUserdata)); if (NULL == userdata) return MHD_NO; userdata->bytes_written = 0; userdata->connection = connection; *req_cls = userdata; return MHD_YES; } /* Second call: create response */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &http_ContentReaderCallback, *req_cls, &free_crc_data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); suspend_connection (connection); return ret; } int main (void) { uint16_t port; char command_line[1024]; /* Flags */ unsigned int daemon_flags = MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_AUTO | MHD_ALLOW_SUSPEND_RESUME | MHD_USE_ITC; struct MHD_Daemon *daemon; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1470; /* Panic callback */ MHD_set_panic_func (&http_PanicCallback, NULL); /* Create daemon */ daemon = MHD_start_daemon (daemon_flags, port, NULL, NULL, &http_AccessHandlerCallback, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (daemon); return 32; } port = dinfo->port; } snprintf (command_line, sizeof (command_line), "curl -s http://127.0.0.1:%u", (unsigned int) port); if (0 != system (command_line)) { MHD_stop_daemon (daemon); return 1; } /* wait for a request */ while (0 == request_counter) (void) sleep (1); fprintf (stderr, "quiesce\n"); MHD_quiesce_daemon (daemon); /* wait a second */ (void) sleep (1); fprintf (stderr, "stopping daemon\n"); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.2/src/testcurl/test_post.c0000644000175000017500000005603314760713574016150 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_post.c * @brief Testcase for libmicrohttpd POST operations using URL-encoding * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define POST_DATA "name=daniel&project=curl" static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct MHD_PostProcessor *pp = *req_cls; (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */ if (NULL != pp) MHD_destroy_post_processor (pp); *req_cls = NULL; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * Note that this post_iterator is not perfect * in that it fails to support incremental processing. * (to be fixed in the future) */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { int *eok = cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) off; /* Unused. Silent compiler warning. */ if ((0 == strcmp (key, "name")) && (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size))) (*eok) |= 1; if ((0 == strcmp (key, "project")) && (size == strlen ("curl")) && (0 == strncmp (value, "curl", size))) (*eok) |= 2; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int eok; struct MHD_Response *response; struct MHD_PostProcessor *pp; enum MHD_Result ret; (void) cls; (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_POST, method)) { fprintf (stderr, "METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } pp = *req_cls; if (pp == NULL) { eok = 0; pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok); *req_cls = pp; } MHD_post_process (pp, upload_data, *upload_data_size); if ((eok == 3) && (0 == *upload_data_size)) { response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); MHD_destroy_post_processor (pp); *req_cls = NULL; return ret; } *upload_data_size = 0; return MHD_YES; } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1370; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1371; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1372; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1373; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } static enum MHD_Result ahc_cancel (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { fprintf (stderr, "Unexpected method `%s'\n", method); return MHD_NO; } if (*req_cls == NULL) { static int marker = 1; *req_cls = ▮ /* We don't want the body. Send a 500. */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, 500, response); if (ret != MHD_YES) fprintf (stderr, "Failed to queue response\n"); MHD_destroy_response (response); return ret; } else { fprintf (stderr, "In ahc_cancel again. This should not happen.\n"); return MHD_NO; } } struct CRBC { const char *buffer; size_t size; size_t pos; }; static size_t readBuffer (void *p, size_t size, size_t nmemb, void *opaque) { struct CRBC *data = opaque; size_t required = size * nmemb; size_t left = data->size - data->pos; if (required > left) required = left; memcpy (p, data->buffer + data->pos, required); data->pos += required; return required / size; } static size_t slowReadBuffer (void *p, size_t size, size_t nmemb, void *opaque) { (void) sleep (1); return readBuffer (p, size, nmemb, opaque); } #define FLAG_EXPECT_CONTINUE 1 #define FLAG_CHUNKED 2 #define FLAG_FORM_DATA 4 #define FLAG_SLOW_READ 8 #define FLAG_COUNT 16 static unsigned int testMultithreadedPostCancelPart (int flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct curl_slist *headers = NULL; long response_code; CURLcode cc; unsigned int result = 0; struct CRBC crbc; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1374; if (oneone) port += 10; } /* Don't test features that aren't available with HTTP/1.0 in * HTTP/1.0 mode. */ if (! oneone && (flags & (FLAG_EXPECT_CONTINUE | FLAG_CHUNKED))) return 0; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_cancel, NULL, MHD_OPTION_END); if (d == NULL) return 32768; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } crbc.buffer = "Test content"; crbc.size = strlen (crbc.buffer); crbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, (flags & FLAG_SLOW_READ) ? &slowReadBuffer : &readBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &crbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, crbc.size); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (flags & FLAG_CHUNKED) headers = curl_slist_append (headers, "Transfer-Encoding: chunked"); if (! (flags & FLAG_FORM_DATA)) headers = curl_slist_append (headers, "Content-Type: application/octet-stream"); if (flags & FLAG_EXPECT_CONTINUE) headers = curl_slist_append (headers, "Expect: 100-Continue"); curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers); if (CURLE_HTTP_RETURNED_ERROR != (errornum = curl_easy_perform (c))) { #ifdef _WIN32 curl_version_info_data *curlverd = curl_version_info (CURLVERSION_NOW); if ((0 != (flags & FLAG_SLOW_READ)) && (CURLE_RECV_ERROR == errornum) && ((curlverd == NULL) || (curlverd->ares_num < 0x073100) ) ) { /* libcurl up to version 7.49.0 didn't have workaround for WinSock bug */ fprintf (stderr, "Ignored curl_easy_perform expected failure on W32 with \"slow read\".\n"); result = 0; } else #else /* ! _WIN32 */ if (1) #endif /* ! _WIN32 */ { fprintf (stderr, "flibbet curl_easy_perform didn't fail as expected: `%s' %u\n", curl_easy_strerror (errornum), (unsigned int) errornum); result = 65536; } curl_easy_cleanup (c); MHD_stop_daemon (d); curl_slist_free_all (headers); return result; } if (CURLE_OK != (cc = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &response_code))) { fprintf (stderr, "curl_easy_getinfo failed: '%s'\n", curl_easy_strerror (cc)); result = 65536; } if (! result && (response_code != 500)) { fprintf (stderr, "Unexpected response code: %ld\n", response_code); result = 131072; } if (! result && (cbc.pos != 0)) result = 262144; curl_easy_cleanup (c); MHD_stop_daemon (d); curl_slist_free_all (headers); return result; } static unsigned int testMultithreadedPostCancel (void) { unsigned int result = 0; int flags; for (flags = 0; flags < FLAG_COUNT; ++flags) result |= testMultithreadedPostCancelPart (flags); return result; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testMultithreadedPostCancel (); errorCount += testInternalPost (); errorCount += testMultithreadedPost (); errorCount += testMultithreadedPoolPost (); } errorCount += testExternalPost (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_put_broken_len.c0000644000175000017500000005100514760713574020163 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_head.c * @brief Testcase for PUT requests with broken Content-Length header * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 500000 #define EXPECTED_URI_BASE_PATH "/" #define EXISTING_URI EXPECTED_URI_BASE_PATH #define EXPECTED_URI_BASE_PATH_MISSING "/wrong_uri" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define PAGE \ "libmicrohttpd demo page" \ "Success!" #define PAGE_404 \ "404 error" \ "Error 404: The requested URI does not exist" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static struct curl_slist *hdr_broken_cnt_len = NULL; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); hdr_broken_cnt_len = curl_slist_append (hdr_broken_cnt_len, MHD_HTTP_HEADER_CONTENT_LENGTH ": 123bad"); } static void test_global_cleanup (void) { curl_slist_free_all (hdr_broken_cnt_len); curl_global_cleanup (); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; /* Unused, mute compiler warning */ (void) ctx; /* Unused, mute compiler warning */ /* Discard data */ return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int http_code; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; if (0 == strcmp (url, EXISTING_URI)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); http_code = MHD_HTTP_OK; } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404), PAGE_404); http_code = MHD_HTTP_NOT_FOUND; } if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, http_code, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URI"); /* Set as a "custom" request, because no actual upload data is provided. */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, MHD_HTTP_METHOD_PUT)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, hdr_broken_cnt_len)) libcurlErrorExitDesc ("Cannot set '" MHD_HTTP_HEADER_CONTENT_LENGTH "'.\n"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code) { long code; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); return ! 0; } static unsigned int performTest (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4220 + oneone ? 0 : 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = MHD_HTTP_METHOD_PUT; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ cbc.pos = 0; /* Reset buffer position */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ cbc.pos = 0; /* Reset buffer position */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); test_global_init (); errorCount += performTest (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth.c0000644000175000017500000004121714760713574017322 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth.c * @brief Testcase for libmicrohttpd Digest Auth * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define MHD_URI_BASE_PATH "/bar%20foo%20without%20args" #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed"); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_MD5); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when digest authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); return c; } static unsigned int testDigestAuth (void) { CURL *c; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1165; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) externalErrorExitDesc ("Failed to open '/dev/urandom'"); while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) externalErrorExitDesc ("Failed to read '/dev/urandom'"); off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) externalErrorExitDesc ("CryptAcquireContext() failed"); b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) externalErrorExitDesc ("CryptGenRandom() failed"); CryptReleaseContext (cc, 0); } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } c = setupCURL (&cbc, port); checkCURLE_OK (curl_easy_perform (c)); curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/mhd_has_param.h0000644000175000017500000000327714760713577016721 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file testcurl/mhd_has_param.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether one of strings in array is equal to @a param. * String @a argv[0] is ignored. * @param argc number of strings in @a argv, as passed to main function * @param argv array of strings, as passed to main function * @param param parameter to look for. * @return zero if @a argv is NULL, @a param is NULL or empty string, * @a argc is less then 2 or @a param is not found in @a argv, * non-zero if one of strings in @a argv is equal to @a param. */ static int has_param (int argc, char *const argv[], const char *param) { int i; if (! argv || ! param || ! param[0]) return 0; for (i = 1; i < argc; i++) { if (argv[i] && (strcmp (argv[i], param) == 0) ) return ! 0; } return 0; } libmicrohttpd-1.0.2/src/testcurl/test_concurrent_stop.c0000644000175000017500000002325014760713574020405 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011, 2015, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_concurrent_stop.c * @brief test stopping server while concurrent GETs are ongoing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many requests do we do in parallel? */ #if SIZEOF_SIZE_T >= 8 || MHD_CPU_COUNT < 8 # define PAR (MHD_CPU_COUNT * 4) #elif MHD_CPU_COUNT < 16 /* Limit load */ # define PAR (MHD_CPU_COUNT * 2) #else /* Limit load */ # define PAR (MHD_CPU_COUNT * 1) #endif /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Continue generating new requests? */ static volatile int continue_requesting; /** * Continue waiting in watchdog thread? */ static volatile int watchdog_continue; static const char *watchdog_obj; /** * Indicate that client detected error */ static volatile CURLcode client_error; static void * thread_watchdog (void *param) { int seconds_passed; const int timeout_val = (int) (intptr_t) param; seconds_passed = 0; while (watchdog_continue) /* Poor threads sync, but works for testing. */ { if (0 == sleep (1)) /* Poor accuracy, but enough for testing. */ seconds_passed++; if (timeout_val < seconds_passed) { fprintf (stderr, "%s timeout expired.\n", watchdog_obj ? watchdog_obj : "Watchdog"); fflush (stderr); _exit (16); } } return NULL; } static pthread_t watchdog_tid; static void start_watchdog (int timeout, const char *obj_name) { watchdog_continue = 1; watchdog_obj = obj_name; if (0 != pthread_create (&watchdog_tid, NULL, &thread_watchdog, (void *) (intptr_t) timeout)) { fprintf (stderr, "Failed to start watchdog.\n"); _exit (99); } } static void stop_watchdog (void) { watchdog_continue = 0; if (0 != pthread_join (watchdog_tid, NULL)) { fprintf (stderr, "Failed to stop watchdog.\n"); _exit (99); } } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; char *const url = (char *) param; c = NULL; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init failed.\n"); _exit (99); } curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 2L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 2L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); while (continue_requesting) { errornum = curl_easy_perform (c); if (CURLE_OK != errornum) { curl_easy_cleanup (c); client_error = errornum; return NULL; } } curl_easy_cleanup (c); return NULL; } static void * do_gets (void *param) { int j; pthread_t par[PAR]; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); for (j = 0; j < PAR; j++) { if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url)) { fprintf (stderr, "pthread_create failed.\n"); continue_requesting = 0; for (j--; j >= 0; j--) { pthread_join (par[j], NULL); } _exit (99); } } (void) sleep (1); for (j = 0; j < PAR; j++) { pthread_join (par[j], NULL); } return NULL; } static pthread_t start_gets (uint16_t port) { pthread_t tid; continue_requesting = 1; if (0 != pthread_create (&tid, NULL, &do_gets, (void *) (intptr_t) port)) { fprintf (stderr, "pthread_create failed.\n"); _exit (99); } return tid; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; pthread_t p; unsigned int result; result = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } client_error = CURLE_OK; /* clear client error state */ p = start_gets (port); (void) sleep (1); start_watchdog (10, "daemon_stop() in testMultithreadedGet"); if (CURLE_OK != client_error) /* poor sync, but enough for test */ { result = 64; fprintf (stderr, "libcurl reported at least one error: \"%s\"\n", curl_easy_strerror (client_error)); } MHD_stop_daemon (d); stop_watchdog (); continue_requesting = 0; pthread_join (p, NULL); return result; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; pthread_t p; unsigned int result; result = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } client_error = CURLE_OK; /* clear client error state */ p = start_gets (port); (void) sleep (1); start_watchdog (10, "daemon_stop() in testMultithreadedPoolGet"); if (CURLE_OK != client_error) /* poor sync, but enough for test */ { result = 64; fprintf (stderr, "libcurl reported at least one error: \"%s\"\n", curl_easy_strerror (client_error)); } MHD_stop_daemon (d); stop_watchdog (); continue_requesting = 0; pthread_join (p, NULL); return result; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port; (void) argc; /* Unused. Silent compiler warning. */ (void) argv; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1142; /* Do reuse connection, otherwise all available local ports may exhausted. */ oneone = 1; if ((0 != port) && oneone) port += 5; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testMultithreadedGet (port, 0); if (0 != port) port++; errorCount += testMultithreadedPoolGet (port, 0); MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/Makefile.in0000644000175000017500000067203315035216310016007 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage @ENABLE_HTTPS_TRUE@am__append_2 = https @HEAVY_TESTS_TRUE@am__append_3 = \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup_nolisten \ @HEAVY_TESTS_TRUE@ test_timeout \ @HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_4 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ perf_get_concurrent11 \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@am__append_5 = \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait11 \ @HAVE_POSIX_THREADS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_6 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_concurrent_stop \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_quiesce \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_7 = \ @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_quiesce_stream @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_8 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ perf_get_concurrent @RUN_LIBCURL_TESTS_TRUE@check_PROGRAMS = test_get$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_head$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_head10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_iovec$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_sendfile$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_close$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_close10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_keep_alive$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_keep_alive10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_delete$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_patch$(EXEEXT) test_put$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_add_conn$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_add_conn_nolisten$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_process_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_process_arguments$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_method$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_url$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_header_name$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_header_value$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_header_name$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_header_value$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_tricky_url$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_tricky_header2$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_iovec11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_sendfile11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_patch11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put_inc11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_broken_len10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_broken_len$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_string$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_string$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_string_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_string_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_chunked$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_callback$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_large_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold_last$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold_large$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_large_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold_last$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold_large$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_1) $(am__EXEEXT_2) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_3) $(am__EXEEXT_4) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_5) $(am__EXEEXT_6) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_7) $(am__EXEEXT_8) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_18) $(am__EXEEXT_19) @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_9 = \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p2 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p1 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_zero \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n2 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n3 @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_10 = \ @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@ perf_get @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_11 = \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth test_basicauth_preauth \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_oldapi test_basicauth_preauth_oldapi @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_12 = \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post11 \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform11 \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop11 @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_13 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_with_arguments \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_concurrent @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_14 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_sha256 @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_15 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext_oldapi \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_all \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_uri \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_all \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_uri @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_16 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256 \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256 \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash_userdigest @HAVE_CURL_BINARY_TRUE@@HAVE_FORK_WAITPID_TRUE@@HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_17 = test_get_response_cleanup @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@am__append_18 = \ @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@ $(THREAD_ONLY_TESTS) @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@am__append_19 = \ @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@ $(THREAD_ONLY_TESTS) subdir = src/testcurl ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__EXEEXT_1 = @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_2 = test_parse_cookies_discp_p2$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p1$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_zero$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n2$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n3$(EXEEXT) @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_3 = \ @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@ perf_get$(EXEEXT) @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_4 = test_basicauth$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_preauth$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_oldapi$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_preauth_oldapi$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_5 = test_post$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post11$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform11$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop11$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_6 = test_digestauth_emu_ext$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext_oldapi$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_all$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_uri$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_all$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_uri$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_7 = test_digestauth2_sha256$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash_userdigest$(EXEEXT) @HAVE_CURL_BINARY_TRUE@@HAVE_FORK_WAITPID_TRUE@@HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_8 = test_get_response_cleanup$(EXEEXT) @HEAVY_TESTS_TRUE@am__EXEEXT_9 = test_add_conn_cleanup$(EXEEXT) \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup_nolisten$(EXEEXT) \ @HEAVY_TESTS_TRUE@ test_timeout$(EXEEXT) $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_10 = perf_get_concurrent11$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@am__EXEEXT_11 = test_get_wait$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait11$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@ $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_12 = test_concurrent_stop$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_quiesce$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(am__EXEEXT_1) @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_13 = test_quiesce_stream$(EXEEXT) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_14 = perf_get_concurrent$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_15 = test_digestauth$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_with_arguments$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_concurrent$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_16 = test_digestauth_sha256$(EXEEXT) am__EXEEXT_17 = test_urlparse$(EXEEXT) test_long_header$(EXEEXT) \ test_long_header11$(EXEEXT) test_iplimit11$(EXEEXT) \ test_termination$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_9) \ $(am__EXEEXT_10) $(am__EXEEXT_11) $(am__EXEEXT_12) \ $(am__EXEEXT_13) $(am__EXEEXT_14) $(am__EXEEXT_15) \ $(am__EXEEXT_16) @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@am__EXEEXT_18 = $(am__EXEEXT_17) @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@am__EXEEXT_19 = $(am__EXEEXT_17) am_perf_get_OBJECTS = perf_get.$(OBJEXT) perf_get_OBJECTS = $(am_perf_get_OBJECTS) perf_get_LDADD = $(LDADD) perf_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_perf_get_concurrent_OBJECTS = \ perf_get_concurrent-perf_get_concurrent.$(OBJEXT) perf_get_concurrent_OBJECTS = $(am_perf_get_concurrent_OBJECTS) am__DEPENDENCIES_1 = am__DEPENDENCIES_2 = $(top_builddir)/src/microhttpd/libmicrohttpd.la perf_get_concurrent_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) perf_get_concurrent_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(perf_get_concurrent_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_perf_get_concurrent11_OBJECTS = \ perf_get_concurrent11-perf_get_concurrent.$(OBJEXT) perf_get_concurrent11_OBJECTS = $(am_perf_get_concurrent11_OBJECTS) perf_get_concurrent11_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) perf_get_concurrent11_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(perf_get_concurrent11_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_add_conn_OBJECTS = test_add_conn-test_add_conn.$(OBJEXT) test_add_conn_OBJECTS = $(am_test_add_conn_OBJECTS) test_add_conn_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_add_conn_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_add_conn_cleanup_OBJECTS = \ test_add_conn_cleanup-test_add_conn.$(OBJEXT) test_add_conn_cleanup_OBJECTS = $(am_test_add_conn_cleanup_OBJECTS) test_add_conn_cleanup_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_cleanup_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_add_conn_cleanup_nolisten_OBJECTS = \ test_add_conn_cleanup_nolisten-test_add_conn.$(OBJEXT) test_add_conn_cleanup_nolisten_OBJECTS = \ $(am_test_add_conn_cleanup_nolisten_OBJECTS) test_add_conn_cleanup_nolisten_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_cleanup_nolisten_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_add_conn_nolisten_OBJECTS = \ test_add_conn_nolisten-test_add_conn.$(OBJEXT) test_add_conn_nolisten_OBJECTS = $(am_test_add_conn_nolisten_OBJECTS) test_add_conn_nolisten_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_nolisten_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_basicauth_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_OBJECTS = $(am_test_basicauth_OBJECTS) test_basicauth_LDADD = $(LDADD) test_basicauth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_oldapi_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_oldapi_OBJECTS = $(am_test_basicauth_oldapi_OBJECTS) test_basicauth_oldapi_LDADD = $(LDADD) test_basicauth_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_preauth_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_preauth_OBJECTS = $(am_test_basicauth_preauth_OBJECTS) test_basicauth_preauth_LDADD = $(LDADD) test_basicauth_preauth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_preauth_oldapi_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_preauth_oldapi_OBJECTS = \ $(am_test_basicauth_preauth_oldapi_OBJECTS) test_basicauth_preauth_oldapi_LDADD = $(LDADD) test_basicauth_preauth_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_callback_OBJECTS = test_callback.$(OBJEXT) test_callback_OBJECTS = $(am_test_callback_OBJECTS) test_callback_LDADD = $(LDADD) test_callback_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_concurrent_stop_OBJECTS = \ test_concurrent_stop-test_concurrent_stop.$(OBJEXT) test_concurrent_stop_OBJECTS = $(am_test_concurrent_stop_OBJECTS) test_concurrent_stop_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_concurrent_stop_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_concurrent_stop_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_delete_OBJECTS = test_delete.$(OBJEXT) test_delete_OBJECTS = $(am_test_delete_OBJECTS) test_delete_LDADD = $(LDADD) test_delete_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_OBJECTS = test_digestauth.$(OBJEXT) test_digestauth_OBJECTS = $(am_test_digestauth_OBJECTS) test_digestauth_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_digestauth2_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_OBJECTS = $(am_test_digestauth2_OBJECTS) test_digestauth2_LDADD = $(LDADD) test_digestauth2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_bind_all_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_bind_all_OBJECTS = \ $(am_test_digestauth2_bind_all_OBJECTS) test_digestauth2_bind_all_LDADD = $(LDADD) test_digestauth2_bind_all_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_bind_uri_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_bind_uri_OBJECTS = \ $(am_test_digestauth2_bind_uri_OBJECTS) test_digestauth2_bind_uri_LDADD = $(LDADD) test_digestauth2_bind_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_OBJECTS = \ $(am_test_digestauth2_oldapi1_OBJECTS) test_digestauth2_oldapi1_LDADD = $(LDADD) test_digestauth2_oldapi1_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_bind_all_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_bind_all_OBJECTS = \ $(am_test_digestauth2_oldapi1_bind_all_OBJECTS) test_digestauth2_oldapi1_bind_all_LDADD = $(LDADD) test_digestauth2_oldapi1_bind_all_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_bind_uri_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_bind_uri_OBJECTS = \ $(am_test_digestauth2_oldapi1_bind_uri_OBJECTS) test_digestauth2_oldapi1_bind_uri_LDADD = $(LDADD) test_digestauth2_oldapi1_bind_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi1_userdigest_OBJECTS) test_digestauth2_oldapi1_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi1_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_OBJECTS = \ $(am_test_digestauth2_oldapi2_OBJECTS) test_digestauth2_oldapi2_LDADD = $(LDADD) test_digestauth2_oldapi2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_sha256_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_sha256_OBJECTS = \ $(am_test_digestauth2_oldapi2_sha256_OBJECTS) test_digestauth2_oldapi2_sha256_LDADD = $(LDADD) test_digestauth2_oldapi2_sha256_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_sha256_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_sha256_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) test_digestauth2_oldapi2_sha256_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi2_userdigest_OBJECTS) test_digestauth2_oldapi2_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi2_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_rfc2069_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_rfc2069_OBJECTS = \ $(am_test_digestauth2_rfc2069_OBJECTS) test_digestauth2_rfc2069_LDADD = $(LDADD) test_digestauth2_rfc2069_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_rfc2069_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_rfc2069_userdigest_OBJECTS = \ $(am_test_digestauth2_rfc2069_userdigest_OBJECTS) test_digestauth2_rfc2069_userdigest_LDADD = $(LDADD) test_digestauth2_rfc2069_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_sha256_OBJECTS = \ $(am_test_digestauth2_sha256_OBJECTS) test_digestauth2_sha256_LDADD = $(LDADD) test_digestauth2_sha256_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userdigest_OBJECTS = \ $(am_test_digestauth2_sha256_userdigest_OBJECTS) test_digestauth2_sha256_userdigest_LDADD = $(LDADD) test_digestauth2_sha256_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userhash_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userhash_OBJECTS = \ $(am_test_digestauth2_sha256_userhash_OBJECTS) test_digestauth2_sha256_userhash_LDADD = $(LDADD) test_digestauth2_sha256_userhash_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userhash_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userhash_userdigest_OBJECTS = \ $(am_test_digestauth2_sha256_userhash_userdigest_OBJECTS) test_digestauth2_sha256_userhash_userdigest_LDADD = $(LDADD) test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userdigest_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_userdigest_OBJECTS = \ $(am_test_digestauth2_userdigest_OBJECTS) test_digestauth2_userdigest_LDADD = $(LDADD) test_digestauth2_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userhash_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_userhash_OBJECTS = \ $(am_test_digestauth2_userhash_OBJECTS) test_digestauth2_userhash_LDADD = $(LDADD) test_digestauth2_userhash_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userhash_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_userhash_userdigest_OBJECTS = \ $(am_test_digestauth2_userhash_userdigest_OBJECTS) test_digestauth2_userhash_userdigest_LDADD = $(LDADD) test_digestauth2_userhash_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_concurrent_OBJECTS = test_digestauth_concurrent-test_digestauth_concurrent.$(OBJEXT) test_digestauth_concurrent_OBJECTS = \ $(am_test_digestauth_concurrent_OBJECTS) test_digestauth_concurrent_DEPENDENCIES = $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) test_digestauth_concurrent_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_digestauth_emu_ext_OBJECTS = \ test_digestauth_emu_ext.$(OBJEXT) test_digestauth_emu_ext_OBJECTS = \ $(am_test_digestauth_emu_ext_OBJECTS) test_digestauth_emu_ext_LDADD = $(LDADD) test_digestauth_emu_ext_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_emu_ext_oldapi_OBJECTS = \ test_digestauth_emu_ext.$(OBJEXT) test_digestauth_emu_ext_oldapi_OBJECTS = \ $(am_test_digestauth_emu_ext_oldapi_OBJECTS) test_digestauth_emu_ext_oldapi_LDADD = $(LDADD) test_digestauth_emu_ext_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_sha256_OBJECTS = test_digestauth_sha256.$(OBJEXT) test_digestauth_sha256_OBJECTS = $(am_test_digestauth_sha256_OBJECTS) test_digestauth_sha256_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_digestauth_with_arguments_OBJECTS = \ test_digestauth_with_arguments.$(OBJEXT) test_digestauth_with_arguments_OBJECTS = \ $(am_test_digestauth_with_arguments_OBJECTS) test_digestauth_with_arguments_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_get_OBJECTS = test_get.$(OBJEXT) test_get_OBJECTS = $(am_test_get_OBJECTS) test_get_LDADD = $(LDADD) test_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get11_OBJECTS = test_get.$(OBJEXT) test_get11_OBJECTS = $(am_test_get11_OBJECTS) test_get11_LDADD = $(LDADD) test_get11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS) test_get_chunked_LDADD = $(LDADD) test_get_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_OBJECTS = $(am_test_get_chunked_close_OBJECTS) test_get_chunked_close_LDADD = $(LDADD) test_get_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_OBJECTS = \ $(am_test_get_chunked_close_empty_OBJECTS) test_get_chunked_close_empty_LDADD = $(LDADD) test_get_chunked_close_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_forced_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_forced_OBJECTS = \ $(am_test_get_chunked_close_empty_forced_OBJECTS) test_get_chunked_close_empty_forced_LDADD = $(LDADD) test_get_chunked_close_empty_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_sized_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_sized_OBJECTS = \ $(am_test_get_chunked_close_empty_sized_OBJECTS) test_get_chunked_close_empty_sized_LDADD = $(LDADD) test_get_chunked_close_empty_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_forced_OBJECTS = \ $(am_test_get_chunked_close_forced_OBJECTS) test_get_chunked_close_forced_LDADD = $(LDADD) test_get_chunked_close_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_sized_OBJECTS = \ $(am_test_get_chunked_close_sized_OBJECTS) test_get_chunked_close_sized_LDADD = $(LDADD) test_get_chunked_close_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_string_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_string_OBJECTS = \ $(am_test_get_chunked_close_string_OBJECTS) test_get_chunked_close_string_LDADD = $(LDADD) test_get_chunked_close_string_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_string_empty_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_string_empty_OBJECTS = \ $(am_test_get_chunked_close_string_empty_OBJECTS) test_get_chunked_close_string_empty_LDADD = $(LDADD) test_get_chunked_close_string_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_OBJECTS = $(am_test_get_chunked_empty_OBJECTS) test_get_chunked_empty_LDADD = $(LDADD) test_get_chunked_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_forced_OBJECTS = \ $(am_test_get_chunked_empty_forced_OBJECTS) test_get_chunked_empty_forced_LDADD = $(LDADD) test_get_chunked_empty_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_sized_OBJECTS = \ $(am_test_get_chunked_empty_sized_OBJECTS) test_get_chunked_empty_sized_LDADD = $(LDADD) test_get_chunked_empty_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_forced_OBJECTS = \ $(am_test_get_chunked_forced_OBJECTS) test_get_chunked_forced_LDADD = $(LDADD) test_get_chunked_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_sized_OBJECTS = $(am_test_get_chunked_sized_OBJECTS) test_get_chunked_sized_LDADD = $(LDADD) test_get_chunked_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_string_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_string_OBJECTS = \ $(am_test_get_chunked_string_OBJECTS) test_get_chunked_string_LDADD = $(LDADD) test_get_chunked_string_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_string_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_string_empty_OBJECTS = \ $(am_test_get_chunked_string_empty_OBJECTS) test_get_chunked_string_empty_LDADD = $(LDADD) test_get_chunked_string_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_close_OBJECTS = $(am_test_get_close_OBJECTS) test_get_close_LDADD = $(LDADD) test_get_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close10_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_close10_OBJECTS = $(am_test_get_close10_OBJECTS) test_get_close10_LDADD = $(LDADD) test_get_close10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_1 = test_put_header_fold.$(OBJEXT) am_test_get_header_double_fold_OBJECTS = $(am__objects_1) test_get_header_double_fold_OBJECTS = \ $(am_test_get_header_double_fold_OBJECTS) test_get_header_double_fold_LDADD = $(LDADD) test_get_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_header_fold_OBJECTS = $(am__objects_1) test_get_header_fold_OBJECTS = $(am_test_get_header_fold_OBJECTS) test_get_header_fold_LDADD = $(LDADD) test_get_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_iovec_OBJECTS = test_get_iovec.$(OBJEXT) test_get_iovec_OBJECTS = $(am_test_get_iovec_OBJECTS) test_get_iovec_LDADD = $(LDADD) test_get_iovec_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_iovec11_OBJECTS = test_get_iovec.$(OBJEXT) test_get_iovec11_OBJECTS = $(am_test_get_iovec11_OBJECTS) test_get_iovec11_LDADD = $(LDADD) test_get_iovec11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_keep_alive_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_keep_alive_OBJECTS = $(am_test_get_keep_alive_OBJECTS) test_get_keep_alive_LDADD = $(LDADD) test_get_keep_alive_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_keep_alive10_OBJECTS = \ test_get_close_keep_alive.$(OBJEXT) test_get_keep_alive10_OBJECTS = $(am_test_get_keep_alive10_OBJECTS) test_get_keep_alive10_LDADD = $(LDADD) test_get_keep_alive10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_response_cleanup_OBJECTS = \ test_get_response_cleanup.$(OBJEXT) test_get_response_cleanup_OBJECTS = \ $(am_test_get_response_cleanup_OBJECTS) test_get_response_cleanup_LDADD = $(LDADD) test_get_response_cleanup_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_sendfile_OBJECTS = test_get_sendfile.$(OBJEXT) test_get_sendfile_OBJECTS = $(am_test_get_sendfile_OBJECTS) test_get_sendfile_LDADD = $(LDADD) test_get_sendfile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_sendfile11_OBJECTS = test_get_sendfile.$(OBJEXT) test_get_sendfile11_OBJECTS = $(am_test_get_sendfile11_OBJECTS) test_get_sendfile11_LDADD = $(LDADD) test_get_sendfile11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_wait_OBJECTS = test_get_wait-test_get_wait.$(OBJEXT) test_get_wait_OBJECTS = $(am_test_get_wait_OBJECTS) test_get_wait_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_get_wait_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_get_wait_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_get_wait11_OBJECTS = test_get_wait11-test_get_wait.$(OBJEXT) test_get_wait11_OBJECTS = $(am_test_get_wait11_OBJECTS) test_get_wait11_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_get_wait11_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_get_wait11_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ am_test_head_OBJECTS = test_head.$(OBJEXT) test_head_OBJECTS = $(am_test_head_OBJECTS) test_head_LDADD = $(LDADD) test_head_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_head10_OBJECTS = test_head.$(OBJEXT) test_head10_OBJECTS = $(am_test_head10_OBJECTS) test_head10_LDADD = $(LDADD) test_head10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_iplimit11_OBJECTS = test_iplimit.$(OBJEXT) test_iplimit11_OBJECTS = $(am_test_iplimit11_OBJECTS) test_iplimit11_LDADD = $(LDADD) test_iplimit11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put_OBJECTS = test_large_put.$(OBJEXT) test_large_put_OBJECTS = $(am_test_large_put_OBJECTS) test_large_put_LDADD = $(LDADD) test_large_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put11_OBJECTS = test_large_put.$(OBJEXT) test_large_put11_OBJECTS = $(am_test_large_put11_OBJECTS) test_large_put11_LDADD = $(LDADD) test_large_put11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put_inc11_OBJECTS = test_large_put.$(OBJEXT) test_large_put_inc11_OBJECTS = $(am_test_large_put_inc11_OBJECTS) test_large_put_inc11_LDADD = $(LDADD) test_large_put_inc11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_long_header_OBJECTS = test_long_header.$(OBJEXT) test_long_header_OBJECTS = $(am_test_long_header_OBJECTS) test_long_header_LDADD = $(LDADD) test_long_header_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_long_header11_OBJECTS = test_long_header.$(OBJEXT) test_long_header11_OBJECTS = $(am_test_long_header11_OBJECTS) test_long_header11_LDADD = $(LDADD) test_long_header11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_2 = test_parse_cookies.$(OBJEXT) am_test_parse_cookies_discp_n2_OBJECTS = $(am__objects_2) test_parse_cookies_discp_n2_OBJECTS = \ $(am_test_parse_cookies_discp_n2_OBJECTS) test_parse_cookies_discp_n2_LDADD = $(LDADD) test_parse_cookies_discp_n2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_n3_OBJECTS = $(am__objects_2) test_parse_cookies_discp_n3_OBJECTS = \ $(am_test_parse_cookies_discp_n3_OBJECTS) test_parse_cookies_discp_n3_LDADD = $(LDADD) test_parse_cookies_discp_n3_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_p1_OBJECTS = $(am__objects_2) test_parse_cookies_discp_p1_OBJECTS = \ $(am_test_parse_cookies_discp_p1_OBJECTS) test_parse_cookies_discp_p1_LDADD = $(LDADD) test_parse_cookies_discp_p1_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_p2_OBJECTS = $(am__objects_2) test_parse_cookies_discp_p2_OBJECTS = \ $(am_test_parse_cookies_discp_p2_OBJECTS) test_parse_cookies_discp_p2_LDADD = $(LDADD) test_parse_cookies_discp_p2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_zero_OBJECTS = \ test_parse_cookies.$(OBJEXT) test_parse_cookies_discp_zero_OBJECTS = \ $(am_test_parse_cookies_discp_zero_OBJECTS) test_parse_cookies_discp_zero_LDADD = $(LDADD) test_parse_cookies_discp_zero_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_patch_OBJECTS = test_patch.$(OBJEXT) test_patch_OBJECTS = $(am_test_patch_OBJECTS) test_patch_LDADD = $(LDADD) test_patch_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_patch11_OBJECTS = test_patch.$(OBJEXT) test_patch11_OBJECTS = $(am_test_patch11_OBJECTS) test_patch11_LDADD = $(LDADD) test_patch11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_OBJECTS = test_post.$(OBJEXT) test_post_OBJECTS = $(am_test_post_OBJECTS) test_post_LDADD = $(LDADD) test_post_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post11_OBJECTS = test_post.$(OBJEXT) test_post11_OBJECTS = $(am_test_post11_OBJECTS) test_post11_LDADD = $(LDADD) test_post11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_loop_OBJECTS = test_post_loop.$(OBJEXT) test_post_loop_OBJECTS = $(am_test_post_loop_OBJECTS) test_post_loop_LDADD = $(LDADD) test_post_loop_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_loop11_OBJECTS = test_post_loop.$(OBJEXT) test_post_loop11_OBJECTS = $(am_test_post_loop11_OBJECTS) test_post_loop11_LDADD = $(LDADD) test_post_loop11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_postform_OBJECTS = test_postform.$(OBJEXT) test_postform_OBJECTS = $(am_test_postform_OBJECTS) test_postform_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_postform11_OBJECTS = test_postform.$(OBJEXT) test_postform11_OBJECTS = $(am_test_postform11_OBJECTS) test_postform11_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_process_arguments_OBJECTS = test_process_arguments.$(OBJEXT) test_process_arguments_OBJECTS = $(am_test_process_arguments_OBJECTS) test_process_arguments_LDADD = $(LDADD) test_process_arguments_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_process_headers_OBJECTS = test_process_headers.$(OBJEXT) test_process_headers_OBJECTS = $(am_test_process_headers_OBJECTS) test_process_headers_LDADD = $(LDADD) test_process_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_OBJECTS = test_put.$(OBJEXT) test_put_OBJECTS = $(am_test_put_OBJECTS) test_put_LDADD = $(LDADD) test_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put11_OBJECTS = test_put.$(OBJEXT) test_put11_OBJECTS = $(am_test_put11_OBJECTS) test_put11_LDADD = $(LDADD) test_put11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_broken_len_OBJECTS = test_put_broken_len.$(OBJEXT) test_put_broken_len_OBJECTS = $(am_test_put_broken_len_OBJECTS) test_put_broken_len_LDADD = $(LDADD) test_put_broken_len_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_3 = test_put_broken_len.$(OBJEXT) am_test_put_broken_len10_OBJECTS = $(am__objects_3) test_put_broken_len10_OBJECTS = $(am_test_put_broken_len10_OBJECTS) test_put_broken_len10_LDADD = $(LDADD) test_put_broken_len10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_OBJECTS = test_put_chunked.$(OBJEXT) test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS) test_put_chunked_LDADD = $(LDADD) test_put_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_double_fold_OBJECTS = $(am__objects_1) test_put_header_double_fold_OBJECTS = \ $(am_test_put_header_double_fold_OBJECTS) test_put_header_double_fold_LDADD = $(LDADD) test_put_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_4 = $(am__objects_1) am_test_put_header_double_fold_large_OBJECTS = $(am__objects_4) test_put_header_double_fold_large_OBJECTS = \ $(am_test_put_header_double_fold_large_OBJECTS) test_put_header_double_fold_large_LDADD = $(LDADD) test_put_header_double_fold_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_double_fold_last_OBJECTS = $(am__objects_4) test_put_header_double_fold_last_OBJECTS = \ $(am_test_put_header_double_fold_last_OBJECTS) test_put_header_double_fold_last_LDADD = $(LDADD) test_put_header_double_fold_last_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_OBJECTS = test_put_header_fold.$(OBJEXT) test_put_header_fold_OBJECTS = $(am_test_put_header_fold_OBJECTS) test_put_header_fold_LDADD = $(LDADD) test_put_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_large_OBJECTS = $(am__objects_1) test_put_header_fold_large_OBJECTS = \ $(am_test_put_header_fold_large_OBJECTS) test_put_header_fold_large_LDADD = $(LDADD) test_put_header_fold_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_last_OBJECTS = $(am__objects_1) test_put_header_fold_last_OBJECTS = \ $(am_test_put_header_fold_last_OBJECTS) test_put_header_fold_last_LDADD = $(LDADD) test_put_header_fold_last_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_header_double_fold_OBJECTS = $(am__objects_4) test_put_large_header_double_fold_OBJECTS = \ $(am_test_put_large_header_double_fold_OBJECTS) test_put_large_header_double_fold_LDADD = $(LDADD) test_put_large_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_header_fold_OBJECTS = $(am__objects_1) test_put_large_header_fold_OBJECTS = \ $(am_test_put_large_header_fold_OBJECTS) test_put_large_header_fold_LDADD = $(LDADD) test_put_large_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_quiesce_OBJECTS = test_quiesce-test_quiesce.$(OBJEXT) test_quiesce_OBJECTS = $(am_test_quiesce_OBJECTS) test_quiesce_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_quiesce_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_quiesce_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_quiesce_stream_OBJECTS = \ test_quiesce_stream-test_quiesce_stream.$(OBJEXT) test_quiesce_stream_OBJECTS = $(am_test_quiesce_stream_OBJECTS) test_quiesce_stream_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_quiesce_stream_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_quiesce_stream_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_termination_OBJECTS = test_termination.$(OBJEXT) test_termination_OBJECTS = $(am_test_termination_OBJECTS) test_termination_LDADD = $(LDADD) test_termination_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_timeout_OBJECTS = test_timeout.$(OBJEXT) test_timeout_OBJECTS = $(am_test_timeout_OBJECTS) test_timeout_LDADD = $(LDADD) test_timeout_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_method_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_method_OBJECTS = $(am_test_toolarge_method_OBJECTS) test_toolarge_method_LDADD = $(LDADD) test_toolarge_method_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_header_name_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_header_name_OBJECTS = \ $(am_test_toolarge_reply_header_name_OBJECTS) test_toolarge_reply_header_name_LDADD = $(LDADD) test_toolarge_reply_header_name_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_header_value_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_header_value_OBJECTS = \ $(am_test_toolarge_reply_header_value_OBJECTS) test_toolarge_reply_header_value_LDADD = $(LDADD) test_toolarge_reply_header_value_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_headers_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_headers_OBJECTS = \ $(am_test_toolarge_reply_headers_OBJECTS) test_toolarge_reply_headers_LDADD = $(LDADD) test_toolarge_reply_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_header_name_OBJECTS = \ test_toolarge.$(OBJEXT) test_toolarge_request_header_name_OBJECTS = \ $(am_test_toolarge_request_header_name_OBJECTS) test_toolarge_request_header_name_LDADD = $(LDADD) test_toolarge_request_header_name_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_header_value_OBJECTS = \ test_toolarge.$(OBJEXT) test_toolarge_request_header_value_OBJECTS = \ $(am_test_toolarge_request_header_value_OBJECTS) test_toolarge_request_header_value_LDADD = $(LDADD) test_toolarge_request_header_value_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_headers_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_request_headers_OBJECTS = \ $(am_test_toolarge_request_headers_OBJECTS) test_toolarge_request_headers_LDADD = $(LDADD) test_toolarge_request_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_url_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_url_OBJECTS = $(am_test_toolarge_url_OBJECTS) test_toolarge_url_LDADD = $(LDADD) test_toolarge_url_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_tricky_header2_OBJECTS = test_tricky.$(OBJEXT) test_tricky_header2_OBJECTS = $(am_test_tricky_header2_OBJECTS) test_tricky_header2_LDADD = $(LDADD) test_tricky_header2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_tricky_url_OBJECTS = test_tricky.$(OBJEXT) test_tricky_url_OBJECTS = $(am_test_tricky_url_OBJECTS) test_tricky_url_LDADD = $(LDADD) test_tricky_url_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_urlparse_OBJECTS = test_urlparse.$(OBJEXT) test_urlparse_OBJECTS = $(am_test_urlparse_OBJECTS) test_urlparse_LDADD = $(LDADD) test_urlparse_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/perf_get.Po \ ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po \ ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po \ ./$(DEPDIR)/test_add_conn-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po \ ./$(DEPDIR)/test_basicauth.Po ./$(DEPDIR)/test_callback.Po \ ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po \ ./$(DEPDIR)/test_delete.Po ./$(DEPDIR)/test_digestauth.Po \ ./$(DEPDIR)/test_digestauth2.Po \ ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po \ ./$(DEPDIR)/test_digestauth_emu_ext.Po \ ./$(DEPDIR)/test_digestauth_sha256.Po \ ./$(DEPDIR)/test_digestauth_with_arguments.Po \ ./$(DEPDIR)/test_get.Po ./$(DEPDIR)/test_get_chunked.Po \ ./$(DEPDIR)/test_get_close_keep_alive.Po \ ./$(DEPDIR)/test_get_iovec.Po \ ./$(DEPDIR)/test_get_response_cleanup.Po \ ./$(DEPDIR)/test_get_sendfile.Po \ ./$(DEPDIR)/test_get_wait-test_get_wait.Po \ ./$(DEPDIR)/test_get_wait11-test_get_wait.Po \ ./$(DEPDIR)/test_head.Po ./$(DEPDIR)/test_iplimit.Po \ ./$(DEPDIR)/test_large_put.Po ./$(DEPDIR)/test_long_header.Po \ ./$(DEPDIR)/test_parse_cookies.Po ./$(DEPDIR)/test_patch.Po \ ./$(DEPDIR)/test_post.Po ./$(DEPDIR)/test_post_loop.Po \ ./$(DEPDIR)/test_postform.Po \ ./$(DEPDIR)/test_process_arguments.Po \ ./$(DEPDIR)/test_process_headers.Po ./$(DEPDIR)/test_put.Po \ ./$(DEPDIR)/test_put_broken_len.Po \ ./$(DEPDIR)/test_put_chunked.Po \ ./$(DEPDIR)/test_put_header_fold.Po \ ./$(DEPDIR)/test_quiesce-test_quiesce.Po \ ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po \ ./$(DEPDIR)/test_termination.Po ./$(DEPDIR)/test_timeout.Po \ ./$(DEPDIR)/test_toolarge.Po ./$(DEPDIR)/test_tricky.Po \ ./$(DEPDIR)/test_urlparse.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(perf_get_SOURCES) $(perf_get_concurrent_SOURCES) \ $(perf_get_concurrent11_SOURCES) $(test_add_conn_SOURCES) \ $(test_add_conn_cleanup_SOURCES) \ $(test_add_conn_cleanup_nolisten_SOURCES) \ $(test_add_conn_nolisten_SOURCES) $(test_basicauth_SOURCES) \ $(test_basicauth_oldapi_SOURCES) \ $(test_basicauth_preauth_SOURCES) \ $(test_basicauth_preauth_oldapi_SOURCES) \ $(test_callback_SOURCES) $(test_concurrent_stop_SOURCES) \ $(test_delete_SOURCES) $(test_digestauth_SOURCES) \ $(test_digestauth2_SOURCES) \ $(test_digestauth2_bind_all_SOURCES) \ $(test_digestauth2_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_SOURCES) \ $(test_digestauth2_oldapi1_bind_all_SOURCES) \ $(test_digestauth2_oldapi1_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_SOURCES) \ $(test_digestauth2_oldapi2_sha256_SOURCES) \ $(test_digestauth2_oldapi2_sha256_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_userdigest_SOURCES) \ $(test_digestauth2_rfc2069_SOURCES) \ $(test_digestauth2_rfc2069_userdigest_SOURCES) \ $(test_digestauth2_sha256_SOURCES) \ $(test_digestauth2_sha256_userdigest_SOURCES) \ $(test_digestauth2_sha256_userhash_SOURCES) \ $(test_digestauth2_sha256_userhash_userdigest_SOURCES) \ $(test_digestauth2_userdigest_SOURCES) \ $(test_digestauth2_userhash_SOURCES) \ $(test_digestauth2_userhash_userdigest_SOURCES) \ $(test_digestauth_concurrent_SOURCES) \ $(test_digestauth_emu_ext_SOURCES) \ $(test_digestauth_emu_ext_oldapi_SOURCES) \ $(test_digestauth_sha256_SOURCES) \ $(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \ $(test_get11_SOURCES) $(test_get_chunked_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_close_empty_SOURCES) \ $(test_get_chunked_close_empty_forced_SOURCES) \ $(test_get_chunked_close_empty_sized_SOURCES) \ $(test_get_chunked_close_forced_SOURCES) \ $(test_get_chunked_close_sized_SOURCES) \ $(test_get_chunked_close_string_SOURCES) \ $(test_get_chunked_close_string_empty_SOURCES) \ $(test_get_chunked_empty_SOURCES) \ $(test_get_chunked_empty_forced_SOURCES) \ $(test_get_chunked_empty_sized_SOURCES) \ $(test_get_chunked_forced_SOURCES) \ $(test_get_chunked_sized_SOURCES) \ $(test_get_chunked_string_SOURCES) \ $(test_get_chunked_string_empty_SOURCES) \ $(test_get_close_SOURCES) $(test_get_close10_SOURCES) \ $(test_get_header_double_fold_SOURCES) \ $(test_get_header_fold_SOURCES) $(test_get_iovec_SOURCES) \ $(test_get_iovec11_SOURCES) $(test_get_keep_alive_SOURCES) \ $(test_get_keep_alive10_SOURCES) \ $(test_get_response_cleanup_SOURCES) \ $(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \ $(test_get_wait_SOURCES) $(test_get_wait11_SOURCES) \ $(test_head_SOURCES) $(test_head10_SOURCES) \ $(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \ $(test_large_put11_SOURCES) $(test_large_put_inc11_SOURCES) \ $(test_long_header_SOURCES) $(test_long_header11_SOURCES) \ $(test_parse_cookies_discp_n2_SOURCES) \ $(test_parse_cookies_discp_n3_SOURCES) \ $(test_parse_cookies_discp_p1_SOURCES) \ $(test_parse_cookies_discp_p2_SOURCES) \ $(test_parse_cookies_discp_zero_SOURCES) $(test_patch_SOURCES) \ $(test_patch11_SOURCES) $(test_post_SOURCES) \ $(test_post11_SOURCES) $(test_post_loop_SOURCES) \ $(test_post_loop11_SOURCES) $(test_postform_SOURCES) \ $(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \ $(test_process_headers_SOURCES) $(test_put_SOURCES) \ $(test_put11_SOURCES) $(test_put_broken_len_SOURCES) \ $(test_put_broken_len10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_header_double_fold_SOURCES) \ $(test_put_header_double_fold_large_SOURCES) \ $(test_put_header_double_fold_last_SOURCES) \ $(test_put_header_fold_SOURCES) \ $(test_put_header_fold_large_SOURCES) \ $(test_put_header_fold_last_SOURCES) \ $(test_put_large_header_double_fold_SOURCES) \ $(test_put_large_header_fold_SOURCES) $(test_quiesce_SOURCES) \ $(test_quiesce_stream_SOURCES) $(test_termination_SOURCES) \ $(test_timeout_SOURCES) $(test_toolarge_method_SOURCES) \ $(test_toolarge_reply_header_name_SOURCES) \ $(test_toolarge_reply_header_value_SOURCES) \ $(test_toolarge_reply_headers_SOURCES) \ $(test_toolarge_request_header_name_SOURCES) \ $(test_toolarge_request_header_value_SOURCES) \ $(test_toolarge_request_headers_SOURCES) \ $(test_toolarge_url_SOURCES) $(test_tricky_header2_SOURCES) \ $(test_tricky_url_SOURCES) $(test_urlparse_SOURCES) DIST_SOURCES = $(perf_get_SOURCES) $(perf_get_concurrent_SOURCES) \ $(perf_get_concurrent11_SOURCES) $(test_add_conn_SOURCES) \ $(test_add_conn_cleanup_SOURCES) \ $(test_add_conn_cleanup_nolisten_SOURCES) \ $(test_add_conn_nolisten_SOURCES) $(test_basicauth_SOURCES) \ $(test_basicauth_oldapi_SOURCES) \ $(test_basicauth_preauth_SOURCES) \ $(test_basicauth_preauth_oldapi_SOURCES) \ $(test_callback_SOURCES) $(test_concurrent_stop_SOURCES) \ $(test_delete_SOURCES) $(test_digestauth_SOURCES) \ $(test_digestauth2_SOURCES) \ $(test_digestauth2_bind_all_SOURCES) \ $(test_digestauth2_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_SOURCES) \ $(test_digestauth2_oldapi1_bind_all_SOURCES) \ $(test_digestauth2_oldapi1_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_SOURCES) \ $(test_digestauth2_oldapi2_sha256_SOURCES) \ $(test_digestauth2_oldapi2_sha256_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_userdigest_SOURCES) \ $(test_digestauth2_rfc2069_SOURCES) \ $(test_digestauth2_rfc2069_userdigest_SOURCES) \ $(test_digestauth2_sha256_SOURCES) \ $(test_digestauth2_sha256_userdigest_SOURCES) \ $(test_digestauth2_sha256_userhash_SOURCES) \ $(test_digestauth2_sha256_userhash_userdigest_SOURCES) \ $(test_digestauth2_userdigest_SOURCES) \ $(test_digestauth2_userhash_SOURCES) \ $(test_digestauth2_userhash_userdigest_SOURCES) \ $(test_digestauth_concurrent_SOURCES) \ $(test_digestauth_emu_ext_SOURCES) \ $(test_digestauth_emu_ext_oldapi_SOURCES) \ $(test_digestauth_sha256_SOURCES) \ $(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \ $(test_get11_SOURCES) $(test_get_chunked_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_close_empty_SOURCES) \ $(test_get_chunked_close_empty_forced_SOURCES) \ $(test_get_chunked_close_empty_sized_SOURCES) \ $(test_get_chunked_close_forced_SOURCES) \ $(test_get_chunked_close_sized_SOURCES) \ $(test_get_chunked_close_string_SOURCES) \ $(test_get_chunked_close_string_empty_SOURCES) \ $(test_get_chunked_empty_SOURCES) \ $(test_get_chunked_empty_forced_SOURCES) \ $(test_get_chunked_empty_sized_SOURCES) \ $(test_get_chunked_forced_SOURCES) \ $(test_get_chunked_sized_SOURCES) \ $(test_get_chunked_string_SOURCES) \ $(test_get_chunked_string_empty_SOURCES) \ $(test_get_close_SOURCES) $(test_get_close10_SOURCES) \ $(test_get_header_double_fold_SOURCES) \ $(test_get_header_fold_SOURCES) $(test_get_iovec_SOURCES) \ $(test_get_iovec11_SOURCES) $(test_get_keep_alive_SOURCES) \ $(test_get_keep_alive10_SOURCES) \ $(test_get_response_cleanup_SOURCES) \ $(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \ $(test_get_wait_SOURCES) $(test_get_wait11_SOURCES) \ $(test_head_SOURCES) $(test_head10_SOURCES) \ $(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \ $(test_large_put11_SOURCES) $(test_large_put_inc11_SOURCES) \ $(test_long_header_SOURCES) $(test_long_header11_SOURCES) \ $(test_parse_cookies_discp_n2_SOURCES) \ $(test_parse_cookies_discp_n3_SOURCES) \ $(test_parse_cookies_discp_p1_SOURCES) \ $(test_parse_cookies_discp_p2_SOURCES) \ $(test_parse_cookies_discp_zero_SOURCES) $(test_patch_SOURCES) \ $(test_patch11_SOURCES) $(test_post_SOURCES) \ $(test_post11_SOURCES) $(test_post_loop_SOURCES) \ $(test_post_loop11_SOURCES) $(test_postform_SOURCES) \ $(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \ $(test_process_headers_SOURCES) $(test_put_SOURCES) \ $(test_put11_SOURCES) $(test_put_broken_len_SOURCES) \ $(test_put_broken_len10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_header_double_fold_SOURCES) \ $(test_put_header_double_fold_large_SOURCES) \ $(test_put_header_double_fold_last_SOURCES) \ $(test_put_header_fold_SOURCES) \ $(test_put_header_fold_large_SOURCES) \ $(test_put_header_fold_last_SOURCES) \ $(test_put_large_header_double_fold_SOURCES) \ $(test_put_large_header_fold_SOURCES) $(test_quiesce_SOURCES) \ $(test_quiesce_stream_SOURCES) $(test_termination_SOURCES) \ $(test_timeout_SOURCES) $(test_toolarge_method_SOURCES) \ $(test_toolarge_reply_header_name_SOURCES) \ $(test_toolarge_reply_header_value_SOURCES) \ $(test_toolarge_reply_headers_SOURCES) \ $(test_toolarge_request_header_name_SOURCES) \ $(test_toolarge_request_header_value_SOURCES) \ $(test_toolarge_request_headers_SOURCES) \ $(test_toolarge_url_SOURCES) $(test_tricky_header2_SOURCES) \ $(test_tricky_url_SOURCES) $(test_urlparse_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = . https am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . $(am__append_2) AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ THREAD_ONLY_TESTS = test_urlparse test_long_header test_long_header11 \ test_iplimit11 test_termination $(EMPTY_ITEM) $(am__append_3) \ $(am__append_4) $(am__append_5) $(am__append_6) \ $(am__append_7) $(am__append_8) $(am__append_13) \ $(am__append_14) @RUN_LIBCURL_TESTS_TRUE@TESTS = $(check_PROGRAMS) test_concurrent_stop_SOURCES = \ test_concurrent_stop.c test_concurrent_stop_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_concurrent_stop_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_head_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_head10_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_quiesce_SOURCES = \ test_quiesce.c mhd_has_param.h mhd_has_in_name.h test_quiesce_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_quiesce_stream_SOURCES = \ test_quiesce_stream.c test_quiesce_stream_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_stream_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_callback_SOURCES = \ test_callback.c perf_get_SOURCES = \ perf_get.c \ mhd_has_in_name.h perf_get_concurrent_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent_LDADD = \ $(PTHREAD_LIBS) $(LDADD) perf_get_concurrent11_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent11_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_basicauth_SOURCES = \ test_basicauth.c test_basicauth_preauth_SOURCES = \ test_basicauth.c test_basicauth_oldapi_SOURCES = \ test_basicauth.c test_basicauth_preauth_oldapi_SOURCES = \ test_basicauth.c test_digestauth_SOURCES = \ test_digestauth.c test_digestauth_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_sha256_SOURCES = \ test_digestauth_sha256.c test_digestauth_sha256_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_with_arguments_SOURCES = \ test_digestauth_with_arguments.c test_digestauth_with_arguments_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_concurrent_SOURCES = \ test_digestauth_concurrent.c test_digestauth_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_digestauth_concurrent_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) $(PTHREAD_LIBS) $(LDADD) test_digestauth_emu_ext_SOURCES = \ test_digestauth_emu_ext.c test_digestauth_emu_ext_oldapi_SOURCES = \ test_digestauth_emu_ext.c test_digestauth2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_get_iovec_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_wait_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_wait11_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait11_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_urlparse_SOURCES = \ test_urlparse.c mhd_has_in_name.h test_get_response_cleanup_SOURCES = \ test_get_response_cleanup.c mhd_has_in_name.h test_get_chunked_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_post_SOURCES = \ test_post.c mhd_has_in_name.h test_process_headers_SOURCES = \ test_process_headers.c mhd_has_in_name.h test_parse_cookies_discp_zero_SOURCES = \ test_parse_cookies.c mhd_has_in_name.h mhd_has_param.h test_parse_cookies_discp_p2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_p1_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n3_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_process_arguments_SOURCES = \ test_process_arguments.c mhd_has_in_name.h test_postform_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_delete_SOURCES = \ test_delete.c mhd_has_in_name.h test_patch_SOURCES = \ test_patch.c mhd_has_in_name.h test_patch11_SOURCES = \ test_patch.c mhd_has_in_name.h test_put_SOURCES = \ test_put.c mhd_has_in_name.h test_put_chunked_SOURCES = \ test_put_chunked.c test_add_conn_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get11_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_get_iovec11_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile11_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_close_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_close10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_post11_SOURCES = \ test_post.c mhd_has_in_name.h test_postform11_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform11_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop11_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_put11_SOURCES = \ test_put.c mhd_has_in_name.h test_large_put_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put_inc11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_long_header_SOURCES = \ test_long_header.c mhd_has_in_name.h test_long_header11_SOURCES = \ test_long_header.c mhd_has_in_name.h test_iplimit11_SOURCES = \ test_iplimit.c mhd_has_in_name.h test_termination_SOURCES = \ test_termination.c test_timeout_SOURCES = \ test_timeout.c mhd_has_in_name.h test_toolarge_method_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_url_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_tricky_url_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_tricky_header2_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len_SOURCES = \ test_put_broken_len.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len10_SOURCES = $(test_put_broken_len_SOURCES) test_put_header_fold_SOURCES = \ test_put_header_fold.c mhd_has_in_name.h mhd_has_param.h test_put_large_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_get_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_last_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_large_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_large_header_double_fold_SOURCES = $(test_put_large_header_fold_SOURCES) test_get_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_last_SOURCES = $(test_put_header_fold_last_SOURCES) test_put_header_double_fold_large_SOURCES = $(test_put_header_fold_large_SOURCES) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testcurl/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list perf_get$(EXEEXT): $(perf_get_OBJECTS) $(perf_get_DEPENDENCIES) $(EXTRA_perf_get_DEPENDENCIES) @rm -f perf_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(perf_get_OBJECTS) $(perf_get_LDADD) $(LIBS) perf_get_concurrent$(EXEEXT): $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_DEPENDENCIES) $(EXTRA_perf_get_concurrent_DEPENDENCIES) @rm -f perf_get_concurrent$(EXEEXT) $(AM_V_CCLD)$(perf_get_concurrent_LINK) $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_LDADD) $(LIBS) perf_get_concurrent11$(EXEEXT): $(perf_get_concurrent11_OBJECTS) $(perf_get_concurrent11_DEPENDENCIES) $(EXTRA_perf_get_concurrent11_DEPENDENCIES) @rm -f perf_get_concurrent11$(EXEEXT) $(AM_V_CCLD)$(perf_get_concurrent11_LINK) $(perf_get_concurrent11_OBJECTS) $(perf_get_concurrent11_LDADD) $(LIBS) test_add_conn$(EXEEXT): $(test_add_conn_OBJECTS) $(test_add_conn_DEPENDENCIES) $(EXTRA_test_add_conn_DEPENDENCIES) @rm -f test_add_conn$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_LINK) $(test_add_conn_OBJECTS) $(test_add_conn_LDADD) $(LIBS) test_add_conn_cleanup$(EXEEXT): $(test_add_conn_cleanup_OBJECTS) $(test_add_conn_cleanup_DEPENDENCIES) $(EXTRA_test_add_conn_cleanup_DEPENDENCIES) @rm -f test_add_conn_cleanup$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_cleanup_LINK) $(test_add_conn_cleanup_OBJECTS) $(test_add_conn_cleanup_LDADD) $(LIBS) test_add_conn_cleanup_nolisten$(EXEEXT): $(test_add_conn_cleanup_nolisten_OBJECTS) $(test_add_conn_cleanup_nolisten_DEPENDENCIES) $(EXTRA_test_add_conn_cleanup_nolisten_DEPENDENCIES) @rm -f test_add_conn_cleanup_nolisten$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_cleanup_nolisten_LINK) $(test_add_conn_cleanup_nolisten_OBJECTS) $(test_add_conn_cleanup_nolisten_LDADD) $(LIBS) test_add_conn_nolisten$(EXEEXT): $(test_add_conn_nolisten_OBJECTS) $(test_add_conn_nolisten_DEPENDENCIES) $(EXTRA_test_add_conn_nolisten_DEPENDENCIES) @rm -f test_add_conn_nolisten$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_nolisten_LINK) $(test_add_conn_nolisten_OBJECTS) $(test_add_conn_nolisten_LDADD) $(LIBS) test_basicauth$(EXEEXT): $(test_basicauth_OBJECTS) $(test_basicauth_DEPENDENCIES) $(EXTRA_test_basicauth_DEPENDENCIES) @rm -f test_basicauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_OBJECTS) $(test_basicauth_LDADD) $(LIBS) test_basicauth_oldapi$(EXEEXT): $(test_basicauth_oldapi_OBJECTS) $(test_basicauth_oldapi_DEPENDENCIES) $(EXTRA_test_basicauth_oldapi_DEPENDENCIES) @rm -f test_basicauth_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_oldapi_OBJECTS) $(test_basicauth_oldapi_LDADD) $(LIBS) test_basicauth_preauth$(EXEEXT): $(test_basicauth_preauth_OBJECTS) $(test_basicauth_preauth_DEPENDENCIES) $(EXTRA_test_basicauth_preauth_DEPENDENCIES) @rm -f test_basicauth_preauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_preauth_OBJECTS) $(test_basicauth_preauth_LDADD) $(LIBS) test_basicauth_preauth_oldapi$(EXEEXT): $(test_basicauth_preauth_oldapi_OBJECTS) $(test_basicauth_preauth_oldapi_DEPENDENCIES) $(EXTRA_test_basicauth_preauth_oldapi_DEPENDENCIES) @rm -f test_basicauth_preauth_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_preauth_oldapi_OBJECTS) $(test_basicauth_preauth_oldapi_LDADD) $(LIBS) test_callback$(EXEEXT): $(test_callback_OBJECTS) $(test_callback_DEPENDENCIES) $(EXTRA_test_callback_DEPENDENCIES) @rm -f test_callback$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_callback_OBJECTS) $(test_callback_LDADD) $(LIBS) test_concurrent_stop$(EXEEXT): $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_DEPENDENCIES) $(EXTRA_test_concurrent_stop_DEPENDENCIES) @rm -f test_concurrent_stop$(EXEEXT) $(AM_V_CCLD)$(test_concurrent_stop_LINK) $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_LDADD) $(LIBS) test_delete$(EXEEXT): $(test_delete_OBJECTS) $(test_delete_DEPENDENCIES) $(EXTRA_test_delete_DEPENDENCIES) @rm -f test_delete$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_delete_OBJECTS) $(test_delete_LDADD) $(LIBS) test_digestauth$(EXEEXT): $(test_digestauth_OBJECTS) $(test_digestauth_DEPENDENCIES) $(EXTRA_test_digestauth_DEPENDENCIES) @rm -f test_digestauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_OBJECTS) $(test_digestauth_LDADD) $(LIBS) test_digestauth2$(EXEEXT): $(test_digestauth2_OBJECTS) $(test_digestauth2_DEPENDENCIES) $(EXTRA_test_digestauth2_DEPENDENCIES) @rm -f test_digestauth2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_OBJECTS) $(test_digestauth2_LDADD) $(LIBS) test_digestauth2_bind_all$(EXEEXT): $(test_digestauth2_bind_all_OBJECTS) $(test_digestauth2_bind_all_DEPENDENCIES) $(EXTRA_test_digestauth2_bind_all_DEPENDENCIES) @rm -f test_digestauth2_bind_all$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_bind_all_OBJECTS) $(test_digestauth2_bind_all_LDADD) $(LIBS) test_digestauth2_bind_uri$(EXEEXT): $(test_digestauth2_bind_uri_OBJECTS) $(test_digestauth2_bind_uri_DEPENDENCIES) $(EXTRA_test_digestauth2_bind_uri_DEPENDENCIES) @rm -f test_digestauth2_bind_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_bind_uri_OBJECTS) $(test_digestauth2_bind_uri_LDADD) $(LIBS) test_digestauth2_oldapi1$(EXEEXT): $(test_digestauth2_oldapi1_OBJECTS) $(test_digestauth2_oldapi1_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_DEPENDENCIES) @rm -f test_digestauth2_oldapi1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_OBJECTS) $(test_digestauth2_oldapi1_LDADD) $(LIBS) test_digestauth2_oldapi1_bind_all$(EXEEXT): $(test_digestauth2_oldapi1_bind_all_OBJECTS) $(test_digestauth2_oldapi1_bind_all_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_bind_all_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_bind_all$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_bind_all_OBJECTS) $(test_digestauth2_oldapi1_bind_all_LDADD) $(LIBS) test_digestauth2_oldapi1_bind_uri$(EXEEXT): $(test_digestauth2_oldapi1_bind_uri_OBJECTS) $(test_digestauth2_oldapi1_bind_uri_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_bind_uri_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_bind_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_bind_uri_OBJECTS) $(test_digestauth2_oldapi1_bind_uri_LDADD) $(LIBS) test_digestauth2_oldapi1_userdigest$(EXEEXT): $(test_digestauth2_oldapi1_userdigest_OBJECTS) $(test_digestauth2_oldapi1_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_userdigest_OBJECTS) $(test_digestauth2_oldapi1_userdigest_LDADD) $(LIBS) test_digestauth2_oldapi2$(EXEEXT): $(test_digestauth2_oldapi2_OBJECTS) $(test_digestauth2_oldapi2_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_DEPENDENCIES) @rm -f test_digestauth2_oldapi2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_OBJECTS) $(test_digestauth2_oldapi2_LDADD) $(LIBS) test_digestauth2_oldapi2_sha256$(EXEEXT): $(test_digestauth2_oldapi2_sha256_OBJECTS) $(test_digestauth2_oldapi2_sha256_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_sha256_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_sha256_OBJECTS) $(test_digestauth2_oldapi2_sha256_LDADD) $(LIBS) test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT): $(test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) $(test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) $(test_digestauth2_oldapi2_sha256_userdigest_LDADD) $(LIBS) test_digestauth2_oldapi2_userdigest$(EXEEXT): $(test_digestauth2_oldapi2_userdigest_OBJECTS) $(test_digestauth2_oldapi2_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_userdigest_OBJECTS) $(test_digestauth2_oldapi2_userdigest_LDADD) $(LIBS) test_digestauth2_rfc2069$(EXEEXT): $(test_digestauth2_rfc2069_OBJECTS) $(test_digestauth2_rfc2069_DEPENDENCIES) $(EXTRA_test_digestauth2_rfc2069_DEPENDENCIES) @rm -f test_digestauth2_rfc2069$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_rfc2069_OBJECTS) $(test_digestauth2_rfc2069_LDADD) $(LIBS) test_digestauth2_rfc2069_userdigest$(EXEEXT): $(test_digestauth2_rfc2069_userdigest_OBJECTS) $(test_digestauth2_rfc2069_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_rfc2069_userdigest_DEPENDENCIES) @rm -f test_digestauth2_rfc2069_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_rfc2069_userdigest_OBJECTS) $(test_digestauth2_rfc2069_userdigest_LDADD) $(LIBS) test_digestauth2_sha256$(EXEEXT): $(test_digestauth2_sha256_OBJECTS) $(test_digestauth2_sha256_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_DEPENDENCIES) @rm -f test_digestauth2_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_OBJECTS) $(test_digestauth2_sha256_LDADD) $(LIBS) test_digestauth2_sha256_userdigest$(EXEEXT): $(test_digestauth2_sha256_userdigest_OBJECTS) $(test_digestauth2_sha256_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userdigest_DEPENDENCIES) @rm -f test_digestauth2_sha256_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userdigest_OBJECTS) $(test_digestauth2_sha256_userdigest_LDADD) $(LIBS) test_digestauth2_sha256_userhash$(EXEEXT): $(test_digestauth2_sha256_userhash_OBJECTS) $(test_digestauth2_sha256_userhash_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userhash_DEPENDENCIES) @rm -f test_digestauth2_sha256_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userhash_OBJECTS) $(test_digestauth2_sha256_userhash_LDADD) $(LIBS) test_digestauth2_sha256_userhash_userdigest$(EXEEXT): $(test_digestauth2_sha256_userhash_userdigest_OBJECTS) $(test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES) @rm -f test_digestauth2_sha256_userhash_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userhash_userdigest_OBJECTS) $(test_digestauth2_sha256_userhash_userdigest_LDADD) $(LIBS) test_digestauth2_userdigest$(EXEEXT): $(test_digestauth2_userdigest_OBJECTS) $(test_digestauth2_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_userdigest_DEPENDENCIES) @rm -f test_digestauth2_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userdigest_OBJECTS) $(test_digestauth2_userdigest_LDADD) $(LIBS) test_digestauth2_userhash$(EXEEXT): $(test_digestauth2_userhash_OBJECTS) $(test_digestauth2_userhash_DEPENDENCIES) $(EXTRA_test_digestauth2_userhash_DEPENDENCIES) @rm -f test_digestauth2_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userhash_OBJECTS) $(test_digestauth2_userhash_LDADD) $(LIBS) test_digestauth2_userhash_userdigest$(EXEEXT): $(test_digestauth2_userhash_userdigest_OBJECTS) $(test_digestauth2_userhash_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_userhash_userdigest_DEPENDENCIES) @rm -f test_digestauth2_userhash_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userhash_userdigest_OBJECTS) $(test_digestauth2_userhash_userdigest_LDADD) $(LIBS) test_digestauth_concurrent$(EXEEXT): $(test_digestauth_concurrent_OBJECTS) $(test_digestauth_concurrent_DEPENDENCIES) $(EXTRA_test_digestauth_concurrent_DEPENDENCIES) @rm -f test_digestauth_concurrent$(EXEEXT) $(AM_V_CCLD)$(test_digestauth_concurrent_LINK) $(test_digestauth_concurrent_OBJECTS) $(test_digestauth_concurrent_LDADD) $(LIBS) test_digestauth_emu_ext$(EXEEXT): $(test_digestauth_emu_ext_OBJECTS) $(test_digestauth_emu_ext_DEPENDENCIES) $(EXTRA_test_digestauth_emu_ext_DEPENDENCIES) @rm -f test_digestauth_emu_ext$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_emu_ext_OBJECTS) $(test_digestauth_emu_ext_LDADD) $(LIBS) test_digestauth_emu_ext_oldapi$(EXEEXT): $(test_digestauth_emu_ext_oldapi_OBJECTS) $(test_digestauth_emu_ext_oldapi_DEPENDENCIES) $(EXTRA_test_digestauth_emu_ext_oldapi_DEPENDENCIES) @rm -f test_digestauth_emu_ext_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_emu_ext_oldapi_OBJECTS) $(test_digestauth_emu_ext_oldapi_LDADD) $(LIBS) test_digestauth_sha256$(EXEEXT): $(test_digestauth_sha256_OBJECTS) $(test_digestauth_sha256_DEPENDENCIES) $(EXTRA_test_digestauth_sha256_DEPENDENCIES) @rm -f test_digestauth_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_sha256_OBJECTS) $(test_digestauth_sha256_LDADD) $(LIBS) test_digestauth_with_arguments$(EXEEXT): $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_DEPENDENCIES) $(EXTRA_test_digestauth_with_arguments_DEPENDENCIES) @rm -f test_digestauth_with_arguments$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_LDADD) $(LIBS) test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) @rm -f test_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS) test_get11$(EXEEXT): $(test_get11_OBJECTS) $(test_get11_DEPENDENCIES) $(EXTRA_test_get11_DEPENDENCIES) @rm -f test_get11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get11_OBJECTS) $(test_get11_LDADD) $(LIBS) test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) @rm -f test_get_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS) test_get_chunked_close$(EXEEXT): $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_DEPENDENCIES) $(EXTRA_test_get_chunked_close_DEPENDENCIES) @rm -f test_get_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_LDADD) $(LIBS) test_get_chunked_close_empty$(EXEEXT): $(test_get_chunked_close_empty_OBJECTS) $(test_get_chunked_close_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_DEPENDENCIES) @rm -f test_get_chunked_close_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_OBJECTS) $(test_get_chunked_close_empty_LDADD) $(LIBS) test_get_chunked_close_empty_forced$(EXEEXT): $(test_get_chunked_close_empty_forced_OBJECTS) $(test_get_chunked_close_empty_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_forced_DEPENDENCIES) @rm -f test_get_chunked_close_empty_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_forced_OBJECTS) $(test_get_chunked_close_empty_forced_LDADD) $(LIBS) test_get_chunked_close_empty_sized$(EXEEXT): $(test_get_chunked_close_empty_sized_OBJECTS) $(test_get_chunked_close_empty_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_sized_DEPENDENCIES) @rm -f test_get_chunked_close_empty_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_sized_OBJECTS) $(test_get_chunked_close_empty_sized_LDADD) $(LIBS) test_get_chunked_close_forced$(EXEEXT): $(test_get_chunked_close_forced_OBJECTS) $(test_get_chunked_close_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_close_forced_DEPENDENCIES) @rm -f test_get_chunked_close_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_forced_OBJECTS) $(test_get_chunked_close_forced_LDADD) $(LIBS) test_get_chunked_close_sized$(EXEEXT): $(test_get_chunked_close_sized_OBJECTS) $(test_get_chunked_close_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_close_sized_DEPENDENCIES) @rm -f test_get_chunked_close_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_sized_OBJECTS) $(test_get_chunked_close_sized_LDADD) $(LIBS) test_get_chunked_close_string$(EXEEXT): $(test_get_chunked_close_string_OBJECTS) $(test_get_chunked_close_string_DEPENDENCIES) $(EXTRA_test_get_chunked_close_string_DEPENDENCIES) @rm -f test_get_chunked_close_string$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_string_OBJECTS) $(test_get_chunked_close_string_LDADD) $(LIBS) test_get_chunked_close_string_empty$(EXEEXT): $(test_get_chunked_close_string_empty_OBJECTS) $(test_get_chunked_close_string_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_close_string_empty_DEPENDENCIES) @rm -f test_get_chunked_close_string_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_string_empty_OBJECTS) $(test_get_chunked_close_string_empty_LDADD) $(LIBS) test_get_chunked_empty$(EXEEXT): $(test_get_chunked_empty_OBJECTS) $(test_get_chunked_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_DEPENDENCIES) @rm -f test_get_chunked_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_OBJECTS) $(test_get_chunked_empty_LDADD) $(LIBS) test_get_chunked_empty_forced$(EXEEXT): $(test_get_chunked_empty_forced_OBJECTS) $(test_get_chunked_empty_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_forced_DEPENDENCIES) @rm -f test_get_chunked_empty_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_forced_OBJECTS) $(test_get_chunked_empty_forced_LDADD) $(LIBS) test_get_chunked_empty_sized$(EXEEXT): $(test_get_chunked_empty_sized_OBJECTS) $(test_get_chunked_empty_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_sized_DEPENDENCIES) @rm -f test_get_chunked_empty_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_sized_OBJECTS) $(test_get_chunked_empty_sized_LDADD) $(LIBS) test_get_chunked_forced$(EXEEXT): $(test_get_chunked_forced_OBJECTS) $(test_get_chunked_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_forced_DEPENDENCIES) @rm -f test_get_chunked_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_forced_OBJECTS) $(test_get_chunked_forced_LDADD) $(LIBS) test_get_chunked_sized$(EXEEXT): $(test_get_chunked_sized_OBJECTS) $(test_get_chunked_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_sized_DEPENDENCIES) @rm -f test_get_chunked_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_sized_OBJECTS) $(test_get_chunked_sized_LDADD) $(LIBS) test_get_chunked_string$(EXEEXT): $(test_get_chunked_string_OBJECTS) $(test_get_chunked_string_DEPENDENCIES) $(EXTRA_test_get_chunked_string_DEPENDENCIES) @rm -f test_get_chunked_string$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_string_OBJECTS) $(test_get_chunked_string_LDADD) $(LIBS) test_get_chunked_string_empty$(EXEEXT): $(test_get_chunked_string_empty_OBJECTS) $(test_get_chunked_string_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_string_empty_DEPENDENCIES) @rm -f test_get_chunked_string_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_string_empty_OBJECTS) $(test_get_chunked_string_empty_LDADD) $(LIBS) test_get_close$(EXEEXT): $(test_get_close_OBJECTS) $(test_get_close_DEPENDENCIES) $(EXTRA_test_get_close_DEPENDENCIES) @rm -f test_get_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close_OBJECTS) $(test_get_close_LDADD) $(LIBS) test_get_close10$(EXEEXT): $(test_get_close10_OBJECTS) $(test_get_close10_DEPENDENCIES) $(EXTRA_test_get_close10_DEPENDENCIES) @rm -f test_get_close10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close10_OBJECTS) $(test_get_close10_LDADD) $(LIBS) test_get_header_double_fold$(EXEEXT): $(test_get_header_double_fold_OBJECTS) $(test_get_header_double_fold_DEPENDENCIES) $(EXTRA_test_get_header_double_fold_DEPENDENCIES) @rm -f test_get_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_header_double_fold_OBJECTS) $(test_get_header_double_fold_LDADD) $(LIBS) test_get_header_fold$(EXEEXT): $(test_get_header_fold_OBJECTS) $(test_get_header_fold_DEPENDENCIES) $(EXTRA_test_get_header_fold_DEPENDENCIES) @rm -f test_get_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_header_fold_OBJECTS) $(test_get_header_fold_LDADD) $(LIBS) test_get_iovec$(EXEEXT): $(test_get_iovec_OBJECTS) $(test_get_iovec_DEPENDENCIES) $(EXTRA_test_get_iovec_DEPENDENCIES) @rm -f test_get_iovec$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_iovec_OBJECTS) $(test_get_iovec_LDADD) $(LIBS) test_get_iovec11$(EXEEXT): $(test_get_iovec11_OBJECTS) $(test_get_iovec11_DEPENDENCIES) $(EXTRA_test_get_iovec11_DEPENDENCIES) @rm -f test_get_iovec11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_iovec11_OBJECTS) $(test_get_iovec11_LDADD) $(LIBS) test_get_keep_alive$(EXEEXT): $(test_get_keep_alive_OBJECTS) $(test_get_keep_alive_DEPENDENCIES) $(EXTRA_test_get_keep_alive_DEPENDENCIES) @rm -f test_get_keep_alive$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_keep_alive_OBJECTS) $(test_get_keep_alive_LDADD) $(LIBS) test_get_keep_alive10$(EXEEXT): $(test_get_keep_alive10_OBJECTS) $(test_get_keep_alive10_DEPENDENCIES) $(EXTRA_test_get_keep_alive10_DEPENDENCIES) @rm -f test_get_keep_alive10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_keep_alive10_OBJECTS) $(test_get_keep_alive10_LDADD) $(LIBS) test_get_response_cleanup$(EXEEXT): $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_DEPENDENCIES) $(EXTRA_test_get_response_cleanup_DEPENDENCIES) @rm -f test_get_response_cleanup$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_LDADD) $(LIBS) test_get_sendfile$(EXEEXT): $(test_get_sendfile_OBJECTS) $(test_get_sendfile_DEPENDENCIES) $(EXTRA_test_get_sendfile_DEPENDENCIES) @rm -f test_get_sendfile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_sendfile_OBJECTS) $(test_get_sendfile_LDADD) $(LIBS) test_get_sendfile11$(EXEEXT): $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_DEPENDENCIES) $(EXTRA_test_get_sendfile11_DEPENDENCIES) @rm -f test_get_sendfile11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_LDADD) $(LIBS) test_get_wait$(EXEEXT): $(test_get_wait_OBJECTS) $(test_get_wait_DEPENDENCIES) $(EXTRA_test_get_wait_DEPENDENCIES) @rm -f test_get_wait$(EXEEXT) $(AM_V_CCLD)$(test_get_wait_LINK) $(test_get_wait_OBJECTS) $(test_get_wait_LDADD) $(LIBS) test_get_wait11$(EXEEXT): $(test_get_wait11_OBJECTS) $(test_get_wait11_DEPENDENCIES) $(EXTRA_test_get_wait11_DEPENDENCIES) @rm -f test_get_wait11$(EXEEXT) $(AM_V_CCLD)$(test_get_wait11_LINK) $(test_get_wait11_OBJECTS) $(test_get_wait11_LDADD) $(LIBS) test_head$(EXEEXT): $(test_head_OBJECTS) $(test_head_DEPENDENCIES) $(EXTRA_test_head_DEPENDENCIES) @rm -f test_head$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_head_OBJECTS) $(test_head_LDADD) $(LIBS) test_head10$(EXEEXT): $(test_head10_OBJECTS) $(test_head10_DEPENDENCIES) $(EXTRA_test_head10_DEPENDENCIES) @rm -f test_head10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_head10_OBJECTS) $(test_head10_LDADD) $(LIBS) test_iplimit11$(EXEEXT): $(test_iplimit11_OBJECTS) $(test_iplimit11_DEPENDENCIES) $(EXTRA_test_iplimit11_DEPENDENCIES) @rm -f test_iplimit11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_iplimit11_OBJECTS) $(test_iplimit11_LDADD) $(LIBS) test_large_put$(EXEEXT): $(test_large_put_OBJECTS) $(test_large_put_DEPENDENCIES) $(EXTRA_test_large_put_DEPENDENCIES) @rm -f test_large_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put_OBJECTS) $(test_large_put_LDADD) $(LIBS) test_large_put11$(EXEEXT): $(test_large_put11_OBJECTS) $(test_large_put11_DEPENDENCIES) $(EXTRA_test_large_put11_DEPENDENCIES) @rm -f test_large_put11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put11_OBJECTS) $(test_large_put11_LDADD) $(LIBS) test_large_put_inc11$(EXEEXT): $(test_large_put_inc11_OBJECTS) $(test_large_put_inc11_DEPENDENCIES) $(EXTRA_test_large_put_inc11_DEPENDENCIES) @rm -f test_large_put_inc11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put_inc11_OBJECTS) $(test_large_put_inc11_LDADD) $(LIBS) test_long_header$(EXEEXT): $(test_long_header_OBJECTS) $(test_long_header_DEPENDENCIES) $(EXTRA_test_long_header_DEPENDENCIES) @rm -f test_long_header$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_long_header_OBJECTS) $(test_long_header_LDADD) $(LIBS) test_long_header11$(EXEEXT): $(test_long_header11_OBJECTS) $(test_long_header11_DEPENDENCIES) $(EXTRA_test_long_header11_DEPENDENCIES) @rm -f test_long_header11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_long_header11_OBJECTS) $(test_long_header11_LDADD) $(LIBS) test_parse_cookies_discp_n2$(EXEEXT): $(test_parse_cookies_discp_n2_OBJECTS) $(test_parse_cookies_discp_n2_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_n2_DEPENDENCIES) @rm -f test_parse_cookies_discp_n2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_n2_OBJECTS) $(test_parse_cookies_discp_n2_LDADD) $(LIBS) test_parse_cookies_discp_n3$(EXEEXT): $(test_parse_cookies_discp_n3_OBJECTS) $(test_parse_cookies_discp_n3_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_n3_DEPENDENCIES) @rm -f test_parse_cookies_discp_n3$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_n3_OBJECTS) $(test_parse_cookies_discp_n3_LDADD) $(LIBS) test_parse_cookies_discp_p1$(EXEEXT): $(test_parse_cookies_discp_p1_OBJECTS) $(test_parse_cookies_discp_p1_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_p1_DEPENDENCIES) @rm -f test_parse_cookies_discp_p1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_p1_OBJECTS) $(test_parse_cookies_discp_p1_LDADD) $(LIBS) test_parse_cookies_discp_p2$(EXEEXT): $(test_parse_cookies_discp_p2_OBJECTS) $(test_parse_cookies_discp_p2_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_p2_DEPENDENCIES) @rm -f test_parse_cookies_discp_p2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_p2_OBJECTS) $(test_parse_cookies_discp_p2_LDADD) $(LIBS) test_parse_cookies_discp_zero$(EXEEXT): $(test_parse_cookies_discp_zero_OBJECTS) $(test_parse_cookies_discp_zero_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_zero_DEPENDENCIES) @rm -f test_parse_cookies_discp_zero$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_zero_OBJECTS) $(test_parse_cookies_discp_zero_LDADD) $(LIBS) test_patch$(EXEEXT): $(test_patch_OBJECTS) $(test_patch_DEPENDENCIES) $(EXTRA_test_patch_DEPENDENCIES) @rm -f test_patch$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_patch_OBJECTS) $(test_patch_LDADD) $(LIBS) test_patch11$(EXEEXT): $(test_patch11_OBJECTS) $(test_patch11_DEPENDENCIES) $(EXTRA_test_patch11_DEPENDENCIES) @rm -f test_patch11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_patch11_OBJECTS) $(test_patch11_LDADD) $(LIBS) test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) @rm -f test_post$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS) test_post11$(EXEEXT): $(test_post11_OBJECTS) $(test_post11_DEPENDENCIES) $(EXTRA_test_post11_DEPENDENCIES) @rm -f test_post11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post11_OBJECTS) $(test_post11_LDADD) $(LIBS) test_post_loop$(EXEEXT): $(test_post_loop_OBJECTS) $(test_post_loop_DEPENDENCIES) $(EXTRA_test_post_loop_DEPENDENCIES) @rm -f test_post_loop$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_loop_OBJECTS) $(test_post_loop_LDADD) $(LIBS) test_post_loop11$(EXEEXT): $(test_post_loop11_OBJECTS) $(test_post_loop11_DEPENDENCIES) $(EXTRA_test_post_loop11_DEPENDENCIES) @rm -f test_post_loop11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_loop11_OBJECTS) $(test_post_loop11_LDADD) $(LIBS) test_postform$(EXEEXT): $(test_postform_OBJECTS) $(test_postform_DEPENDENCIES) $(EXTRA_test_postform_DEPENDENCIES) @rm -f test_postform$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postform_OBJECTS) $(test_postform_LDADD) $(LIBS) test_postform11$(EXEEXT): $(test_postform11_OBJECTS) $(test_postform11_DEPENDENCIES) $(EXTRA_test_postform11_DEPENDENCIES) @rm -f test_postform11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postform11_OBJECTS) $(test_postform11_LDADD) $(LIBS) test_process_arguments$(EXEEXT): $(test_process_arguments_OBJECTS) $(test_process_arguments_DEPENDENCIES) $(EXTRA_test_process_arguments_DEPENDENCIES) @rm -f test_process_arguments$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_process_arguments_OBJECTS) $(test_process_arguments_LDADD) $(LIBS) test_process_headers$(EXEEXT): $(test_process_headers_OBJECTS) $(test_process_headers_DEPENDENCIES) $(EXTRA_test_process_headers_DEPENDENCIES) @rm -f test_process_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_process_headers_OBJECTS) $(test_process_headers_LDADD) $(LIBS) test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) @rm -f test_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS) test_put11$(EXEEXT): $(test_put11_OBJECTS) $(test_put11_DEPENDENCIES) $(EXTRA_test_put11_DEPENDENCIES) @rm -f test_put11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put11_OBJECTS) $(test_put11_LDADD) $(LIBS) test_put_broken_len$(EXEEXT): $(test_put_broken_len_OBJECTS) $(test_put_broken_len_DEPENDENCIES) $(EXTRA_test_put_broken_len_DEPENDENCIES) @rm -f test_put_broken_len$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_broken_len_OBJECTS) $(test_put_broken_len_LDADD) $(LIBS) test_put_broken_len10$(EXEEXT): $(test_put_broken_len10_OBJECTS) $(test_put_broken_len10_DEPENDENCIES) $(EXTRA_test_put_broken_len10_DEPENDENCIES) @rm -f test_put_broken_len10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_broken_len10_OBJECTS) $(test_put_broken_len10_LDADD) $(LIBS) test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) @rm -f test_put_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS) test_put_header_double_fold$(EXEEXT): $(test_put_header_double_fold_OBJECTS) $(test_put_header_double_fold_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_DEPENDENCIES) @rm -f test_put_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_OBJECTS) $(test_put_header_double_fold_LDADD) $(LIBS) test_put_header_double_fold_large$(EXEEXT): $(test_put_header_double_fold_large_OBJECTS) $(test_put_header_double_fold_large_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_large_DEPENDENCIES) @rm -f test_put_header_double_fold_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_large_OBJECTS) $(test_put_header_double_fold_large_LDADD) $(LIBS) test_put_header_double_fold_last$(EXEEXT): $(test_put_header_double_fold_last_OBJECTS) $(test_put_header_double_fold_last_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_last_DEPENDENCIES) @rm -f test_put_header_double_fold_last$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_last_OBJECTS) $(test_put_header_double_fold_last_LDADD) $(LIBS) test_put_header_fold$(EXEEXT): $(test_put_header_fold_OBJECTS) $(test_put_header_fold_DEPENDENCIES) $(EXTRA_test_put_header_fold_DEPENDENCIES) @rm -f test_put_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_OBJECTS) $(test_put_header_fold_LDADD) $(LIBS) test_put_header_fold_large$(EXEEXT): $(test_put_header_fold_large_OBJECTS) $(test_put_header_fold_large_DEPENDENCIES) $(EXTRA_test_put_header_fold_large_DEPENDENCIES) @rm -f test_put_header_fold_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_large_OBJECTS) $(test_put_header_fold_large_LDADD) $(LIBS) test_put_header_fold_last$(EXEEXT): $(test_put_header_fold_last_OBJECTS) $(test_put_header_fold_last_DEPENDENCIES) $(EXTRA_test_put_header_fold_last_DEPENDENCIES) @rm -f test_put_header_fold_last$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_last_OBJECTS) $(test_put_header_fold_last_LDADD) $(LIBS) test_put_large_header_double_fold$(EXEEXT): $(test_put_large_header_double_fold_OBJECTS) $(test_put_large_header_double_fold_DEPENDENCIES) $(EXTRA_test_put_large_header_double_fold_DEPENDENCIES) @rm -f test_put_large_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_header_double_fold_OBJECTS) $(test_put_large_header_double_fold_LDADD) $(LIBS) test_put_large_header_fold$(EXEEXT): $(test_put_large_header_fold_OBJECTS) $(test_put_large_header_fold_DEPENDENCIES) $(EXTRA_test_put_large_header_fold_DEPENDENCIES) @rm -f test_put_large_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_header_fold_OBJECTS) $(test_put_large_header_fold_LDADD) $(LIBS) test_quiesce$(EXEEXT): $(test_quiesce_OBJECTS) $(test_quiesce_DEPENDENCIES) $(EXTRA_test_quiesce_DEPENDENCIES) @rm -f test_quiesce$(EXEEXT) $(AM_V_CCLD)$(test_quiesce_LINK) $(test_quiesce_OBJECTS) $(test_quiesce_LDADD) $(LIBS) test_quiesce_stream$(EXEEXT): $(test_quiesce_stream_OBJECTS) $(test_quiesce_stream_DEPENDENCIES) $(EXTRA_test_quiesce_stream_DEPENDENCIES) @rm -f test_quiesce_stream$(EXEEXT) $(AM_V_CCLD)$(test_quiesce_stream_LINK) $(test_quiesce_stream_OBJECTS) $(test_quiesce_stream_LDADD) $(LIBS) test_termination$(EXEEXT): $(test_termination_OBJECTS) $(test_termination_DEPENDENCIES) $(EXTRA_test_termination_DEPENDENCIES) @rm -f test_termination$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_termination_OBJECTS) $(test_termination_LDADD) $(LIBS) test_timeout$(EXEEXT): $(test_timeout_OBJECTS) $(test_timeout_DEPENDENCIES) $(EXTRA_test_timeout_DEPENDENCIES) @rm -f test_timeout$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_timeout_OBJECTS) $(test_timeout_LDADD) $(LIBS) test_toolarge_method$(EXEEXT): $(test_toolarge_method_OBJECTS) $(test_toolarge_method_DEPENDENCIES) $(EXTRA_test_toolarge_method_DEPENDENCIES) @rm -f test_toolarge_method$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_method_OBJECTS) $(test_toolarge_method_LDADD) $(LIBS) test_toolarge_reply_header_name$(EXEEXT): $(test_toolarge_reply_header_name_OBJECTS) $(test_toolarge_reply_header_name_DEPENDENCIES) $(EXTRA_test_toolarge_reply_header_name_DEPENDENCIES) @rm -f test_toolarge_reply_header_name$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_header_name_OBJECTS) $(test_toolarge_reply_header_name_LDADD) $(LIBS) test_toolarge_reply_header_value$(EXEEXT): $(test_toolarge_reply_header_value_OBJECTS) $(test_toolarge_reply_header_value_DEPENDENCIES) $(EXTRA_test_toolarge_reply_header_value_DEPENDENCIES) @rm -f test_toolarge_reply_header_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_header_value_OBJECTS) $(test_toolarge_reply_header_value_LDADD) $(LIBS) test_toolarge_reply_headers$(EXEEXT): $(test_toolarge_reply_headers_OBJECTS) $(test_toolarge_reply_headers_DEPENDENCIES) $(EXTRA_test_toolarge_reply_headers_DEPENDENCIES) @rm -f test_toolarge_reply_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_headers_OBJECTS) $(test_toolarge_reply_headers_LDADD) $(LIBS) test_toolarge_request_header_name$(EXEEXT): $(test_toolarge_request_header_name_OBJECTS) $(test_toolarge_request_header_name_DEPENDENCIES) $(EXTRA_test_toolarge_request_header_name_DEPENDENCIES) @rm -f test_toolarge_request_header_name$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_header_name_OBJECTS) $(test_toolarge_request_header_name_LDADD) $(LIBS) test_toolarge_request_header_value$(EXEEXT): $(test_toolarge_request_header_value_OBJECTS) $(test_toolarge_request_header_value_DEPENDENCIES) $(EXTRA_test_toolarge_request_header_value_DEPENDENCIES) @rm -f test_toolarge_request_header_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_header_value_OBJECTS) $(test_toolarge_request_header_value_LDADD) $(LIBS) test_toolarge_request_headers$(EXEEXT): $(test_toolarge_request_headers_OBJECTS) $(test_toolarge_request_headers_DEPENDENCIES) $(EXTRA_test_toolarge_request_headers_DEPENDENCIES) @rm -f test_toolarge_request_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_headers_OBJECTS) $(test_toolarge_request_headers_LDADD) $(LIBS) test_toolarge_url$(EXEEXT): $(test_toolarge_url_OBJECTS) $(test_toolarge_url_DEPENDENCIES) $(EXTRA_test_toolarge_url_DEPENDENCIES) @rm -f test_toolarge_url$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_url_OBJECTS) $(test_toolarge_url_LDADD) $(LIBS) test_tricky_header2$(EXEEXT): $(test_tricky_header2_OBJECTS) $(test_tricky_header2_DEPENDENCIES) $(EXTRA_test_tricky_header2_DEPENDENCIES) @rm -f test_tricky_header2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tricky_header2_OBJECTS) $(test_tricky_header2_LDADD) $(LIBS) test_tricky_url$(EXEEXT): $(test_tricky_url_OBJECTS) $(test_tricky_url_DEPENDENCIES) $(EXTRA_test_tricky_url_DEPENDENCIES) @rm -f test_tricky_url$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tricky_url_OBJECTS) $(test_tricky_url_LDADD) $(LIBS) test_urlparse$(EXEEXT): $(test_urlparse_OBJECTS) $(test_urlparse_DEPENDENCIES) $(EXTRA_test_urlparse_DEPENDENCIES) @rm -f test_urlparse$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_urlparse_OBJECTS) $(test_urlparse_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_basicauth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_callback.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_delete.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth2.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_emu_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_with_arguments.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_chunked.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_close_keep_alive.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_iovec.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_response_cleanup.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_sendfile.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_wait-test_get_wait.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_wait11-test_get_wait.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_head.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_iplimit.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_large_put.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_long_header.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_parse_cookies.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_patch.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post_loop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postform.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_arguments.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_headers.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_broken_len.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_chunked.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_header_fold.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_quiesce-test_quiesce.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_termination.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_timeout.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_toolarge.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tricky.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_urlparse.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< perf_get_concurrent-perf_get_concurrent.o: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -MT perf_get_concurrent-perf_get_concurrent.o -MD -MP -MF $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo -c -o perf_get_concurrent-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent-perf_get_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c perf_get_concurrent-perf_get_concurrent.obj: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -MT perf_get_concurrent-perf_get_concurrent.obj -MD -MP -MF $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo -c -o perf_get_concurrent-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent-perf_get_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` perf_get_concurrent11-perf_get_concurrent.o: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -MT perf_get_concurrent11-perf_get_concurrent.o -MD -MP -MF $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo -c -o perf_get_concurrent11-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent11-perf_get_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent11-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c perf_get_concurrent11-perf_get_concurrent.obj: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -MT perf_get_concurrent11-perf_get_concurrent.obj -MD -MP -MF $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo -c -o perf_get_concurrent11-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent11-perf_get_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent11-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` test_add_conn-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -MT test_add_conn-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn-test_add_conn.Tpo -c -o test_add_conn-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn-test_add_conn.Tpo $(DEPDIR)/test_add_conn-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -c -o test_add_conn-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -MT test_add_conn-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn-test_add_conn.Tpo -c -o test_add_conn-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn-test_add_conn.Tpo $(DEPDIR)/test_add_conn-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -c -o test_add_conn-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_cleanup-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo -c -o test_add_conn_cleanup-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_cleanup-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo -c -o test_add_conn_cleanup-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_cleanup_nolisten-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup_nolisten-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo -c -o test_add_conn_cleanup_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup_nolisten-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_cleanup_nolisten-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup_nolisten-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo -c -o test_add_conn_cleanup_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup_nolisten-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_nolisten-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_nolisten-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo -c -o test_add_conn_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_nolisten-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_nolisten-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_nolisten-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo -c -o test_add_conn_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_nolisten-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_concurrent_stop-test_concurrent_stop.o: test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -MT test_concurrent_stop-test_concurrent_stop.o -MD -MP -MF $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo -c -o test_concurrent_stop-test_concurrent_stop.o `test -f 'test_concurrent_stop.c' || echo '$(srcdir)/'`test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_concurrent_stop.c' object='test_concurrent_stop-test_concurrent_stop.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -c -o test_concurrent_stop-test_concurrent_stop.o `test -f 'test_concurrent_stop.c' || echo '$(srcdir)/'`test_concurrent_stop.c test_concurrent_stop-test_concurrent_stop.obj: test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -MT test_concurrent_stop-test_concurrent_stop.obj -MD -MP -MF $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo -c -o test_concurrent_stop-test_concurrent_stop.obj `if test -f 'test_concurrent_stop.c'; then $(CYGPATH_W) 'test_concurrent_stop.c'; else $(CYGPATH_W) '$(srcdir)/test_concurrent_stop.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_concurrent_stop.c' object='test_concurrent_stop-test_concurrent_stop.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -c -o test_concurrent_stop-test_concurrent_stop.obj `if test -f 'test_concurrent_stop.c'; then $(CYGPATH_W) 'test_concurrent_stop.c'; else $(CYGPATH_W) '$(srcdir)/test_concurrent_stop.c'; fi` test_digestauth_concurrent-test_digestauth_concurrent.o: test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -MT test_digestauth_concurrent-test_digestauth_concurrent.o -MD -MP -MF $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo -c -o test_digestauth_concurrent-test_digestauth_concurrent.o `test -f 'test_digestauth_concurrent.c' || echo '$(srcdir)/'`test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_digestauth_concurrent.c' object='test_digestauth_concurrent-test_digestauth_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -c -o test_digestauth_concurrent-test_digestauth_concurrent.o `test -f 'test_digestauth_concurrent.c' || echo '$(srcdir)/'`test_digestauth_concurrent.c test_digestauth_concurrent-test_digestauth_concurrent.obj: test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -MT test_digestauth_concurrent-test_digestauth_concurrent.obj -MD -MP -MF $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo -c -o test_digestauth_concurrent-test_digestauth_concurrent.obj `if test -f 'test_digestauth_concurrent.c'; then $(CYGPATH_W) 'test_digestauth_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/test_digestauth_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_digestauth_concurrent.c' object='test_digestauth_concurrent-test_digestauth_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -c -o test_digestauth_concurrent-test_digestauth_concurrent.obj `if test -f 'test_digestauth_concurrent.c'; then $(CYGPATH_W) 'test_digestauth_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/test_digestauth_concurrent.c'; fi` test_get_wait-test_get_wait.o: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -MT test_get_wait-test_get_wait.o -MD -MP -MF $(DEPDIR)/test_get_wait-test_get_wait.Tpo -c -o test_get_wait-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait-test_get_wait.Tpo $(DEPDIR)/test_get_wait-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait-test_get_wait.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -c -o test_get_wait-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c test_get_wait-test_get_wait.obj: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -MT test_get_wait-test_get_wait.obj -MD -MP -MF $(DEPDIR)/test_get_wait-test_get_wait.Tpo -c -o test_get_wait-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait-test_get_wait.Tpo $(DEPDIR)/test_get_wait-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait-test_get_wait.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -c -o test_get_wait-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` test_get_wait11-test_get_wait.o: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -MT test_get_wait11-test_get_wait.o -MD -MP -MF $(DEPDIR)/test_get_wait11-test_get_wait.Tpo -c -o test_get_wait11-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait11-test_get_wait.Tpo $(DEPDIR)/test_get_wait11-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait11-test_get_wait.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -c -o test_get_wait11-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c test_get_wait11-test_get_wait.obj: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -MT test_get_wait11-test_get_wait.obj -MD -MP -MF $(DEPDIR)/test_get_wait11-test_get_wait.Tpo -c -o test_get_wait11-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait11-test_get_wait.Tpo $(DEPDIR)/test_get_wait11-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait11-test_get_wait.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -c -o test_get_wait11-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` test_quiesce-test_quiesce.o: test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.o -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c test_quiesce-test_quiesce.obj: test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.obj -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi` test_quiesce_stream-test_quiesce_stream.o: test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -MT test_quiesce_stream-test_quiesce_stream.o -MD -MP -MF $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo -c -o test_quiesce_stream-test_quiesce_stream.o `test -f 'test_quiesce_stream.c' || echo '$(srcdir)/'`test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce_stream.c' object='test_quiesce_stream-test_quiesce_stream.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -c -o test_quiesce_stream-test_quiesce_stream.o `test -f 'test_quiesce_stream.c' || echo '$(srcdir)/'`test_quiesce_stream.c test_quiesce_stream-test_quiesce_stream.obj: test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -MT test_quiesce_stream-test_quiesce_stream.obj -MD -MP -MF $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo -c -o test_quiesce_stream-test_quiesce_stream.obj `if test -f 'test_quiesce_stream.c'; then $(CYGPATH_W) 'test_quiesce_stream.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce_stream.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce_stream.c' object='test_quiesce_stream-test_quiesce_stream.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -c -o test_quiesce_stream-test_quiesce_stream.obj `if test -f 'test_quiesce_stream.c'; then $(CYGPATH_W) 'test_quiesce_stream.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce_stream.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_get.log: test_get$(EXEEXT) @p='test_get$(EXEEXT)'; \ b='test_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_head.log: test_head$(EXEEXT) @p='test_head$(EXEEXT)'; \ b='test_head'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_head10.log: test_head10$(EXEEXT) @p='test_head10$(EXEEXT)'; \ b='test_head10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_iovec.log: test_get_iovec$(EXEEXT) @p='test_get_iovec$(EXEEXT)'; \ b='test_get_iovec'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_sendfile.log: test_get_sendfile$(EXEEXT) @p='test_get_sendfile$(EXEEXT)'; \ b='test_get_sendfile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close.log: test_get_close$(EXEEXT) @p='test_get_close$(EXEEXT)'; \ b='test_get_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close10.log: test_get_close10$(EXEEXT) @p='test_get_close10$(EXEEXT)'; \ b='test_get_close10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_keep_alive.log: test_get_keep_alive$(EXEEXT) @p='test_get_keep_alive$(EXEEXT)'; \ b='test_get_keep_alive'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_keep_alive10.log: test_get_keep_alive10$(EXEEXT) @p='test_get_keep_alive10$(EXEEXT)'; \ b='test_get_keep_alive10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_delete.log: test_delete$(EXEEXT) @p='test_delete$(EXEEXT)'; \ b='test_delete'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_patch.log: test_patch$(EXEEXT) @p='test_patch$(EXEEXT)'; \ b='test_patch'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put.log: test_put$(EXEEXT) @p='test_put$(EXEEXT)'; \ b='test_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn.log: test_add_conn$(EXEEXT) @p='test_add_conn$(EXEEXT)'; \ b='test_add_conn'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_nolisten.log: test_add_conn_nolisten$(EXEEXT) @p='test_add_conn_nolisten$(EXEEXT)'; \ b='test_add_conn_nolisten'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_process_headers.log: test_process_headers$(EXEEXT) @p='test_process_headers$(EXEEXT)'; \ b='test_process_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_process_arguments.log: test_process_arguments$(EXEEXT) @p='test_process_arguments$(EXEEXT)'; \ b='test_process_arguments'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_method.log: test_toolarge_method$(EXEEXT) @p='test_toolarge_method$(EXEEXT)'; \ b='test_toolarge_method'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_url.log: test_toolarge_url$(EXEEXT) @p='test_toolarge_url$(EXEEXT)'; \ b='test_toolarge_url'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_header_name.log: test_toolarge_request_header_name$(EXEEXT) @p='test_toolarge_request_header_name$(EXEEXT)'; \ b='test_toolarge_request_header_name'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_header_value.log: test_toolarge_request_header_value$(EXEEXT) @p='test_toolarge_request_header_value$(EXEEXT)'; \ b='test_toolarge_request_header_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_headers.log: test_toolarge_request_headers$(EXEEXT) @p='test_toolarge_request_headers$(EXEEXT)'; \ b='test_toolarge_request_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_header_name.log: test_toolarge_reply_header_name$(EXEEXT) @p='test_toolarge_reply_header_name$(EXEEXT)'; \ b='test_toolarge_reply_header_name'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_header_value.log: test_toolarge_reply_header_value$(EXEEXT) @p='test_toolarge_reply_header_value$(EXEEXT)'; \ b='test_toolarge_reply_header_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_headers.log: test_toolarge_reply_headers$(EXEEXT) @p='test_toolarge_reply_headers$(EXEEXT)'; \ b='test_toolarge_reply_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tricky_url.log: test_tricky_url$(EXEEXT) @p='test_tricky_url$(EXEEXT)'; \ b='test_tricky_url'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tricky_header2.log: test_tricky_header2$(EXEEXT) @p='test_tricky_header2$(EXEEXT)'; \ b='test_tricky_header2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put.log: test_large_put$(EXEEXT) @p='test_large_put$(EXEEXT)'; \ b='test_large_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get11.log: test_get11$(EXEEXT) @p='test_get11$(EXEEXT)'; \ b='test_get11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_iovec11.log: test_get_iovec11$(EXEEXT) @p='test_get_iovec11$(EXEEXT)'; \ b='test_get_iovec11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_sendfile11.log: test_get_sendfile11$(EXEEXT) @p='test_get_sendfile11$(EXEEXT)'; \ b='test_get_sendfile11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_patch11.log: test_patch11$(EXEEXT) @p='test_patch11$(EXEEXT)'; \ b='test_patch11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put11.log: test_put11$(EXEEXT) @p='test_put11$(EXEEXT)'; \ b='test_put11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put11.log: test_large_put11$(EXEEXT) @p='test_large_put11$(EXEEXT)'; \ b='test_large_put11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put_inc11.log: test_large_put_inc11$(EXEEXT) @p='test_large_put_inc11$(EXEEXT)'; \ b='test_large_put_inc11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_broken_len10.log: test_put_broken_len10$(EXEEXT) @p='test_put_broken_len10$(EXEEXT)'; \ b='test_put_broken_len10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_broken_len.log: test_put_broken_len$(EXEEXT) @p='test_put_broken_len$(EXEEXT)'; \ b='test_put_broken_len'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked.log: test_get_chunked$(EXEEXT) @p='test_get_chunked$(EXEEXT)'; \ b='test_get_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close.log: test_get_chunked_close$(EXEEXT) @p='test_get_chunked_close$(EXEEXT)'; \ b='test_get_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_string.log: test_get_chunked_string$(EXEEXT) @p='test_get_chunked_string$(EXEEXT)'; \ b='test_get_chunked_string'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_string.log: test_get_chunked_close_string$(EXEEXT) @p='test_get_chunked_close_string$(EXEEXT)'; \ b='test_get_chunked_close_string'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty.log: test_get_chunked_empty$(EXEEXT) @p='test_get_chunked_empty$(EXEEXT)'; \ b='test_get_chunked_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty.log: test_get_chunked_close_empty$(EXEEXT) @p='test_get_chunked_close_empty$(EXEEXT)'; \ b='test_get_chunked_close_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_string_empty.log: test_get_chunked_string_empty$(EXEEXT) @p='test_get_chunked_string_empty$(EXEEXT)'; \ b='test_get_chunked_string_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_string_empty.log: test_get_chunked_close_string_empty$(EXEEXT) @p='test_get_chunked_close_string_empty$(EXEEXT)'; \ b='test_get_chunked_close_string_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_sized.log: test_get_chunked_sized$(EXEEXT) @p='test_get_chunked_sized$(EXEEXT)'; \ b='test_get_chunked_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_sized.log: test_get_chunked_close_sized$(EXEEXT) @p='test_get_chunked_close_sized$(EXEEXT)'; \ b='test_get_chunked_close_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty_sized.log: test_get_chunked_empty_sized$(EXEEXT) @p='test_get_chunked_empty_sized$(EXEEXT)'; \ b='test_get_chunked_empty_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty_sized.log: test_get_chunked_close_empty_sized$(EXEEXT) @p='test_get_chunked_close_empty_sized$(EXEEXT)'; \ b='test_get_chunked_close_empty_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_forced.log: test_get_chunked_forced$(EXEEXT) @p='test_get_chunked_forced$(EXEEXT)'; \ b='test_get_chunked_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_forced.log: test_get_chunked_close_forced$(EXEEXT) @p='test_get_chunked_close_forced$(EXEEXT)'; \ b='test_get_chunked_close_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty_forced.log: test_get_chunked_empty_forced$(EXEEXT) @p='test_get_chunked_empty_forced$(EXEEXT)'; \ b='test_get_chunked_empty_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty_forced.log: test_get_chunked_close_empty_forced$(EXEEXT) @p='test_get_chunked_close_empty_forced$(EXEEXT)'; \ b='test_get_chunked_close_empty_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked.log: test_put_chunked$(EXEEXT) @p='test_put_chunked$(EXEEXT)'; \ b='test_put_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_callback.log: test_callback$(EXEEXT) @p='test_callback$(EXEEXT)'; \ b='test_callback'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_header_fold.log: test_get_header_fold$(EXEEXT) @p='test_get_header_fold$(EXEEXT)'; \ b='test_get_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold.log: test_put_header_fold$(EXEEXT) @p='test_put_header_fold$(EXEEXT)'; \ b='test_put_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_header_fold.log: test_put_large_header_fold$(EXEEXT) @p='test_put_large_header_fold$(EXEEXT)'; \ b='test_put_large_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold_last.log: test_put_header_fold_last$(EXEEXT) @p='test_put_header_fold_last$(EXEEXT)'; \ b='test_put_header_fold_last'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold_large.log: test_put_header_fold_large$(EXEEXT) @p='test_put_header_fold_large$(EXEEXT)'; \ b='test_put_header_fold_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_header_double_fold.log: test_get_header_double_fold$(EXEEXT) @p='test_get_header_double_fold$(EXEEXT)'; \ b='test_get_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold.log: test_put_header_double_fold$(EXEEXT) @p='test_put_header_double_fold$(EXEEXT)'; \ b='test_put_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_header_double_fold.log: test_put_large_header_double_fold$(EXEEXT) @p='test_put_large_header_double_fold$(EXEEXT)'; \ b='test_put_large_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold_last.log: test_put_header_double_fold_last$(EXEEXT) @p='test_put_header_double_fold_last$(EXEEXT)'; \ b='test_put_header_double_fold_last'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold_large.log: test_put_header_double_fold_large$(EXEEXT) @p='test_put_header_double_fold_large$(EXEEXT)'; \ b='test_put_header_double_fold_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_p2.log: test_parse_cookies_discp_p2$(EXEEXT) @p='test_parse_cookies_discp_p2$(EXEEXT)'; \ b='test_parse_cookies_discp_p2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_p1.log: test_parse_cookies_discp_p1$(EXEEXT) @p='test_parse_cookies_discp_p1$(EXEEXT)'; \ b='test_parse_cookies_discp_p1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_zero.log: test_parse_cookies_discp_zero$(EXEEXT) @p='test_parse_cookies_discp_zero$(EXEEXT)'; \ b='test_parse_cookies_discp_zero'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_n2.log: test_parse_cookies_discp_n2$(EXEEXT) @p='test_parse_cookies_discp_n2$(EXEEXT)'; \ b='test_parse_cookies_discp_n2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_n3.log: test_parse_cookies_discp_n3$(EXEEXT) @p='test_parse_cookies_discp_n3$(EXEEXT)'; \ b='test_parse_cookies_discp_n3'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get.log: perf_get$(EXEEXT) @p='perf_get$(EXEEXT)'; \ b='perf_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth.log: test_basicauth$(EXEEXT) @p='test_basicauth$(EXEEXT)'; \ b='test_basicauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_preauth.log: test_basicauth_preauth$(EXEEXT) @p='test_basicauth_preauth$(EXEEXT)'; \ b='test_basicauth_preauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_oldapi.log: test_basicauth_oldapi$(EXEEXT) @p='test_basicauth_oldapi$(EXEEXT)'; \ b='test_basicauth_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_preauth_oldapi.log: test_basicauth_preauth_oldapi$(EXEEXT) @p='test_basicauth_preauth_oldapi$(EXEEXT)'; \ b='test_basicauth_preauth_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post.log: test_post$(EXEEXT) @p='test_post$(EXEEXT)'; \ b='test_post'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postform.log: test_postform$(EXEEXT) @p='test_postform$(EXEEXT)'; \ b='test_postform'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_loop.log: test_post_loop$(EXEEXT) @p='test_post_loop$(EXEEXT)'; \ b='test_post_loop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post11.log: test_post11$(EXEEXT) @p='test_post11$(EXEEXT)'; \ b='test_post11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postform11.log: test_postform11$(EXEEXT) @p='test_postform11$(EXEEXT)'; \ b='test_postform11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_loop11.log: test_post_loop11$(EXEEXT) @p='test_post_loop11$(EXEEXT)'; \ b='test_post_loop11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_emu_ext.log: test_digestauth_emu_ext$(EXEEXT) @p='test_digestauth_emu_ext$(EXEEXT)'; \ b='test_digestauth_emu_ext'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_emu_ext_oldapi.log: test_digestauth_emu_ext_oldapi$(EXEEXT) @p='test_digestauth_emu_ext_oldapi$(EXEEXT)'; \ b='test_digestauth_emu_ext_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2.log: test_digestauth2$(EXEEXT) @p='test_digestauth2$(EXEEXT)'; \ b='test_digestauth2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_rfc2069.log: test_digestauth2_rfc2069$(EXEEXT) @p='test_digestauth2_rfc2069$(EXEEXT)'; \ b='test_digestauth2_rfc2069'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_rfc2069_userdigest.log: test_digestauth2_rfc2069_userdigest$(EXEEXT) @p='test_digestauth2_rfc2069_userdigest$(EXEEXT)'; \ b='test_digestauth2_rfc2069_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1.log: test_digestauth2_oldapi1$(EXEEXT) @p='test_digestauth2_oldapi1$(EXEEXT)'; \ b='test_digestauth2_oldapi1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2.log: test_digestauth2_oldapi2$(EXEEXT) @p='test_digestauth2_oldapi2$(EXEEXT)'; \ b='test_digestauth2_oldapi2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userhash.log: test_digestauth2_userhash$(EXEEXT) @p='test_digestauth2_userhash$(EXEEXT)'; \ b='test_digestauth2_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userdigest.log: test_digestauth2_userdigest$(EXEEXT) @p='test_digestauth2_userdigest$(EXEEXT)'; \ b='test_digestauth2_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_userdigest.log: test_digestauth2_oldapi1_userdigest$(EXEEXT) @p='test_digestauth2_oldapi1_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi1_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_userdigest.log: test_digestauth2_oldapi2_userdigest$(EXEEXT) @p='test_digestauth2_oldapi2_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi2_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userhash_userdigest.log: test_digestauth2_userhash_userdigest$(EXEEXT) @p='test_digestauth2_userhash_userdigest$(EXEEXT)'; \ b='test_digestauth2_userhash_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_bind_all.log: test_digestauth2_bind_all$(EXEEXT) @p='test_digestauth2_bind_all$(EXEEXT)'; \ b='test_digestauth2_bind_all'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_bind_uri.log: test_digestauth2_bind_uri$(EXEEXT) @p='test_digestauth2_bind_uri$(EXEEXT)'; \ b='test_digestauth2_bind_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_bind_all.log: test_digestauth2_oldapi1_bind_all$(EXEEXT) @p='test_digestauth2_oldapi1_bind_all$(EXEEXT)'; \ b='test_digestauth2_oldapi1_bind_all'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_bind_uri.log: test_digestauth2_oldapi1_bind_uri$(EXEEXT) @p='test_digestauth2_oldapi1_bind_uri$(EXEEXT)'; \ b='test_digestauth2_oldapi1_bind_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256.log: test_digestauth2_sha256$(EXEEXT) @p='test_digestauth2_sha256$(EXEEXT)'; \ b='test_digestauth2_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userhash.log: test_digestauth2_sha256_userhash$(EXEEXT) @p='test_digestauth2_sha256_userhash$(EXEEXT)'; \ b='test_digestauth2_sha256_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_sha256.log: test_digestauth2_oldapi2_sha256$(EXEEXT) @p='test_digestauth2_oldapi2_sha256$(EXEEXT)'; \ b='test_digestauth2_oldapi2_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userdigest.log: test_digestauth2_sha256_userdigest$(EXEEXT) @p='test_digestauth2_sha256_userdigest$(EXEEXT)'; \ b='test_digestauth2_sha256_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_sha256_userdigest.log: test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) @p='test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi2_sha256_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userhash_userdigest.log: test_digestauth2_sha256_userhash_userdigest$(EXEEXT) @p='test_digestauth2_sha256_userhash_userdigest$(EXEEXT)'; \ b='test_digestauth2_sha256_userhash_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_response_cleanup.log: test_get_response_cleanup$(EXEEXT) @p='test_get_response_cleanup$(EXEEXT)'; \ b='test_get_response_cleanup'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_urlparse.log: test_urlparse$(EXEEXT) @p='test_urlparse$(EXEEXT)'; \ b='test_urlparse'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_long_header.log: test_long_header$(EXEEXT) @p='test_long_header$(EXEEXT)'; \ b='test_long_header'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_long_header11.log: test_long_header11$(EXEEXT) @p='test_long_header11$(EXEEXT)'; \ b='test_long_header11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_iplimit11.log: test_iplimit11$(EXEEXT) @p='test_iplimit11$(EXEEXT)'; \ b='test_iplimit11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_termination.log: test_termination$(EXEEXT) @p='test_termination$(EXEEXT)'; \ b='test_termination'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_cleanup.log: test_add_conn_cleanup$(EXEEXT) @p='test_add_conn_cleanup$(EXEEXT)'; \ b='test_add_conn_cleanup'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_cleanup_nolisten.log: test_add_conn_cleanup_nolisten$(EXEEXT) @p='test_add_conn_cleanup_nolisten$(EXEEXT)'; \ b='test_add_conn_cleanup_nolisten'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_timeout.log: test_timeout$(EXEEXT) @p='test_timeout$(EXEEXT)'; \ b='test_timeout'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get_concurrent11.log: perf_get_concurrent11$(EXEEXT) @p='perf_get_concurrent11$(EXEEXT)'; \ b='perf_get_concurrent11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_wait.log: test_get_wait$(EXEEXT) @p='test_get_wait$(EXEEXT)'; \ b='test_get_wait'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_wait11.log: test_get_wait11$(EXEEXT) @p='test_get_wait11$(EXEEXT)'; \ b='test_get_wait11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_concurrent_stop.log: test_concurrent_stop$(EXEEXT) @p='test_concurrent_stop$(EXEEXT)'; \ b='test_concurrent_stop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_quiesce.log: test_quiesce$(EXEEXT) @p='test_quiesce$(EXEEXT)'; \ b='test_quiesce'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_quiesce_stream.log: test_quiesce_stream$(EXEEXT) @p='test_quiesce_stream$(EXEEXT)'; \ b='test_quiesce_stream'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get_concurrent.log: perf_get_concurrent$(EXEEXT) @p='perf_get_concurrent$(EXEEXT)'; \ b='perf_get_concurrent'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth.log: test_digestauth$(EXEEXT) @p='test_digestauth$(EXEEXT)'; \ b='test_digestauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_with_arguments.log: test_digestauth_with_arguments$(EXEEXT) @p='test_digestauth_with_arguments$(EXEEXT)'; \ b='test_digestauth_with_arguments'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_concurrent.log: test_digestauth_concurrent$(EXEEXT) @p='test_digestauth_concurrent$(EXEEXT)'; \ b='test_digestauth_concurrent'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_sha256.log: test_digestauth_sha256$(EXEEXT) @p='test_digestauth_sha256$(EXEEXT)'; \ b='test_digestauth_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/perf_get.Po -rm -f ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/test_add_conn-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_basicauth.Po -rm -f ./$(DEPDIR)/test_callback.Po -rm -f ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po -rm -f ./$(DEPDIR)/test_delete.Po -rm -f ./$(DEPDIR)/test_digestauth.Po -rm -f ./$(DEPDIR)/test_digestauth2.Po -rm -f ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po -rm -f ./$(DEPDIR)/test_digestauth_emu_ext.Po -rm -f ./$(DEPDIR)/test_digestauth_sha256.Po -rm -f ./$(DEPDIR)/test_digestauth_with_arguments.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_chunked.Po -rm -f ./$(DEPDIR)/test_get_close_keep_alive.Po -rm -f ./$(DEPDIR)/test_get_iovec.Po -rm -f ./$(DEPDIR)/test_get_response_cleanup.Po -rm -f ./$(DEPDIR)/test_get_sendfile.Po -rm -f ./$(DEPDIR)/test_get_wait-test_get_wait.Po -rm -f ./$(DEPDIR)/test_get_wait11-test_get_wait.Po -rm -f ./$(DEPDIR)/test_head.Po -rm -f ./$(DEPDIR)/test_iplimit.Po -rm -f ./$(DEPDIR)/test_large_put.Po -rm -f ./$(DEPDIR)/test_long_header.Po -rm -f ./$(DEPDIR)/test_parse_cookies.Po -rm -f ./$(DEPDIR)/test_patch.Po -rm -f ./$(DEPDIR)/test_post.Po -rm -f ./$(DEPDIR)/test_post_loop.Po -rm -f ./$(DEPDIR)/test_postform.Po -rm -f ./$(DEPDIR)/test_process_arguments.Po -rm -f ./$(DEPDIR)/test_process_headers.Po -rm -f ./$(DEPDIR)/test_put.Po -rm -f ./$(DEPDIR)/test_put_broken_len.Po -rm -f ./$(DEPDIR)/test_put_chunked.Po -rm -f ./$(DEPDIR)/test_put_header_fold.Po -rm -f ./$(DEPDIR)/test_quiesce-test_quiesce.Po -rm -f ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po -rm -f ./$(DEPDIR)/test_termination.Po -rm -f ./$(DEPDIR)/test_timeout.Po -rm -f ./$(DEPDIR)/test_toolarge.Po -rm -f ./$(DEPDIR)/test_tricky.Po -rm -f ./$(DEPDIR)/test_urlparse.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/perf_get.Po -rm -f ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/test_add_conn-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_basicauth.Po -rm -f ./$(DEPDIR)/test_callback.Po -rm -f ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po -rm -f ./$(DEPDIR)/test_delete.Po -rm -f ./$(DEPDIR)/test_digestauth.Po -rm -f ./$(DEPDIR)/test_digestauth2.Po -rm -f ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po -rm -f ./$(DEPDIR)/test_digestauth_emu_ext.Po -rm -f ./$(DEPDIR)/test_digestauth_sha256.Po -rm -f ./$(DEPDIR)/test_digestauth_with_arguments.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_chunked.Po -rm -f ./$(DEPDIR)/test_get_close_keep_alive.Po -rm -f ./$(DEPDIR)/test_get_iovec.Po -rm -f ./$(DEPDIR)/test_get_response_cleanup.Po -rm -f ./$(DEPDIR)/test_get_sendfile.Po -rm -f ./$(DEPDIR)/test_get_wait-test_get_wait.Po -rm -f ./$(DEPDIR)/test_get_wait11-test_get_wait.Po -rm -f ./$(DEPDIR)/test_head.Po -rm -f ./$(DEPDIR)/test_iplimit.Po -rm -f ./$(DEPDIR)/test_large_put.Po -rm -f ./$(DEPDIR)/test_long_header.Po -rm -f ./$(DEPDIR)/test_parse_cookies.Po -rm -f ./$(DEPDIR)/test_patch.Po -rm -f ./$(DEPDIR)/test_post.Po -rm -f ./$(DEPDIR)/test_post_loop.Po -rm -f ./$(DEPDIR)/test_postform.Po -rm -f ./$(DEPDIR)/test_process_arguments.Po -rm -f ./$(DEPDIR)/test_process_headers.Po -rm -f ./$(DEPDIR)/test_put.Po -rm -f ./$(DEPDIR)/test_put_broken_len.Po -rm -f ./$(DEPDIR)/test_put_chunked.Po -rm -f ./$(DEPDIR)/test_put_header_fold.Po -rm -f ./$(DEPDIR)/test_quiesce-test_quiesce.Po -rm -f ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po -rm -f ./$(DEPDIR)/test_termination.Po -rm -f ./$(DEPDIR)/test_timeout.Po -rm -f ./$(DEPDIR)/test_toolarge.Po -rm -f ./$(DEPDIR)/test_tricky.Po -rm -f ./$(DEPDIR)/test_urlparse.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile @HEAVY_TESTS_NOTPARALLEL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/testcurl/test_quiesce.c0000644000175000017500000005643014760713574016622 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2013, 2015 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_quiesce.c * @brief Testcase for libmicrohttpd quiescing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include "mhd_sockets.h" /* only macros used */ #include "mhd_has_in_name.h" #include "mhd_has_param.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 4 #define MHD_URI_BASE_PATH "/hello_world" /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) { fprintf (stderr, "Unexpected HTTP method '%s'. ", method); externalErrorExit (); } if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) mhdErrorExitDesc ("MHD_create_response failed"); /* Make sure that connection will not be reused */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close")) mhdErrorExitDesc ("MHD_add_response_header() failed"); if (MHD_NO == MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("MHD_queue_response() failed"); MHD_destroy_response (response); return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode code) { int *done = (int *) cls; (void) connection; (void) req_cls; (void) code; /* Unused. Silent compiler warning. */ if (MHD_REQUEST_TERMINATED_COMPLETED_OK != code) { fprintf (stderr, "Unexpected termination code: %d. ", (int) code); mhdErrorExit (); } *done = 1; if (verbose) printf ("Notify callback has been called with OK code.\n"); } static void * ServeOneRequest (void *param) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket fd, max; time_t start; struct timeval tv; volatile int done = 0; if (NULL == param) externalErrorExit (); fd = *((MHD_socket *) param); d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_LISTEN_SOCKET, fd, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, &done, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (verbose) printf ("Started MHD daemon in ServeOneRequest().\n"); start = time (NULL); while ((time (NULL) - start < TIMEOUTS_VAL * 2) && done == 0) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) mhdErrorExit ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 100000; if (-1 == MHD_SYS_select_ (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } MHD_run (d); } if (! done) mhdErrorExit ("ServeOneRequest() failed and finished by timeout"); fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExit ("MHD_quiesce_daemon() failed in ServeOneRequest()"); MHD_stop_daemon (d); return NULL; } static CURL * setupCURL (void *cbc) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" MHD_URI_BASE_PATH)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) global_port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) (TIMEOUTS_VAL / 2))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) TIMEOUTS_VAL)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static unsigned int testGet (unsigned int type, int pool_count, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; MHD_socket fd; pthread_t thrd; char *thrdRet; if (verbose) printf ("testGet(%u, %d, %u) test started.\n", type, pool_count, (unsigned int) poll_flag); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; if (pool_count > 0) { d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) pool_count, MHD_OPTION_END); } else { d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); } if (d == NULL) mhdErrorExitDesc ("MHD_start_daemon() failed"); if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); global_port = dinfo->port; } c = setupCURL (&cbc); checkCURLE_OK (curl_easy_perform (c)); if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Received valid response data.\n"); fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExitDesc ("MHD_quiesce_daemon failed"); if (0 != pthread_create (&thrd, NULL, &ServeOneRequest, (void *) &fd)) externalErrorExitDesc ("pthread_create() failed"); /* No need for the thread sync as socket is already listening, * so libcurl may start connecting before MHD is started in another thread */ cbc.pos = 0; checkCURLE_OK (curl_easy_perform (c)); if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (0 != pthread_join (thrd, (void **) &thrdRet)) externalErrorExitDesc ("pthread_join() failed"); if (NULL != thrdRet) externalErrorExitDesc ("ServeOneRequest() returned non-NULL result"); if (verbose) { printf ("ServeOneRequest() thread was joined.\n"); fflush (stdout); } /* at this point, the forked server quiesced and quit, * so new requests should fail */ cbc.pos = 0; if (CURLE_OK == curl_easy_perform (c)) { fprintf (stderr, "curl_easy_perform() succeed while it should fail. "); fprintf (stderr, "Got %u bytes ('%.*s'), " "valid data would be %u bytes (%s). ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH), MHD_URI_BASE_PATH); mhdErrorExitDesc ("Unexpected succeed request"); } if (verbose) printf ("curl_easy_perform() failed as expected.\n"); curl_easy_cleanup (c); MHD_stop_daemon (d); MHD_socket_close_chk_ (fd); if (verbose) { printf ("testGet(%u, %d, %u) test succeed.\n", type, pool_count, (unsigned int) poll_flag); fflush (stdout); } return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int running; struct CURLMsg *msg; time_t start; struct timeval tv; int i; MHD_socket fd = MHD_INVALID_SOCKET; if (verbose) printf ("testExternalGet test started.\n"); fd = MHD_INVALID_SOCKET; multi = NULL; cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); global_port = dinfo->port; } for (i = 0; i < 2; i++) { c = setupCURL (&cbc); multi = curl_multi_init (); if (multi == NULL) libcurlErrorExit (); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) libcurlErrorExit (); start = time (NULL); while ( (time (NULL) - start < TIMEOUTS_VAL * 2) && (NULL != multi) ) { MHD_socket maxsock; int maxposixs; maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) libcurlErrorExit (); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) mhdErrorExit (); #ifndef MHD_WINSOCK_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 100000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) { curl_fine = 1; if (verbose) printf ("libcurl reported success.\n"); } else if (i == 0) { fprintf (stderr, "curl_multi_perform() failed with '%s'. ", curl_easy_strerror (msg->data.result)); mhdErrorExit (); } } } if (i == 0) { if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); mhdErrorExit (); } /* MHD is running, result should be correct */ if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) { printf ("First request was successful.\n"); fflush (stdout); } } else if (i == 1) { if (curl_fine) { fprintf (stderr, "libcurl returned OK code, while it shouldn't\n"); mhdErrorExit (); } if (verbose) printf ("Second request failed as expected.\n"); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; break; } MHD_run (d); } if (NULL != multi) mhdErrorExitDesc ("Test failed and finished by timeout"); if (0 == i) { /* quiesce the daemon on the 1st iteration, so the 2nd should fail */ fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExitDesc ("MHD_quiesce_daemon() failed"); } } MHD_stop_daemon (d); if (MHD_INVALID_SOCKET == fd) { fprintf (stderr, "Failed to MHD_quiesce_daemon() at some point. "); externalErrorExit (); } MHD_socket_close_chk_ (fd); if (verbose) { printf ("testExternalGet succeed.\n"); fflush (stdout); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; oneone = ! has_in_name (argv[0], "10"); verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) global_port = 0; else global_port = 1480 + (oneone ? 1 : 0); errorCount += testExternalGet (); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, 0); errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, 0, 0); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL); errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_EPOLL); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, MHD_USE_EPOLL); } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_get_sendfile.c0000644000175000017500000004341614760713574017614 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_sendfile.c * @brief Testcase for libmicrohttpd response from FD * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include "mhd_sockets.h" #include "mhd_has_in_name.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define TESTSTR \ "This is the content of the test file we are sending using sendfile (if available)" static char *sourcefile; static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; int fd; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; fd = open (sourcefile, O_RDONLY); if (fd == -1) { fprintf (stderr, "Failed to open `%s': %s\n", sourcefile, strerror (errno)); exit (1); } response = MHD_create_response_from_fd (strlen (TESTSTR), fd); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1200; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 4; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1201; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 64; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1202; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 64; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1203; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) { fprintf (stderr, "Got %.*s instead of %s!\n", (int) cbc.pos, cbc.buf, TESTSTR); return 8192; } if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 16384; return 0; } static unsigned int testUnknownPortGet (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_END); if (d == NULL) return 32768; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = (uint16_t) ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 1048576; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 2097152; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *tmp; FILE *f; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if ( (NULL == (tmp = getenv ("TMPDIR"))) && (NULL == (tmp = getenv ("TMP"))) && (NULL == (tmp = getenv ("TEMP"))) ) tmp = "/tmp"; sourcefile = malloc (strlen (tmp) + 32); snprintf (sourcefile, strlen (tmp) + 32, "%s/%s%s", tmp, "test-mhd-sendfile", oneone ? "11" : ""); f = fopen (sourcefile, "w"); if (NULL == f) { fprintf (stderr, "failed to write test file\n"); free (sourcefile); return 1; } if (1 != fwrite (TESTSTR, strlen (TESTSTR), 1, f)) abort (); fclose (f); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); errorCount += testUnknownPortGet (); errorCount += testExternalGet (0); } errorCount += testExternalGet (! 0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); unlink (sourcefile); free (sourcefile); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_postform.c0000644000175000017500000005041614760713574017033 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postform.c * @brief Testcase for libmicrohttpd POST operations using multipart/postform data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H #include #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include #ifndef WINDOWS #include #endif #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if CURL_AT_LEAST_VERSION (7,56,0) #define HAS_CURL_MIME 1 #endif /* CURL_AT_LEAST_VERSION(7,56,0) */ #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct MHD_PostProcessor *pp = *req_cls; (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */ if (NULL != pp) MHD_destroy_post_processor (pp); *req_cls = NULL; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * Note that this post_iterator is not perfect * in that it fails to support incremental processing. * (to be fixed in the future) */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { int *eok = cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) off; /* Unused. Silent compiler warning. */ #if 0 fprintf (stderr, "PI sees %s-%.*s\n", key, size, value); #endif if ((0 == strcmp (key, "name")) && (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size))) (*eok) |= 1; if ((0 == strcmp (key, "project")) && (size == strlen ("curl")) && (0 == strncmp (value, "curl", size))) (*eok) |= 2; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int eok; struct MHD_Response *response; struct MHD_PostProcessor *pp; enum MHD_Result ret; (void) cls; (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { printf ("METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } pp = *req_cls; if (pp == NULL) { eok = 0; pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok); if (NULL == pp) abort (); *req_cls = pp; } if (MHD_YES != MHD_post_process (pp, upload_data, *upload_data_size)) abort (); if ((eok == 3) && (0 == *upload_data_size)) { response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); MHD_destroy_post_processor (pp); *req_cls = NULL; return ret; } *upload_data_size = 0; return MHD_YES; } struct mhd_test_postdata { #if defined(HAS_CURL_MIME) curl_mime *mime; #else /* ! HAS_CURL_MIME */ struct curl_httppost *post; #endif /* ! HAS_CURL_MIME */ }; /* Return non-zero if succeed */ static int add_test_form (CURL *handle, struct mhd_test_postdata *postdata) { #if defined(HAS_CURL_MIME) postdata->mime = curl_mime_init (handle); if (NULL == postdata->mime) return 0; else { curl_mimepart *part; part = curl_mime_addpart (postdata->mime); if (NULL != part) { if ( (CURLE_OK == curl_mime_data (part, "daniel", CURL_ZERO_TERMINATED)) && (CURLE_OK == curl_mime_name (part, "name")) ) { part = curl_mime_addpart (postdata->mime); if (NULL != part) { if ( (CURLE_OK == curl_mime_data (part, "curl", CURL_ZERO_TERMINATED)) && (CURLE_OK == curl_mime_name (part, "project")) ) { if (CURLE_OK == curl_easy_setopt (handle, CURLOPT_MIMEPOST, postdata->mime)) { return ! 0; } } } } } } curl_mime_free (postdata->mime); postdata->mime = NULL; return 0; #else /* ! HAS_CURL_MIME */ postdata->post = NULL; struct curl_httppost *last = NULL; if (0 == curl_formadd (&postdata->post, &last, CURLFORM_COPYNAME, "name", CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END)) { if (0 == curl_formadd (&postdata->post, &last, CURLFORM_COPYNAME, "project", CURLFORM_COPYCONTENTS, "curl", CURLFORM_END)) { if (CURLE_OK == curl_easy_setopt (handle, CURLOPT_HTTPPOST, postdata->post)) { return ! 0; } } } curl_formfree (postdata->post); return 0; #endif /* ! HAS_CURL_MIME */ } static void free_test_form (struct mhd_test_postdata *postdata) { #if defined(HAS_CURL_MIME) if (NULL != postdata->mime) curl_mime_free (postdata->mime); #else /* ! HAS_CURL_MIME */ if (NULL != postdata->post) curl_formfree (postdata->post); #endif /* ! HAS_CURL_MIME */ } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1390; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1390; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1391; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1392; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); free_test_form (&form); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); free_test_form (&form); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPost (); errorCount += testMultithreadedPost (); errorCount += testMultithreadedPoolPost (); } errorCount += testExternalPost (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_delete.c0000644000175000017500000003735714760713574016435 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_delete.c * @brief Testcase for libmicrohttpd DELETE operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("DELETE", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1152; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1153; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1154; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1154; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalDelete (); errorCount += testMultithreadedDelete (); errorCount += testMultithreadedPoolDelete (); } errorCount += testExternalDelete (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_parse_cookies.c0000644000175000017500000011401114760713574020000 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_parse_cookies.c * @brief Testcase for HTTP cookie parsing * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 500000 #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define PAGE \ "libmicrohttpd test page" \ "Success!" #define PAGE_ERROR \ "Cookies parsing error" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ struct strct_str_len { const char *str; const size_t len; }; #define STR_LEN_(str) {str, MHD_STATICSTR_LEN_ (str)} #define STR_NULL_ {NULL, 0} struct strct_cookie { struct strct_str_len name; struct strct_str_len value; }; #define COOKIE_(name,value) {STR_LEN_ (name), STR_LEN_ (value)} #define COOKIE_NULL {STR_NULL_, STR_NULL_} struct strct_test_data { unsigned int line_num; const char *header_str; unsigned int num_cookies_strict_p2; unsigned int num_cookies_strict_p1; unsigned int num_cookies_strict_zero; unsigned int num_cookies_strict_n2; unsigned int num_cookies_strict_n3; struct strct_cookie cookies[5]; }; static const struct strct_test_data test_data[] = { { __LINE__, "name1=value1", 1, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;", 0, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; ", 0, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "; name1=value1", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";name1=value1", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ", 1, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ;", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ; ", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name2=\"value 2\"", 0, 0, 0, 1, 1, { COOKIE_ ("name2", "value 2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;\tname2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name1=value1", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name1", "value1"), /* The second value is not checked actually */ COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2 ", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;name2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;\tname2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ; name2=value2", 0, 0, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, " name1=value1; name2=value2", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1;name2=var2;name3=;" \ "name4=\"var4 with spaces\";" \ "name5=var_with_=_char", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char\t \t", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1;;name2=var2;;name3=;;" \ "name4=\"var4 with spaces\";;" \ "name5=var_with_=_char;\t \t", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name3=; name1=var1; name2=var2; " \ "name5=var_with_=_char;" \ "name4=\"var4 with spaces\"", 0, 4, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name5=var_with_=_char; name3=; " \ "name4=\"var4 with spaces\";", 0, 4, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name5=var_with_=_char; " \ "name4=\"var4 with spaces\"; name3=", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char; name3=;", 0, 2, 2, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, ";;;;;;;;name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char", 0, 0, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; ; ; ; ; " \ "name5=var_with_=_char", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char;;;;;;;;", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; " \ "name4=\"var4 with spaces\";" \ "name5=var_with_=_char; ; ; ; ; name3=", 0, 2, 2, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char ;" \ "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\" ", 0, 0, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char; name4=\"var4 with spaces\";" \ "name1=var1; name2=var2; name3=", 0, 1, 1, 5, 5, { COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char; name4=\"var4_without_spaces\"; " \ "name1=var1; name2=var2; name3=", 5, 5, 5, 5, 5, { COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4_without_spaces") } }, { __LINE__, "name1 = value1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1\t=\tvalue1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1\t = \tvalue1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1 = value1; name2 =\tvalue2", 0, 0, 0, 0, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2 =\tvalue2", 0, 1, 1, 1, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1 = value1; name2=value2", 0, 0, 0, 0, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, " ", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "\t", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=,", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=\"\\ \"", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=value space", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=value\ttab", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "=", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "====", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";=", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "=;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "= ;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";= ;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } } }; /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static int use_discp_n3; static int use_discp_n2; static int use_discp_zero; static int use_discp_p1; static int use_discp_p2; static int discp_level; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; const struct strct_test_data *check; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int expected_num_cookies; unsigned int i; int cookie_failed; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (use_discp_p2) expected_num_cookies = param->check->num_cookies_strict_p2; else if (use_discp_p1) expected_num_cookies = param->check->num_cookies_strict_p1; else if (use_discp_zero) expected_num_cookies = param->check->num_cookies_strict_zero; else if (use_discp_n2) expected_num_cookies = param->check->num_cookies_strict_n2; else if (use_discp_n3) expected_num_cookies = param->check->num_cookies_strict_n3; else externalErrorExit (); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); cookie_failed = 0; for (i = 0; i < expected_num_cookies; ++i) { const char *cookie_val; size_t cookie_val_len; const struct strct_cookie *const cookie_data = param->check->cookies + i; if (NULL == cookie_data->name.str) externalErrorExitDesc ("Broken test data"); if (NULL == cookie_data->value.str) externalErrorExitDesc ("Broken test data"); cookie_val = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, cookie_data->name.str); if (cookie_val == NULL) { fprintf (stderr, "'%s' cookie not found.\n", cookie_data->name.str); cookie_failed = 1; } else if (0 != strcmp (cookie_val, cookie_data->value.str)) { fprintf (stderr, "'%s' cookie decoded incorrectly.\n" "Expected: %s\nGot: %s\n", cookie_data->name.str, cookie_data->value.str, cookie_val); cookie_failed = 1; } else if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_COOKIE_KIND, cookie_data->name.str, cookie_data->name.len, &cookie_val, &cookie_val_len)) { fprintf (stderr, "'%s' (length %lu) cookie not found.\n", cookie_data->name.str, (unsigned long) cookie_data->name.len); cookie_failed = 1; } else { if (cookie_data->value.len != cookie_val_len) { fprintf (stderr, "'%s' (length %lu) cookie has wrong value length.\n" "Expected: %lu\nGot: %lu\n", cookie_data->name.str, (unsigned long) cookie_data->name.len, (unsigned long) cookie_data->value.len, (unsigned long) cookie_val_len); cookie_failed = 1; } else if (0 != memcmp (cookie_val, cookie_data->value.str, cookie_val_len)) { fprintf (stderr, "'%s' (length %lu) cookie has wrong value.\n" "Expected: %.*s\nGot: %.*s\n", cookie_data->name.str, (unsigned long) cookie_data->name.len, (int) cookie_data->value.len, cookie_data->value.str, (int) cookie_val_len, cookie_val); cookie_failed = 1; } } } if (((int) expected_num_cookies) != MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL, NULL)) { fprintf (stderr, "Wrong total number of cookies.\n" "Expected: %u\nGot: %d\n", expected_num_cookies, MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL, NULL)); cookie_failed = 1; } if (cookie_failed) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_ERROR), PAGE_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); return ret; } if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URL"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct CBC *pcbc) { long code; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "### The response has wrong HTTP code: %ld\t" "Expected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("### The response has expected HTTP code: %ld\n", expected_code); if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } fflush (stderr); fflush (stdout); return 1; } static unsigned int testExternalPolling (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; char buf[2048]; CURL *c; CURLM *multi_reuse; size_t i; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1340 + oneone ? 0 : 6 + (uint16_t) (1 + discp_level); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) (discp_level), MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } ahc_param.rq_method = MHD_HTTP_METHOD_GET; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; cbc.buf = buf; cbc.size = sizeof (buf); memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); ++i) { cbc.pos = 0; ahc_param.check = test_data + i; if (CURLE_OK != curl_easy_setopt (c, CURLOPT_COOKIE, ahc_param.check->header_str)) libcurlErrorExitDesc ("Cannot set request cookies"); if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc)) { if (verbose) printf ("### Got expected response for the check at line %u.\n", test_data[i].line_num); fflush (stdout); } else { fprintf (stderr, "### FAILED request for the check at line %u.\n", test_data[i].line_num); fflush (stderr); failed = 1; } } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); use_discp_n3 = has_in_name (argv[0], "_discp_n3"); use_discp_n2 = has_in_name (argv[0], "_discp_n2"); use_discp_zero = has_in_name (argv[0], "_discp_zero"); use_discp_p1 = has_in_name (argv[0], "_discp_p1"); use_discp_p2 = has_in_name (argv[0], "_discp_p2"); if (1 != ((use_discp_n3 ? 1 : 0) + (use_discp_n2 ? 1 : 0) + (use_discp_zero ? 1 : 0) + (use_discp_p1 ? 1 : 0) + (use_discp_p2 ? 1 : 0))) return 99; if (use_discp_n3) discp_level = -3; else if (use_discp_n2) discp_level = -2; else if (use_discp_zero) discp_level = 0; else if (use_discp_p1) discp_level = 1; else if (use_discp_p2) discp_level = 2; test_global_init (); errorCount += testExternalPolling (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth_concurrent.c0000644000175000017500000005356214760713574021572 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digestauth_concurrent.c * @brief Testcase for libmicrohttpd concurrent Digest Authorisation * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #include #ifndef WINDOWS #include #include #else #include #endif #include #include "mhd_has_param.h" #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static int verbose; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; enum MHD_DigestAuthResult ret_e; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed"); MHD_destroy_response (response); return ret; } ret_e = MHD_digest_auth_check3 (connection, realm, username, password, 50 * TIMEOUTS_VAL, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO3_MD5); MHD_free (username); if (ret_e != MHD_DAUTH_OK) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_DAUTH_NONCE_STALE == ret_e) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port, char *errbuf) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when digest authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); return c; } static void getRnd (void *buf, size_t size) { #ifndef WINDOWS int fd; size_t off = 0; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) externalErrorExitDesc ("Failed to open '/dev/urandom'"); do { ssize_t res; res = read (fd, ((uint8_t *) buf) + off, size - off); if (0 > res) externalErrorExitDesc ("Failed to read '/dev/urandom'"); off += (size_t) res; } while (off < size); (void) close (fd); #else HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); if (b == 0) externalErrorExitDesc ("CryptAcquireContext() failed"); b = CryptGenRandom (cc, (DWORD) size, (BYTE *) buf); if (b == 0) externalErrorExitDesc ("CryptGenRandom() failed"); CryptReleaseContext (cc, 0); #endif /* ! WINDOWS */ } struct curlWokerInfo { int workerNumber; struct CBC cbc; pthread_t tid; /** * The libcurl handle to run in thread */ CURL *c; char *libcurl_errbuf; /** * Non-zero if worker is finished */ volatile int finished; /** * The number of successful worker results */ volatile unsigned int success; }; static void * worker_func (void *param) { struct curlWokerInfo *const w = (struct curlWokerInfo *) param; CURLcode req_result; if (NULL == w) externalErrorExit (); req_result = curl_easy_perform (w->c); if (CURLE_OK != req_result) { if (0 != w->libcurl_errbuf[0]) fprintf (stderr, "Worker %d: first request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result), w->libcurl_errbuf); else fprintf (stderr, "Worker %d: first request failed. " "libcurl error: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result)); } else { if (w->cbc.pos != strlen (PAGE)) { fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ", w->workerNumber, (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE))) { fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ", w->workerNumber, (int) w->cbc.pos, w->cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Worker %d: first request successful.\n", w->workerNumber); w->success++; } #ifdef _DEBUG fflush (stderr); fflush (stdout); #endif /* _DEBUG */ /* Second request */ w->cbc.pos = 0; req_result = curl_easy_perform (w->c); if (CURLE_OK != req_result) { if (0 != w->libcurl_errbuf[0]) fprintf (stderr, "Worker %d: second request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result), w->libcurl_errbuf); else fprintf (stderr, "Worker %d: second request failed. " "libcurl error: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result)); } else { if (w->cbc.pos != strlen (PAGE)) { fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ", w->workerNumber, (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE))) { fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ", w->workerNumber, (int) w->cbc.pos, w->cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Worker %d: second request successful.\n", w->workerNumber); w->success++; } #ifdef _DEBUG fflush (stderr); fflush (stdout); #endif /* _DEBUG */ w->finished = ! 0; return NULL; } #define CLIENT_BUF_SIZE 2048 static unsigned int testDigestAuth (void) { struct MHD_Daemon *d; char rnd[8]; uint16_t port; size_t i; /* Run three workers in parallel so at least two workers would start within * the same monotonic clock second.*/ struct curlWokerInfo workers[3]; unsigned int ret; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4200; getRnd (rnd, sizeof(rnd)); d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) (sizeof(workers) / sizeof(workers[0])), MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* Initialise all workers */ for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; w->workerNumber = (int) i + 1; /* Use 1-based numbering */ w->cbc.buf = malloc (CLIENT_BUF_SIZE); if (NULL == w->cbc.buf) externalErrorExitDesc ("malloc() failed"); w->cbc.size = CLIENT_BUF_SIZE; w->cbc.pos = 0; w->libcurl_errbuf = malloc (CURL_ERROR_SIZE); if (NULL == w->libcurl_errbuf) externalErrorExitDesc ("malloc() failed"); w->libcurl_errbuf[0] = 0; w->c = setupCURL (&w->cbc, port, w->libcurl_errbuf); w->finished = 0; w->success = 0; } /* Fire already initialised workers */ for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; if (0 != pthread_create (&w->tid, NULL, &worker_func, w)) externalErrorExitDesc ("pthread_create() failed"); } /* Collect results, cleanup workers */ ret = 0; for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; if (0 != pthread_join (w->tid, NULL)) externalErrorExitDesc ("pthread_join() failed"); curl_easy_cleanup (w->c); free (w->libcurl_errbuf); free (w->cbc.buf); if (! w->finished) externalErrorExitDesc ("The worker thread did't signal 'finished' state"); ret += 2 - w->success; } MHD_stop_daemon (d); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing " "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth_emu_ext.c0000644000175000017500000007002614760713574021050 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digest_emu_ext.c * @brief Testcase for MHD Digest Authorisation client's header parsing * @author Karlson2k (Evgeny Grin) * * libcurl does not support extended notation for username, so this test * "emulates" client request will all valid fields except nonce, cnonce and * response (however syntactically these fields valid as well). */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define REALM "TestRealm" /* "titkos szuperügynök" in UTF-8 */ #define USERNAME "titkos szuper" "\xC3\xBC" "gyn" "\xC3\xB6" "k" /* percent-encoded username */ #define USERNAME_PCTENC "titkos%20szuper%C3%BCgyn%C3%B6k" #define PASSWORD_VALUE "fake pass" #define OPAQUE_VALUE "opaque-content" #define NONCE_EMU "badbadbadbadbadbadbadbadbadbadbadbadbadbadba" #define CNONCE_EMU "utututututututututututututututututututututs=" #define RESPONSE_EMU "badbadbadbadbadbadbadbadbadbadba" #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" struct CBC { char *buf; size_t pos; size_t size; }; /* Global parameters */ static int verbose; static int oldapi; /* Static helper variables */ static struct curl_slist *curl_headers; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); curl_headers = NULL; curl_headers = curl_slist_append (curl_headers, "Authorization: " "Digest username*=UTF-8''" USERNAME_PCTENC ", " "realm=\"" REALM "\", " "nonce=\"" NONCE_EMU "\", " "uri=\"" MHD_URI_BASE_PATH "\", " "cnonce=\"" CNONCE_EMU "\", " "nc=00000001, " "qop=auth, " "response=\"" RESPONSE_EMU "\", " "opaque=\"" OPAQUE_VALUE "\", " "algorithm=MD5"); if (NULL == curl_headers) externalErrorExit (); } static void test_global_cleanup (void) { curl_slist_free_all (curl_headers); curl_headers = NULL; curl_global_cleanup (); } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); if (! oldapi) { struct MHD_DigestAuthUsernameInfo *creds; struct MHD_DigestAuthInfo *dinfo; enum MHD_DigestAuthResult check_res; creds = MHD_digest_auth_get_username3 (connection); if (NULL == creds) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != creds->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED, (int) creds->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == creds->username) mhdErrorExitDesc ("'username' is NULL"); else if (creds->username_len != MHD_STATICSTR_LEN_ (USERNAME)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) creds->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (creds->username, USERNAME, creds->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) creds->username_len, creds->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != creds->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != creds->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex' is NOT zero"); else if (NULL != creds->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); dinfo = MHD_digest_auth_get_request_info3 (connection); if (NULL == dinfo) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED, (int) creds->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == dinfo->username) mhdErrorExitDesc ("'username' is NULL"); else if (dinfo->username_len != MHD_STATICSTR_LEN_ (USERNAME)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) dinfo->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (dinfo->username, USERNAME, dinfo->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) dinfo->username_len, dinfo->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != dinfo->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != dinfo->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex' is NOT zero"); else if (NULL != dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); else if (MHD_DIGEST_AUTH_ALGO3_MD5 != dinfo->algo3) { fprintf (stderr, "Unexpected 'algo'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_ALGO3_MD5, (int) dinfo->algo3); mhdErrorExitDesc ("Wrong 'algo'"); } else if (MHD_STATICSTR_LEN_ (CNONCE_EMU) != dinfo->cnonce_len) { fprintf (stderr, "Unexpected 'cnonce_len'.\n" "Expected: %d\tRecieved: %ld. ", (int) MHD_STATICSTR_LEN_ (CNONCE_EMU), (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } else if (NULL == dinfo->opaque) mhdErrorExitDesc ("'opaque' is NULL"); else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE)) { fprintf (stderr, "'opaque_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE), (unsigned) dinfo->opaque_len); mhdErrorExitDesc ("Wrong 'opaque_len'"); } else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len)) { fprintf (stderr, "'opaque' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->opaque_len, dinfo->opaque); mhdErrorExitDesc ("Wrong 'opaque'"); } else if (MHD_DIGEST_AUTH_QOP_AUTH != dinfo->qop) { fprintf (stderr, "Unexpected 'qop'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_QOP_AUTH, (int) dinfo->qop); mhdErrorExitDesc ("Wrong 'qop'"); } else if (NULL == dinfo->realm) mhdErrorExitDesc ("'realm' is NULL"); else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM)) { fprintf (stderr, "'realm_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (REALM), (unsigned) dinfo->realm_len); mhdErrorExitDesc ("Wrong 'realm_len'"); } else if (0 != memcmp (dinfo->realm, REALM, dinfo->realm_len)) { fprintf (stderr, "'realm' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->realm_len, dinfo->realm); mhdErrorExitDesc ("Wrong 'realm'"); } MHD_free (creds); MHD_free (dinfo); check_res = MHD_digest_auth_check3 (connection, REALM, USERNAME, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO3_MD5); switch (check_res) { /* Valid results */ case MHD_DAUTH_NONCE_STALE: if (verbose) printf ("Got valid auth check result: MHD_DAUTH_NONCE_STALE.\n"); break; case MHD_DAUTH_NONCE_WRONG: if (verbose) printf ("Got valid auth check result: MHD_DAUTH_NONCE_WRONG.\n"); break; /* Invalid results */ case MHD_DAUTH_OK: mhdErrorExitDesc ("'MHD_digest_auth_check3()' succeed, " \ "but it should not"); break; case MHD_DAUTH_ERROR: externalErrorExitDesc ("General error returned " \ "by 'MHD_digest_auth_check3()'"); break; case MHD_DAUTH_WRONG_USERNAME: mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \ "MHD_DAUTH_WRONG_USERNAME"); break; case MHD_DAUTH_RESPONSE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \ "MHD_DAUTH_RESPONSE_WRONG"); break; case MHD_DAUTH_WRONG_HEADER: case MHD_DAUTH_WRONG_REALM: case MHD_DAUTH_WRONG_URI: case MHD_DAUTH_WRONG_QOP: case MHD_DAUTH_WRONG_ALGO: case MHD_DAUTH_TOO_LARGE: case MHD_DAUTH_NONCE_OTHER_COND: fprintf (stderr, "'MHD_digest_auth_check3()' returned " "unexpected result: %d. ", check_res); mhdErrorExitDesc ("Wrong returned code"); break; default: fprintf (stderr, "'MHD_digest_auth_check3()' returned " "impossible result code: %d. ", check_res); mhdErrorExitDesc ("Impossible returned code"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_auth_fail_response2 (connection, REALM, OPAQUE_VALUE, response, 0, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } else { char *username; int check_res; username = MHD_digest_auth_get_username (connection); if (NULL == username) mhdErrorExitDesc ("'MHD_digest_auth_get_username()' returned NULL"); else if (0 != strcmp (username, USERNAME)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", USERNAME, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); check_res = MHD_digest_auth_check (connection, REALM, USERNAME, PASSWORD_VALUE, 300); if (MHD_INVALID_NONCE != check_res) { fprintf (stderr, "'MHD_digest_auth_check()' returned unexpected" " result: %d. ", check_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_auth_fail_response (connection, REALM, OPAQUE_VALUE, response, 0); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_headers)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc) { long code; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (401 != code) { fprintf (stderr, "Request returned wrong code: %ld.\n", code); return 0; } if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != strlen (DENIED)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) strlen (DENIED)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (DENIED, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testDigestAuthEmu (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; char buf[2048]; CURL *c; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = (uint16_t) dinfo->port; } /* First request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); if (check_result (performQueryExternal (d, c), c, &cbc)) { if (verbose) printf ("Got expected response.\n"); } else { fprintf (stderr, "Request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oldapi = has_in_name (argv[0], "_oldapi"); test_global_init (); errorCount += testDigestAuthEmu (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth2.c0000644000175000017500000015247714760713574017417 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digest2.c * @brief Testcase for MHD Digest Authorisation * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define MHD_URI_BASE_PATH2 "/another_path" /* Should not fit buffer in the stack */ #define MHD_URI_BASE_PATH3 \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/path?with%20some=parameters" #define REALM_VAL "TestRealm" #define USERNAME1 "test_user" /* The hex form of MD5("test_user:TestRealm") */ #define USERHASH1_MD5_HEX "c53c601503ff176f18f623725fba4281" #define USERHASH1_MD5_BIN 0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, \ 0x18, 0xf6, 0x23, 0x72, 0x5f, 0xba, 0x42, 0x81 /* The hex form of SHA-256("test_user:TestRealm") */ #define USERHASH1_SHA256_HEX \ "090c7e06b77d6614cf5fe6cafa004d2e5f8fb36ba45a0e35eacb2eb7728f34de" /* The binary form of SHA-256("test_user:TestRealm") */ #define USERHASH1_SHA256_BIN 0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, \ 0xcf, 0x5f, 0xe6, 0xca, 0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, \ 0xa4, 0x5a, 0x0e, 0x35, 0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde /* The hex form of MD5("test_user:TestRealm:test pass") */ #define USERDIGEST1_MD5_BIN 0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, \ 0x67, 0x94, 0xea, 0x66, 0x86, 0x03, 0x6b, 0x43 /* The binary form of SHA-256("test_user:TestRealm:test pass") */ #define USERDIGEST1_SHA256_BIN 0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, \ 0xac, 0x04, 0xf1, 0x6e, 0x46, 0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, \ 0x8f, 0x66, 0xa6, 0xd6, 0x3f, 0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, \ 0x6d #define PASSWORD_VALUE "test pass" #define OPAQUE_VALUE "opaque+content" /* Base64 character set */ #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" /* Global parameters */ static int verbose; static int test_oldapi; static int test_userhash; static int test_userdigest; static int test_sha256; static int test_rfc2069; /* Bind DAuth nonces to everything except URI */ static int test_bind_all; /* Bind DAuth nonces to URI */ static int test_bind_uri; static int curl_uses_usehash; /* Static helper variables */ static const char userhash1_md5_hex[] = USERHASH1_MD5_HEX; static const uint8_t userhash1_md5_bin[] = { USERHASH1_MD5_BIN }; static const char userhash1_sha256_hex[] = USERHASH1_SHA256_HEX; static const uint8_t userhash1_sha256_bin[] = { USERHASH1_SHA256_BIN }; static const char *userhash_hex; static size_t userhash_hex_len; static const uint8_t *userhash_bin; static const uint8_t userdigest1_md5_bin[] = { USERDIGEST1_MD5_BIN }; static const uint8_t userdigest1_sha256_bin[] = { USERDIGEST1_SHA256_BIN }; static const uint8_t *userdigest_bin; static size_t userdigest_bin_size; static const char *username_ptr; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); username_ptr = USERNAME1; if (! test_sha256) { userhash_hex = userhash1_md5_hex; userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_md5_hex); userhash_bin = userhash1_md5_bin; if ((userhash_hex_len / 2) != \ (sizeof(userhash1_md5_bin) / sizeof(userhash1_md5_bin[0]))) externalErrorExitDesc ("Wrong size of the 'userhash1_md5_bin' array"); userdigest_bin = userdigest1_md5_bin; userdigest_bin_size = (sizeof(userdigest1_md5_bin) / sizeof(userdigest1_md5_bin[0])); } else { userhash_hex = userhash1_sha256_hex; userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_sha256_hex); userhash_bin = userhash1_sha256_bin; if ((userhash_hex_len / 2) != \ (sizeof(userhash1_sha256_bin) \ / sizeof(userhash1_sha256_bin[0]))) externalErrorExitDesc ("Wrong size of the 'userhash1_sha256_bin' array"); userdigest_bin = userdigest1_sha256_bin; userdigest_bin_size = (sizeof(userdigest1_sha256_bin) / sizeof(userdigest1_sha256_bin[0])); } } static void test_global_cleanup (void) { curl_global_cleanup (); } static int gen_good_rnd (void *rnd_buf, size_t rnd_buf_size) { if (1024 < rnd_buf_size) externalErrorExitDesc ("Too large amount of random data " \ "is requested"); #ifndef _WIN32 if (1) { const int urand_fd = open ("/dev/urandom", O_RDONLY); if (0 <= urand_fd) { size_t pos = 0; do { ssize_t res = read (urand_fd, ((uint8_t *) rnd_buf) + pos, rnd_buf_size - pos); if (0 > res) break; pos += (size_t) res; } while (rnd_buf_size > pos); (void) close (urand_fd); if (rnd_buf_size == pos) return ! 0; /* Success */ } } #else /* _WIN32 */ if (1) { HCRYPTPROV cpr_hndl; if (CryptAcquireContextW (&cpr_hndl, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { if (CryptGenRandom (cpr_hndl, (DWORD) rnd_buf_size, (BYTE *) rnd_buf)) { (void) CryptReleaseContext (cpr_hndl, 0); return ! 0; /* Success */ } (void) CryptReleaseContext (cpr_hndl, 0); } } #endif /* _WIN32 */ return 0; /* Failure */ } struct CBC { char *buf; size_t pos; size_t size; }; struct req_track { /** * The number of used URI, zero-based */ unsigned int uri_num; /** * The number of request for URI. * This includes number of unauthorised requests. */ unsigned int req_num; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result res; static int already_called_marker; struct req_track *const tr_p = (struct req_track *) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); tr_p->req_num++; if (2 < tr_p->req_num) mhdErrorExitDesc ("Received more than two requests for the same URI"); response = NULL; if (! test_oldapi) { struct MHD_DigestAuthInfo *dinfo; const enum MHD_DigestAuthAlgo3 algo3 = test_sha256 ? MHD_DIGEST_AUTH_ALGO3_SHA256 : MHD_DIGEST_AUTH_ALGO3_MD5; const enum MHD_DigestAuthQOP qop = test_rfc2069 ? MHD_DIGEST_AUTH_QOP_NONE : MHD_DIGEST_AUTH_QOP_AUTH; dinfo = MHD_digest_auth_get_request_info3 (connection); if (NULL != dinfo) { /* Got any kind of Digest response. Check it, it must be valid */ struct MHD_DigestAuthUsernameInfo *uname; enum MHD_DigestAuthResult check_res; enum MHD_DigestAuthResult expect_res; if (curl_uses_usehash) { if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH, (int) dinfo->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (dinfo->userhash_hex_len != userhash_hex_len) { fprintf (stderr, "'userhash_hex_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) userhash_hex_len, (unsigned) dinfo->userhash_hex_len); mhdErrorExitDesc ("Wrong 'userhash_hex_len'"); } else if (0 != memcmp (dinfo->userhash_hex, userhash_hex, dinfo->userhash_hex_len)) { fprintf (stderr, "'userhash_hex' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", userhash_hex, (int) dinfo->userhash_hex_len, dinfo->userhash_hex); mhdErrorExitDesc ("Wrong 'userhash_hex'"); } else if (NULL == dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NULL"); else if (0 != memcmp (dinfo->userhash_bin, userhash_bin, dinfo->username_len / 2)) mhdErrorExitDesc ("Wrong 'userhash_bin'"); else if (NULL != dinfo->username) mhdErrorExitDesc ("'username' is NOT NULL"); else if (0 != dinfo->username_len) mhdErrorExitDesc ("'username_len' is NOT zero"); } else { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD, (int) dinfo->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == dinfo->username) mhdErrorExitDesc ("'username' is NULL"); else if (dinfo->username_len != strlen (username_ptr)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) strlen (username_ptr), (unsigned) dinfo->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (dinfo->username, username_ptr, dinfo->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", username_ptr, (int) dinfo->username_len, dinfo->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != dinfo->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != dinfo->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex_len' is NOT zero"); else if (NULL != dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); } if (algo3 != dinfo->algo3) { fprintf (stderr, "Unexpected 'algo3'.\n" "Expected: %d\tRecieved: %d. ", (int) algo3, (int) dinfo->algo3); mhdErrorExitDesc ("Wrong 'algo3'"); } if (! test_rfc2069) { if ( #if CURL_AT_LEAST_VERSION (7,37,1) 10 >= dinfo->cnonce_len #else /* libcurl before 7.37.1 */ 8 > dinfo->cnonce_len #endif /* libcurl before 7.37.1 */ ) { fprintf (stderr, "Unexpected small 'cnonce_len': %ld. ", (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } } else { if (0 != dinfo->cnonce_len) { fprintf (stderr, "'cnonce_len' is not zero: %ld. ", (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } } if (NULL == dinfo->opaque) mhdErrorExitDesc ("'opaque' is NULL"); else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE)) { fprintf (stderr, "'opaque_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE), (unsigned) dinfo->opaque_len); mhdErrorExitDesc ("Wrong 'opaque_len'"); } else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len)) { fprintf (stderr, "'opaque' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->opaque_len, dinfo->opaque); mhdErrorExitDesc ("Wrong 'opaque'"); } else if (qop != dinfo->qop) { fprintf (stderr, "Unexpected 'qop'.\n" "Expected: %d\tRecieved: %d. ", (int) qop, (int) dinfo->qop); mhdErrorExitDesc ("Wrong 'qop'"); } else if (NULL == dinfo->realm) mhdErrorExitDesc ("'realm' is NULL"); else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM_VAL)) { fprintf (stderr, "'realm_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (REALM_VAL), (unsigned) dinfo->realm_len); mhdErrorExitDesc ("Wrong 'realm_len'"); } else if (0 != memcmp (dinfo->realm, REALM_VAL, dinfo->realm_len)) { fprintf (stderr, "'realm' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->realm_len, dinfo->realm); mhdErrorExitDesc ("Wrong 'realm'"); } MHD_free (dinfo); uname = MHD_digest_auth_get_username3 (connection); if (NULL == uname) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); if (curl_uses_usehash) { if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != uname->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH, (int) uname->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (uname->userhash_hex_len != userhash_hex_len) { fprintf (stderr, "'userhash_hex_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) userhash_hex_len, (unsigned) uname->userhash_hex_len); mhdErrorExitDesc ("Wrong 'userhash_hex_len'"); } else if (0 != memcmp (uname->userhash_hex, userhash_hex, uname->userhash_hex_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", userhash_hex, (int) uname->userhash_hex_len, uname->userhash_hex); mhdErrorExitDesc ("Wrong 'userhash_hex'"); } else if (NULL == uname->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NULL"); else if (0 != memcmp (uname->userhash_bin, userhash_bin, uname->username_len / 2)) mhdErrorExitDesc ("Wrong 'userhash_bin'"); else if (NULL != uname->username) mhdErrorExitDesc ("'username' is NOT NULL"); else if (0 != uname->username_len) mhdErrorExitDesc ("'username_len' is NOT zero"); } else { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD, (int) uname->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == uname->username) mhdErrorExitDesc ("'username' is NULL"); else if (uname->username_len != strlen (username_ptr)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) strlen (username_ptr), (unsigned) uname->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (uname->username, username_ptr, uname->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", username_ptr, (int) uname->username_len, uname->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != uname->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != uname->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex_len' is NOT zero"); else if (NULL != uname->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); } if (algo3 != uname->algo3) { fprintf (stderr, "Unexpected 'algo3'.\n" "Expected: %d\tRecieved: %d. ", (int) algo3, (int) uname->algo3); mhdErrorExitDesc ("Wrong 'algo3'"); } MHD_free (uname); if (! test_userdigest) check_res = MHD_digest_auth_check3 (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3); else check_res = MHD_digest_auth_check_digest3 (connection, REALM_VAL, username_ptr, userdigest_bin, userdigest_bin_size, 50 * TIMEOUTS_VAL, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3); if (test_rfc2069) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_DAUTH_NONCE_STALE; else expect_res = MHD_DAUTH_OK; } else if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_DAUTH_NONCE_OTHER_COND; else expect_res = MHD_DAUTH_OK; } else expect_res = MHD_DAUTH_OK; switch (check_res) { /* Conditionally valid results */ case MHD_DAUTH_OK: if (expect_res == MHD_DAUTH_OK) { if (verbose) printf ("Got valid auth check result: MHD_DAUTH_OK.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_OK"); break; case MHD_DAUTH_NONCE_STALE: if (expect_res == MHD_DAUTH_NONCE_STALE) { if (verbose) printf ("Got expected auth check result: MHD_DAUTH_NONCE_STALE.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_STALE"); break; case MHD_DAUTH_NONCE_OTHER_COND: if (expect_res == MHD_DAUTH_NONCE_OTHER_COND) { if (verbose) printf ("Got expected auth check result: " "MHD_DAUTH_NONCE_OTHER_COND.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_OTHER_COND"); break; /* Invalid results */ case MHD_DAUTH_NONCE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_WRONG"); break; case MHD_DAUTH_ERROR: externalErrorExitDesc ("General error returned " \ "by 'MHD_digest_auth_check[_digest]3()'"); break; case MHD_DAUTH_WRONG_USERNAME: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_WRONG_USERNAME"); break; case MHD_DAUTH_RESPONSE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_RESPONSE_WRONG"); break; case MHD_DAUTH_WRONG_HEADER: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_WRONG_HEADER"); break; case MHD_DAUTH_WRONG_REALM: case MHD_DAUTH_WRONG_URI: case MHD_DAUTH_WRONG_QOP: case MHD_DAUTH_WRONG_ALGO: case MHD_DAUTH_TOO_LARGE: fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned " "unexpected result: %d. ", check_res); mhdErrorExitDesc ("Wrong returned code"); break; default: fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned " "impossible result code: %d. ", check_res); mhdErrorExitDesc ("Impossible returned code"); } fflush (stderr); fflush (stdout); if (MHD_DAUTH_OK == check_res) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if ((MHD_DAUTH_NONCE_STALE == check_res) || (MHD_DAUTH_NONCE_OTHER_COND == check_res)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_required_response3 (connection, REALM_VAL, OPAQUE_VALUE, "/", response, 1, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3, test_userhash, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* No Digest auth header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_required_response3 ( connection, REALM_VAL, OPAQUE_VALUE, "/", response, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3, test_userhash, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed"); } } else if (2 == test_oldapi) { /* Use old API v2 */ char *username; int check_res; int expect_res; username = MHD_digest_auth_get_username (connection); if (NULL != username) { /* Has a valid username in header */ if (0 != strcmp (username, username_ptr)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", username_ptr, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); if (! test_userdigest) check_res = MHD_digest_auth_check2 (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); else check_res = MHD_digest_auth_check_digest2 (connection, REALM_VAL, username_ptr, userdigest_bin, userdigest_bin_size, 50 * TIMEOUTS_VAL, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_INVALID_NONCE; else expect_res = MHD_YES; } else expect_res = MHD_YES; if (expect_res != check_res) { fprintf (stderr, "'MHD_digest_auth_check[_digest]2()' returned " "unexpected result '%d', while expected is '%d. ", check_res, expect_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]2()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES == expect_res) { if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if (MHD_INVALID_NONCE == expect_res) { if (MHD_YES != MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE, response, 1, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5)) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* Has no valid username in header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE, response, 0, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } } else if (1 == test_oldapi) { /* Use old API v1 */ char *username; int check_res; int expect_res; username = MHD_digest_auth_get_username (connection); if (NULL != username) { /* Has a valid username in header */ if (0 != strcmp (username, username_ptr)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", username_ptr, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); if (! test_userdigest) check_res = MHD_digest_auth_check (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL); else check_res = MHD_digest_auth_check_digest (connection, REALM_VAL, username_ptr, userdigest_bin, 50 * TIMEOUTS_VAL); if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_INVALID_NONCE; else expect_res = MHD_YES; } else expect_res = MHD_YES; if (expect_res != check_res) { fprintf (stderr, "'MHD_digest_auth_check[_digest]()' returned " "unexpected result '%d', while expected is '%d. ", check_res, expect_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES == expect_res) { if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if (MHD_INVALID_NONCE == expect_res) { if (MHD_YES != MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE, response, 1)) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* Has no valid username in header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE, response, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } } else externalErrorExitDesc ("Wrong 'test_oldapi' value"); MHD_destroy_response (response); return MHD_YES; } /** * * @param c the CURL handle to use * @param port the port to set * @param uri_num the number of URI, should be 0, 1 or 2 */ static void setCURL_rq_path (CURL *c, uint16_t port, unsigned int uri_num) { const char *req_path; char uri[512]; int res; if (0 == uri_num) req_path = MHD_URI_BASE_PATH; else if (1 == uri_num) req_path = MHD_URI_BASE_PATH2; else req_path = MHD_URI_BASE_PATH3; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (uri, (sizeof(uri) / sizeof(uri[0])), "http://127.0.0.1:%u%s", (unsigned int) port, req_path); if ((0 >= res) || ((sizeof(uri) / sizeof(uri[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, uri)) libcurlErrorExitDesc ("Cannot set request URL"); } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, (long) CURLAUTH_DIGEST)) || #if CURL_AT_LEAST_VERSION (7,19,1) /* Need version 7.19.1 for separate username and password */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERNAME, username_ptr)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PASSWORD, PASSWORD_VALUE)) || #endif /* CURL_AT_LEAST_VERSION(7,19,1) */ #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); setCURL_rq_path (c, port, 0); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc) { long code; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (MHD_HTTP_OK != code) { fprintf (stderr, "Request returned wrong code: %ld.\n", code); return 0; } if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testDigestAuth (void) { unsigned int dauth_nonce_bind; struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct req_track rq_tr; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; if (1) { uint8_t salt[8]; /* Use local variable to test MHD "copy" function */ if (! gen_good_rnd (salt, sizeof(salt))) { fprintf (stderr, "WARNING: the random buffer (used as salt value) is not " "initialised completely, nonce generation may be " "predictable in this test.\n"); fflush (stderr); } dauth_nonce_bind = MHD_DAUTH_BIND_NONCE_NONE; if (test_bind_all) dauth_nonce_bind |= (MHD_DAUTH_BIND_NONCE_CLIENT_IP | MHD_DAUTH_BIND_NONCE_REALM); if (test_bind_uri) dauth_nonce_bind |= MHD_DAUTH_BIND_NONCE_URI_PARAMS; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &rq_tr, MHD_OPTION_DIGEST_AUTH_RANDOM_COPY, sizeof (salt), salt, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE, dauth_nonce_bind, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ rq_tr.req_num = 0; rq_tr.uri_num = 0; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); failed = 1; } cbc.pos = 0; /* Reset buffer position */ rq_tr.req_num = 0; /* Second request */ setCURL_rq_path (c, port, ++rq_tr.uri_num); if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); failed = 1; } cbc.pos = 0; /* Reset buffer position */ rq_tr.req_num = 0; /* Third request */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ setCURL_rq_path (c, port, ++rq_tr.uri_num); if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { #if ! CURL_AT_LEAST_VERSION (7,19,1) (void) argc; (void) argv; /* Unused. Silent compiler warning. */ /* Need version 7.19.1 or newer for separate username and password */ fprintf (stderr, "Required libcurl at least version 7.19.1" " to run this test.\n"); return 77; #else /* CURL_AT_LEAST_VERSION(7,19,1) */ unsigned int errorCount = 0; const curl_version_info_data *const curl_info = curl_version_info (CURLVERSION_NOW); int curl_sspi; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_oldapi = 0; if (has_in_name (argv[0], "_oldapi1")) test_oldapi = 1; if (has_in_name (argv[0], "_oldapi2")) test_oldapi = 2; test_userhash = has_in_name (argv[0], "_userhash"); test_userdigest = has_in_name (argv[0], "_userdigest"); test_sha256 = has_in_name (argv[0], "_sha256"); test_rfc2069 = has_in_name (argv[0], "_rfc2069"); test_bind_all = has_in_name (argv[0], "_bind_all"); test_bind_uri = has_in_name (argv[0], "_bind_uri"); /* Wrong test types combinations */ if (1 == test_oldapi) { if (test_sha256) return 99; } if (test_oldapi) { if (test_userhash || test_rfc2069) return 99; } if (test_rfc2069) { if (test_userhash) return 99; } /* Curl version and known bugs checks */ curl_sspi = 0; #ifdef CURL_VERSION_SSPI if (0 != (curl_info->features & CURL_VERSION_SSPI)) curl_sspi = 1; #endif /* CURL_VERSION_SSPI */ if ((CURL_VERSION_BITS (7,63,0) > curl_info->version_num) && (CURL_VERSION_BITS (7,62,0) <= curl_info->version_num) ) { fprintf (stderr, "libcurl version 7.62.x has bug in processing " "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test with libcurl %u.%u.%u cannot be performed.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } if (test_sha256) { if (curl_sspi) { fprintf (stderr, "Windows SSPI API does not support SHA-256 digests.\n"); return 77; } else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num) { fprintf (stderr, "Required libcurl at least version 7.57.0 " "to run this test with SHA-256.\n"); fprintf (stderr, "This libcurl version %u.%u.%u " "does not support SHA-256.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } } if (test_userhash) { if (curl_sspi) { printf ("WARNING: Windows SSPI API does not support 'userhash'.\n"); printf ("This test just checks Digest Auth compatibility with " "the clients without 'userhash' support " "when 'userhash=true' is specified by MHD.\n"); curl_uses_usehash = 0; } else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num) { printf ("WARNING: libcurl before version 7.57.0 does not " "support 'userhash'.\n"); printf ("This test just checks Digest Auth compatibility with " "libcurl version %u.%u.%u without 'userhash' support " "when 'userhash=true' is specified by MHD.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); curl_uses_usehash = 0; } else if (CURL_VERSION_BITS (7,81,0) > curl_info->version_num) { fprintf (stderr, "Required libcurl at least version 7.81.0 " "to run this test with userhash.\n"); fprintf (stderr, "This libcurl version %u.%u.%u has broken digest " "calculation when userhash is used.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } else curl_uses_usehash = ! 0; } else curl_uses_usehash = 0; test_global_init (); errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ #endif /* CURL_AT_LEAST_VERSION(7,19,1) */ } libmicrohttpd-1.0.2/src/testcurl/test_get_close_keep_alive.c0000644000175000017500000010547414760713574021317 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_close_keep_alive.c * @brief Testcase for libmicrohttpd "Close" and "Keep-Alive" connection. * @details Testcases for testing of MHD automatic choice between "Close" and * "Keep-Alive" connections. Also tested selected HTTP version and * "Connection:" headers. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/hello_world" #define EXPECTED_URI_QUERY "a=%26&b=c" #define EXPECTED_URI_FULL_PATH EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY #define HDR_CONN_CLOSE_VALUE "close" #define HDR_CONN_CLOSE MHD_HTTP_HEADER_CONNECTION ": " \ HDR_CONN_CLOSE_VALUE #define HDR_CONN_KEEP_ALIVE_VALUE "Keep-Alive" #define HDR_CONN_KEEP_ALIVE MHD_HTTP_HEADER_CONNECTION ": " \ HDR_CONN_KEEP_ALIVE_VALUE /* Global parameters */ static int oneone; /**< Use HTTP/1.1 instead of HTTP/1.0 for requests*/ static int conn_close; /**< Don't use Keep-Alive */ static uint16_t global_port; /**< MHD daemons listen port number */ static int slow_reply = 0; /**< Slowdown MHD replies */ static int ignore_response_errors = 0; /**< Do not fail test if CURL returns error */ static int response_timeout_val = TIMEOUTS_VAL; /* Current test parameters */ /* Poor thread sync, but enough for the testing */ static volatile int mhd_add_close; /**< Add "Connection: close" header by MHD */ static volatile int mhd_set_10_cmptbl; /**< Set MHD_RF_HTTP_1_0_COMPATIBLE_STRICT response flag */ static volatile int mhd_set_10_server; /**< Set MHD_RF_HTTP_1_0_SERVER response flag */ static volatile int mhd_set_k_a_send; /**< Set MHD_RF_SEND_KEEP_ALIVE_HEADER response flag */ /* Static helper variables */ static struct curl_slist *curl_close_hdr; /**< CURL "Connection: close" header */ static struct curl_slist *curl_k_alive_hdr; /**< CURL "Connection: keep-alive" header */ static struct curl_slist *curl_both_hdrs; /**< CURL both "Connection: keep-alive" and "close" headers */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); curl_close_hdr = NULL; curl_close_hdr = curl_slist_append (curl_close_hdr, HDR_CONN_CLOSE); if (NULL == curl_close_hdr) externalErrorExit (); curl_k_alive_hdr = NULL; curl_k_alive_hdr = curl_slist_append (curl_k_alive_hdr, HDR_CONN_KEEP_ALIVE); if (NULL == curl_k_alive_hdr) externalErrorExit (); curl_both_hdrs = NULL; curl_both_hdrs = curl_slist_append (curl_both_hdrs, HDR_CONN_KEEP_ALIVE); if (NULL == curl_both_hdrs) externalErrorExit (); curl_both_hdrs = curl_slist_append (curl_both_hdrs, HDR_CONN_CLOSE); if (NULL == curl_both_hdrs) externalErrorExit (); } static void test_global_cleanup (void) { curl_slist_free_all (curl_both_hdrs); curl_slist_free_all (curl_k_alive_hdr); curl_slist_free_all (curl_close_hdr); curl_global_cleanup (); } struct headers_check_result { int found_http11; int found_http10; int found_conn_close; int found_conn_keep_alive; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((strlen (MHD_HTTP_VERSION_1_1) < data_size) && (0 == memcmp (MHD_HTTP_VERSION_1_1, buffer, strlen (MHD_HTTP_VERSION_1_1)))) check_res->found_http11 = 1; else if ((strlen (MHD_HTTP_VERSION_1_0) < data_size) && (0 == memcmp (MHD_HTTP_VERSION_1_0, buffer, strlen (MHD_HTTP_VERSION_1_0)))) check_res->found_http10 = 1; else if ((data_size == strlen (HDR_CONN_CLOSE) + 2) && (0 == memcmp (buffer, HDR_CONN_CLOSE "\r\n", data_size))) check_res->found_conn_close = 1; else if ((data_size == strlen (HDR_CONN_KEEP_ALIVE) + 2) && (0 == memcmp (buffer, HDR_CONN_KEEP_ALIVE "\r\n", data_size))) check_res->found_conn_keep_alive = 1; return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_FULL_PATH)) { fprintf (stderr, "Wrong URI: `%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (slow_reply) usleep (200000); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) { fprintf (stderr, "Failed to create response. Line: %d\n", __LINE__); exit (19); } if (mhd_add_close) { if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, HDR_CONN_CLOSE_VALUE)) { fprintf (stderr, "Failed to add header. Line: %d\n", __LINE__); exit (19); } } if (MHD_YES != MHD_set_response_options (response, (mhd_set_10_cmptbl ? MHD_RF_HTTP_1_0_COMPATIBLE_STRICT : 0) | (mhd_set_10_server ? MHD_RF_HTTP_1_0_SERVER : 0) | (mhd_set_k_a_send ? MHD_RF_SEND_KEEP_ALIVE_HEADER : 0), MHD_RO_END)) { fprintf (stderr, "Failed to set response flags. Line: %d\n", __LINE__); exit (19); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) { fprintf (stderr, "Failed to queue response. Line: %d\n", __LINE__); exit (19); } return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Destination port for CURL query */ uint16_t queryPort; /* CURL query result error flag */ volatile unsigned int queryError; }; static CURL * curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc, struct headers_check_result *hdr_chk_result, int add_hdr_close, int add_hdr_k_alive) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (add_hdr_close && add_hdr_k_alive) { /* This combination is actually incorrect */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_both_hdrs)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } else if (add_hdr_close) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_close_hdr)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } else if (add_hdr_k_alive) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_k_alive_hdr)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } return c; } static void print_test_params (int add_hdr_close, int add_hdr_k_alive) { fprintf (stderr, "Request HTTP/%s| ", oneone ? "1.1" : "1.0"); fprintf (stderr, "Connection must be: %s| ", conn_close ? "close" : "keep-alive"); fprintf (stderr, "Request \"close\": %s| ", add_hdr_close ? " used" : "NOT used"); fprintf (stderr, "Request \"keep-alive\": %s| ", add_hdr_k_alive ? " used" : "NOT used"); fprintf (stderr, "MHD response \"close\": %s| ", mhd_add_close ? " used" : "NOT used"); fprintf (stderr, "MHD response 1.0 strict compatible: %s| ", mhd_set_10_cmptbl ? "yes" : " NO"); fprintf (stderr, "MHD response 1.0 server: %s| ", mhd_set_10_server ? "yes" : " NO"); fprintf (stderr, "MHD response send \"Keep-Alive\": %s|", mhd_set_k_a_send ? "yes" : " NO"); fprintf (stderr, "\n*** "); } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed.\n"); externalErrorExit (); } if (CURLM_OK != curl_multi_add_handle (multi, c)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); externalErrorExit (); } start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) { fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n"); externalErrorExit (); } totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) { fprintf (stderr, "curl_multi_fdset() failed.\n"); externalErrorExit (); } } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) { fprintf (stderr, "MHD_get_fdset() failed. Line: %d\n", __LINE__); exit (11); break; } tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) { fprintf (stderr, "MHD_run_from_select() failed. Line: %d\n", __LINE__); exit (11); } } return ret; } static unsigned int getMhdActiveConnections (struct MHD_Daemon *d) { const union MHD_DaemonInfo *dinfo; /* The next method is unreliable unless it's known that no * connections are started or finished in parallel */ dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL == dinfo) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } return dinfo->num_connections; } static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, int add_hdr_close, int add_hdr_k_alive) { const union MHD_DaemonInfo *dinfo; CURL *c; char buf[2048]; struct CBC cbc; struct headers_check_result hdr_res; CURLcode errornum; int use_external_poll; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; hdr_res.found_http11 = 0; hdr_res.found_http10 = 0; hdr_res.found_conn_close = 0; hdr_res.found_conn_keep_alive = 0; c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc, &hdr_res, add_hdr_close, add_hdr_k_alive); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (ignore_response_errors) { p->queryError = 0; curl_easy_cleanup (c); return p->queryError; } if (CURLE_OK != errornum) { p->queryError = 1; fprintf (stderr, "libcurl query failed: `%s'\n", curl_easy_strerror (errornum)); libcurlErrorExit (); } else { if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "curl reports wrong size of MHD reply body data.\n"); p->queryError = 1; } else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf, strlen (EXPECTED_URI_BASE_PATH))) { fprintf (stderr, "curl reports wrong MHD reply body data.\n"); p->queryError = 1; } else p->queryError = 0; } if (! hdr_res.found_http11 && ! hdr_res.found_http10) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "No know HTTP versions were found in the " "reply header. Line: %d\n", __LINE__); exit (24); } else if (hdr_res.found_http11 && hdr_res.found_http10) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Both HTTP/1.1 and HTTP/1.0 were found in the " "reply header. Line: %d\n", __LINE__); exit (24); } if (conn_close) { if (! hdr_res.found_conn_close) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: close\" was not found in" " MHD reply headers.\n"); p->queryError |= 2; } if (hdr_res.found_conn_keep_alive) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } if (use_external_poll) { /* The number of MHD connection can queried only with external poll. * otherwise it creates a race condition. */ if (0 != getMhdActiveConnections (d)) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD still has active connection " "after response has been sent.\n"); p->queryError |= 2; } } } else { /* Keep-Alive */ if (! oneone || mhd_set_10_server || mhd_set_k_a_send) { /* Should have "Connection: Keep-Alive" */ if (! hdr_res.found_conn_keep_alive) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was not found in" " MHD reply headers.\n"); p->queryError |= 2; } } else { /* Should NOT have "Connection: Keep-Alive" */ if (hdr_res.found_conn_keep_alive) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } } if (hdr_res.found_conn_close) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: close\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } if (use_external_poll) { /* The number of MHD connection can be queried only with external poll. * otherwise it creates a race condition. */ unsigned int num_conn = getMhdActiveConnections (d); if (0 == num_conn) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD has no active connection " "after response has been sent.\n"); p->queryError |= 2; } else if (1 != num_conn) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD has wrong number of active connection (%u) " "after response has been sent. Line: %d\n", num_conn, __LINE__); exit (23); } } } #if defined(CURL_AT_LEAST_VERSION) && CURL_AT_LEAST_VERSION (7, 45, 0) if (! use_external_poll) { /* libcurl closes connection socket with curl_multi_remove_handle () / curl_multi_cleanup() */ curl_socket_t curl_sckt; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_ACTIVESOCKET, &curl_sckt)) { fprintf (stderr, "Failed to get libcurl active socket.\n"); libcurlErrorExit (); } if (conn_close && (CURL_SOCKET_BAD != curl_sckt)) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "libcurl still has active connection " "after performing the test query.\n"); p->queryError |= 2; } else if (! conn_close && (CURL_SOCKET_BAD == curl_sckt)) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "libcurl has no active connection " "after performing the test query.\n"); p->queryError |= 2; } } #endif if (! mhd_set_10_server) { /* Response must be HTTP/1.1 */ if (hdr_res.found_http10) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Reply has HTTP/1.0 version, while it " "must be HTTP/1.1.\n"); p->queryError |= 4; } } else { /* Response must be HTTP/1.0 */ if (hdr_res.found_http11) { print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Reply has HTTP/1.1 version, while it " "must be HTTP/1.0.\n"); p->queryError |= 4; } } curl_easy_cleanup (c); return p->queryError; } /* Perform test queries and shut down MHD daemon */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ int i = 0; /* masks */ const int m_mhd_close = 1 << (i++); const int m_10_cmptbl = 1 << (i++); const int m_10_server = 1 << (i++); const int m_k_a_send = 1 << (i++); const int m_client_close = 1 << (i++); const int m_client_k_alive = 1 << (i++); qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; qParam.queryPort = d_port; /* Connect to the daemon */ for (i = (1 << i) - 1; 0 <= i; i--) { const int f_mhd_close = (0 == (i & m_mhd_close)); /**< Use MHD "close" header */ const int f_10_cmptbl = (0 == (i & m_10_cmptbl)); /**< Use MHD MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag */ const int f_10_server = (0 == (i & m_10_server)); /**< Use MHD MHD_RF_HTTP_1_0_SERVER flag */ const int f_k_a_send = (0 == (i & m_k_a_send)); /**< Use MHD MHD_RF_SEND_KEEP_ALIVE_HEADER flag */ const int f_client_close = (0 == (i & m_client_close)); /**< Use libcurl "close" header */ const int f_client_k_alive = (0 == (i & m_client_k_alive)); /**< Use libcurl "Keep-Alive" header */ int res_close; /**< Indicate the result of the test query should be closed connection */ if (f_mhd_close) /* Connection with server's "close" header must be always closed */ res_close = 1; else if (f_client_close) /* Connection with client's "close" header must be always closed */ res_close = 1; else if (f_10_cmptbl) /* Connection in strict HTTP/1.0 compatible mode must be always closed */ res_close = 1; else if (! oneone || f_10_server) /* With HTTP/1.0 client or server connection must be close unless client use "keep-alive" header */ res_close = ! f_client_k_alive; else res_close = 0; /* HTTP/1.1 is "keep-alive" by default */ if ((! ! res_close) != (! ! conn_close)) continue; /* Another mode is in test currently */ mhd_add_close = f_mhd_close; mhd_set_10_cmptbl = f_10_cmptbl; mhd_set_10_server = f_10_server; mhd_set_k_a_send = f_k_a_send; ret <<= 3; /* Remember errors for each step */ ret |= doCurlQueryInThread (d, &qParam, f_client_close, f_client_k_alive); } MHD_stop_daemon (d); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4050; if (oneone) *pport += 1; if (! conn_close) *pport += 2; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port); return performTestQueries (d, d_port); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); return performTestQueries (d, d_port); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port); return performTestQueries (d, d_port); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port); return performTestQueries (d, d_port); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); conn_close = has_in_name (argv[0], "_close"); if (! conn_close && ! has_in_name (argv[0], "_keep_alive")) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/perf_get_concurrent.c0000644000175000017500000003533114760713574020157 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file perf_get_concurrent.c * @brief benchmark concurrent GET operations * Note that we run libcurl on the machine at the * same time, so the execution time may be influenced * by the concurrent activity; it is quite possible * that more time is spend with libcurl than with MHD, * so the performance scores calculated with this code * should NOT be used to compare with other HTTP servers * (since MHD is actually better); only the relative * scores between MHD versions are meaningful. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test (total number of requests will be ROUNDS * PAR). * Ensure that free ports are not exhausted during test. */ #if MHD_CPU_COUNT > 8 #ifndef _WIN32 #define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT) #else /* _WIN32 */ #define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT) #endif /* _WIN32 */ #else #define ROUNDS 500 #endif /** * How many requests do we do in parallel? */ #define PAR MHD_CPU_COUNT /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Time this round was started. */ static unsigned long long start_time; /** * Set to 1 if the worker threads are done. */ static volatile int signal_done; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } /** * Start the timer. */ static void start_timer (void) { start_time = now (); } /** * Stop the timer and report performance * * @param desc description of the threading mode we used */ static void stop (const char *desc) { double rps = ((double) (PAR * ROUNDS * 1000)) / ((double) (now () - start_time)); fprintf (stderr, "Parallel GETs using %s: %f %s\n", desc, rps, "requests/s"); } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; unsigned int i; char *const url = (char *) param; static char curl_err_marker[] = "curl error"; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); for (i = 0; i < ROUNDS; i++) { if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); return curl_err_marker; } } curl_easy_cleanup (c); return NULL; } static void * do_gets (void *param) { int j; pthread_t par[PAR]; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; char *err = NULL; static char pthr_err_marker[] = "pthread_create error"; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); for (j = 0; j < PAR; j++) { if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url)) { for (j--; j >= 0; j--) pthread_join (par[j], NULL); return pthr_err_marker; } } for (j = 0; j < PAR; j++) { char *ret_val; if ((0 != pthread_join (par[j], (void **) &ret_val)) || (NULL != ret_val) ) err = ret_val; } signal_done = 1; return err; } static unsigned int testInternalGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto'" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll()" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll" : "internal thread with select()"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto' and thread per connection" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll() and thread per connection" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll and thread per connection" : "internal thread with select() and thread per connection"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread pool with 'auto'" : (poll_flag & MHD_USE_POLL) ? "internal thread pool with poll()" : (poll_flag & MHD_USE_EPOLL) ? "internal thread poll with epoll" : "internal thread pool with select()"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testExternalGet (uint16_t port) { struct MHD_Daemon *d; pthread_t tid; fd_set rs; fd_set ws; fd_set es; MHD_socket max; struct timeval tv; uint64_t tt64; char *ret_val; int ret = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } if (0 != pthread_create (&tid, NULL, &do_gets, (void *) (intptr_t) port)) { MHD_stop_daemon (d); return 512; } start_timer (); while (0 == signal_done) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } if (MHD_NO == MHD_get_timeout64 (d, &tt64)) tt64 = 1; #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (tt64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (tt64 / 1000); #endif /* Native W32 */ tv.tv_usec = ((long) (tt64 % 1000)) * 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } ret |= 1024; break; #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run_from_select (d, &rs, &ws, &es); } stop ("external select"); MHD_stop_daemon (d); if ((0 != pthread_join (tid, (void **) &ret_val)) || (NULL != ret_val) ) { fprintf (stderr, "%s\n", ret_val); ret |= 8; } if (ret) fprintf (stderr, "Error performing test.\n"); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port = 1100; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 15; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testInternalGet (port++, 0); errorCount += testMultithreadedGet (port++, 0); errorCount += testMultithreadedPoolGet (port++, 0); errorCount += testExternalGet (port++); errorCount += testInternalGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (port++, MHD_USE_POLL); errorCount += testMultithreadedGet (port++, MHD_USE_POLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (port++, MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL); } MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_basicauth.c0000644000175000017500000005642114760713574017127 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_basicauth.c * @brief Testcase for libmicrohttpd Basic Authorisation * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo%3Fkey%3Dvalue" #define REALM "TestRealm" #define USERNAME "Aladdin" #define PASSWORD "open sesame" #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" struct CBC { char *buf; size_t pos; size_t size; }; static int verbose; static int preauth; static int oldapi; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); /* require: USERNAME with password PASSWORD */ if (! oldapi) { struct MHD_BasicAuthInfo *creds; creds = MHD_basic_auth_get_username_password3 (connection); if (NULL != creds) { if (NULL == creds->username) mhdErrorExitDesc ("'username' is NULL"); else if (MHD_STATICSTR_LEN_ (USERNAME) != creds->username_len) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) creds->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (creds->username, USERNAME, creds->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) creds->username_len, creds->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (0 != creds->username[creds->username_len]) mhdErrorExitDesc ("'username' is not zero-terminated"); else if (NULL == creds->password) mhdErrorExitDesc ("'password' is NULL"); else if (MHD_STATICSTR_LEN_ (PASSWORD) != creds->password_len) { fprintf (stderr, "'password_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (PASSWORD), (unsigned) creds->password_len); mhdErrorExitDesc ("Wrong 'password_len'"); } else if (0 != memcmp (creds->password, PASSWORD, creds->password_len)) { fprintf (stderr, "'password' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", PASSWORD, (int) creds->password_len, creds->password); mhdErrorExitDesc ("Wrong 'username'"); } else if (0 != creds->password[creds->password_len]) mhdErrorExitDesc ("'password' is not zero-terminated"); MHD_free (creds); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_basic_auth_required_response3 (connection, REALM, MHD_YES, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_basic_auth_required_response3()' failed"); } } else { char *username; char *password; password = NULL; username = MHD_basic_auth_get_username_password (connection, &password); if (NULL != username) { if (0 != strcmp (username, USERNAME)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", USERNAME, username); mhdErrorExitDesc ("Wrong 'username'"); } if (NULL == password) mhdErrorExitDesc ("The password pointer is NULL"); if (0 != strcmp (password, PASSWORD)) fprintf (stderr, "'password' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", PASSWORD, password); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else { if (NULL != password) mhdErrorExitDesc ("The password pointer is NOT NULL"); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_basic_auth_fail_response (connection, REALM, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_basic_auth_fail_response()' failed"); } if (NULL != username) MHD_free (username); if (NULL != password) MHD_free (password); } MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port, char *errbuf) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); #if CURL_AT_LEAST_VERSION (7,21,3) if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC | (preauth ? 0 : CURLAUTH_ONLY))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, USERNAME ":" PASSWORD))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); #else /* libcurl version before 7.21.3 */ if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, USERNAME ":" PASSWORD))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); #endif /* libcurl version before 7.21.3 */ return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, struct CBC *pcbc) { if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "First request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "First request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != strlen (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) strlen (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testBasicAuth (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; char buf[2048]; CURL *c; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = (uint16_t) dinfo->port; } /* First request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, libcurl_errbuf); if (check_result (performQueryExternal (d, c), &cbc)) { if (verbose) printf ("First request successful.\n"); } else { fprintf (stderr, "First request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); /* Second request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, libcurl_errbuf); if (check_result (performQueryExternal (d, c), &cbc)) { if (verbose) printf ("Second request successful.\n"); } else { fprintf (stderr, "Second request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); preauth = has_in_name (argv[0], "_preauth"); #if ! CURL_AT_LEAST_VERSION (7,21,3) if (preauth) { fprintf (stderr, "libcurl version 7.21.3 or later is " "required to run this test.\n"); return 77; } #endif /* libcurl version before 7.21.3 */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ oldapi = has_in_name (argv[0], "_oldapi"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testBasicAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_callback.c0000644000175000017500000001662714760713574016724 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_callback.c * @brief Testcase for MHD not calling the callback too often * @author Jan Seeger * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include struct callback_closure { unsigned int called; }; static ssize_t called_twice (void *cls, uint64_t pos, char *buf, size_t max) { struct callback_closure *cls2 = cls; (void) pos; /* Unused. Silence compiler warning. */ (void) max; if (cls2->called == 0) { memcpy (buf, "test", 5); cls2->called = 1; return (ssize_t) strlen (buf); } if (cls2->called == 1) { cls2->called = 2; return MHD_CONTENT_READER_END_OF_STREAM; } fprintf (stderr, "Handler called after returning END_OF_STREAM!\n"); abort (); return MHD_CONTENT_READER_END_WITH_ERROR; } static enum MHD_Result callback (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct callback_closure *cbc = calloc (1, sizeof(struct callback_closure)); struct MHD_Response *r; enum MHD_Result ret; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (NULL == cbc) return MHD_NO; r = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &called_twice, cbc, &free); if (NULL == r) { free (cbc); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static size_t discard_buffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } int main (int argc, char **argv) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ CURL *c; CURLM *multi; CURLMcode mret; struct CURLMsg *msg; int running; struct timeval tv; int extra; uint16_t port; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1140; d = MHD_start_daemon (MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 32; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 48; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &discard_buffer); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } extra = 10; while ( (c != NULL) || (--extra > 0) ) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&ws); FD_ZERO (&rs); FD_ZERO (&es); curl_multi_perform (multi, &running); if (NULL != multi) { mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/testcurl/test_get_iovec.c0000644000175000017500000005061414760713574017126 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2021 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_iovec.c * @brief Testcase for libmicrohttpd response from scatter/gather array * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * @author Lawrence Sebald */ /* * This test is largely derived from the test_get_sendfile.c file, with the * daemon using MHD_create_response_from_iovec instead of working from an fd. */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include #ifdef HAVE_STDBOOL_H #include #endif #include #include "mhd_sockets.h" #include "mhd_has_in_name.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define TESTSTR_IOVLEN 20480 #define TESTSTR_IOVCNT 20 #define TESTSTR_SIZE (TESTSTR_IOVCNT * TESTSTR_IOVLEN) static int oneone; static int readbuf[TESTSTR_SIZE * 2 / sizeof(int)]; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) _exit (7); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void iov_free_callback (void *cls) { free (cls); } struct iovncont_data { void *ptrs[TESTSTR_IOVCNT]; }; static void iovncont_free_callback (void *cls) { struct iovncont_data *data = (struct iovncont_data *) cls; unsigned int i; for (i = 0; i < TESTSTR_IOVCNT; ++i) free (data->ptrs[i]); free (data); } static int check_read_data (const void *ptr, size_t len) { const int *buf; size_t i; if (len % sizeof(int)) return -1; buf = (const int *) ptr; for (i = 0; i < len / sizeof(int); ++i) { if (buf[i] != (int) i) return -1; } return 0; } static enum MHD_Result ahc_cont (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; int *data; struct MHD_IoVec iov[TESTSTR_IOVCNT]; int i; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; /* Create some test data. */ if (NULL == (data = malloc (TESTSTR_SIZE))) return MHD_NO; for (i = 0; i < (int) (TESTSTR_SIZE / sizeof(int)); ++i) { data[i] = i; } for (i = 0; i < TESTSTR_IOVCNT; ++i) { iov[i].iov_base = data + (((size_t) i) * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int))); iov[i].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT; } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iov_free_callback, data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static enum MHD_Result ahc_ncont (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_IoVec iov[TESTSTR_IOVCNT]; struct iovncont_data *clear_cls; int i, j; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; clear_cls = malloc (sizeof(struct iovncont_data)); if (NULL == clear_cls) abort (); memset (iov, 0, sizeof(struct MHD_IoVec) * TESTSTR_IOVCNT); /* Create some test data. */ for (j = TESTSTR_IOVCNT - 1; j >= 0; --j) { int *data; data = malloc (TESTSTR_IOVLEN); if (NULL == data) abort (); clear_cls->ptrs[j] = (void *) data; for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i) { data[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int))); } iov[j].iov_base = (const void *) data; iov[j].iov_len = TESTSTR_IOVLEN; } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iovncont_free_callback, clear_cls); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (bool contiguous) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1200; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; if (contiguous) { d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END); } else { d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_ncont, NULL, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 4; if (0 != check_read_data (cbc.buf, cbc.pos)) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1201; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_AUTO, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 64; if (0 != check_read_data (cbc.buf, cbc.pos)) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1202; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_AUTO, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 64; if (0 != check_read_data (cbc.buf, cbc.pos)) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1203; if (oneone) port += 10; } multi = NULL; cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 8192; if (0 != check_read_data (cbc.buf, cbc.pos)) return 16384; return 0; } static unsigned int testUnknownPortGet (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; char buf[2048]; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_END); if (d == NULL) return 32768; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 1048576; if (0 != check_read_data (cbc.buf, cbc.pos)) return 2097152; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (true); errorCount += testInternalGet (false); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); errorCount += testUnknownPortGet (); errorCount += testExternalGet (0); } errorCount += testExternalGet (! 0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_long_header.c0000644000175000017500000003462614760713574017436 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_long_header.c * @brief Testcase for libmicrohttpd handling of very long headers * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #ifndef WINDOWS #include #endif #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ /** * We will set the memory available per connection to * half of this value, so the actual value does not have * to be big at all... */ #define VERY_LONG (1024 * 8) /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST_PATH URL_SCHEME URL_HOST EXPECTED_URI_BASE_PATH static int oneone; static uint16_t daemon_port; static char libcurl_err_buf[CURL_ERROR_SIZE]; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } /* Return non-zero on success, zero on failure */ static int setup_easy_handler_params (CURL *c, struct CBC *pcbc, const char *url, struct curl_slist *header) { libcurl_err_buf[0] = 0; /* Reset error message */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_err_buf)) { fprintf (stderr, "Failed to set CURLOPT_ERRORBUFFER option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) { fprintf (stderr, "Failed to set CURLOPT_NOSIGNAL option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) { fprintf (stderr, "Failed to set CURLOPT_WRITEFUNCTION option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) { fprintf (stderr, "Failed to set CURLOPT_WRITEDATA option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) { fprintf (stderr, "Failed to set CURLOPT_CONNECTTIMEOUT option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) { fprintf (stderr, "Failed to set CURLOPT_TIMEOUT option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) { fprintf (stderr, "Failed to set CURLOPT_HTTP_VERSION option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) { fprintf (stderr, "Failed to set CURLOPT_FAILONERROR option.\n"); return 0; } #ifdef _DEBUG if (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) { fprintf (stderr, "Failed to set CURLOPT_VERBOSE option.\n"); return 0; } #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 45, 0) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) { fprintf (stderr, "Failed to set CURLOPT_DEFAULT_PROTOCOL option.\n"); return 0; } #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS_STR option.\n"); return 0; } #elif CURL_AT_LEAST_VERSION (7, 19, 4) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, (NULL != url) ? url : URL_SCHEME_HOST_PATH)) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) daemon_port))) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } if (NULL != header) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, header)) { fprintf (stderr, "Failed to set CURLOPT_HTTPHEADER option.\n"); return 0; } } return ! 0; } static CURL * setup_easy_handler (struct CBC *pcbc, const char *url, struct curl_slist *header) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() error.\n"); return NULL; } if (setup_easy_handler_params (c, pcbc, url, header)) { return c; /* Success exit point */ } curl_easy_cleanup (c); return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int marker; (void) cls; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testLongUrlGet (size_t buff_size) { struct MHD_Daemon *d; unsigned int ret; ret = 1; /* Error value, shall be reset to zero if succeed */ d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */, daemon_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) buff_size, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "MHD_start_daemon() failed.\n"); return 16; } if (0 == daemon_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) fprintf (stderr, "MHD_get_daemon_info(d, MHD_DAEMON_INFO_BIND_PORT) " \ "failed.\n"); else daemon_port = dinfo->port; } if (0 != daemon_port) { char *url_str; url_str = malloc (VERY_LONG); if (NULL == url_str) fprintf (stderr, "malloc (VERY_LONG) failed.\n"); else { CURL *c; char buf[2048]; struct CBC cbc; memset (url_str, 'a', VERY_LONG); url_str[VERY_LONG - 1] = '\0'; memcpy (url_str, URL_SCHEME_HOST_PATH, MHD_STATICSTR_LEN_ (URL_SCHEME_HOST_PATH)); cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; c = setup_easy_handler (&cbc, url_str, NULL); if (NULL != c) { CURLcode r; r = curl_easy_perform (c); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_perform() failed. Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { long code; r = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_getinfo() failed. " "Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { if (code != MHD_HTTP_URI_TOO_LONG) { fprintf (stderr, "testLongHeaderGet(%lu) failed. HTTP " "response code is %ld, while it should be %ld.\n", (unsigned long) buff_size, code, (long) MHD_HTTP_URI_TOO_LONG); } else { printf ("testLongHeaderGet(%lu) succeed. HTTP " "response code is %ld, as expected.\n", (unsigned long) buff_size, (long) MHD_HTTP_URI_TOO_LONG); ret = 0; /* Success */ } } } curl_easy_cleanup (c); } free (url_str); } } MHD_stop_daemon (d); return ret; } static unsigned int testLongHeaderGet (size_t buff_size) { struct MHD_Daemon *d; unsigned int ret; ret = 1; /* Error value, shall be reset to zero if succeed */ d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */, daemon_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) buff_size, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "MHD_start_daemon() failed.\n"); return 16; } if (0 == daemon_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) fprintf (stderr, "MHD_get_daemon_info(d, MHD_DAEMON_INFO_BIND_PORT) " \ "failed.\n"); else daemon_port = dinfo->port; } if (0 != daemon_port) { char *header_str; header_str = malloc (VERY_LONG); if (NULL == header_str) fprintf (stderr, "malloc (VERY_LONG) failed.\n"); else { struct curl_slist *header = NULL; memset (header_str, 'a', VERY_LONG); header_str[VERY_LONG - 1] = '\0'; header_str[VERY_LONG / 2] = ':'; header_str[VERY_LONG / 2 + 1] = ' '; header = curl_slist_append (header, header_str); if (NULL == header) fprintf (stderr, "curl_slist_append () failed.\n"); else { CURL *c; char buf[2048]; struct CBC cbc; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; c = setup_easy_handler (&cbc, NULL, header); if (NULL != c) { CURLcode r; r = curl_easy_perform (c); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_perform() failed. Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { long code; r = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_getinfo() failed. " "Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { if (code != MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE) { fprintf (stderr, "testLongHeaderGet(%lu) failed. HTTP " "response code is %ld, while it should be %ld.\n", (unsigned long) buff_size, code, (long) MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE); } else { printf ("testLongHeaderGet(%lu) succeed. HTTP " "response code is %ld, as expected.\n", (unsigned long) buff_size, (long) MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE); ret = 0; /* Success */ } } } curl_easy_cleanup (c); } curl_slist_free_all (header); } free (header_str); } } MHD_stop_daemon (d); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) daemon_port = 0; else daemon_port = oneone ? 1336 : 1331; errorCount += testLongUrlGet (VERY_LONG / 2); errorCount += testLongUrlGet (VERY_LONG / 2 + 978); errorCount += testLongHeaderGet (VERY_LONG / 2); errorCount += testLongHeaderGet (VERY_LONG / 2 + 1893); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); else printf ("Test succeed.\n"); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/Makefile.am0000644000175000017500000004033715035214301015770 00000000000000# This Makefile.am is in the public domain EMPTY_ITEM = @HEAVY_TESTS_NOTPARALLEL@ SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += -fprofile-arcs -ftest-coverage endif if ENABLE_HTTPS SUBDIRS += https endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la THREAD_ONLY_TESTS = \ test_urlparse \ test_long_header \ test_long_header11 \ test_iplimit11 \ test_termination \ $(EMPTY_ITEM) if HEAVY_TESTS THREAD_ONLY_TESTS += \ test_add_conn_cleanup \ test_add_conn_cleanup_nolisten \ test_timeout \ $(EMPTY_ITEM) endif if HAVE_POSIX_THREADS if HEAVY_TESTS THREAD_ONLY_TESTS += \ perf_get_concurrent11 \ $(EMPTY_ITEM) endif THREAD_ONLY_TESTS += \ test_get_wait \ test_get_wait11 \ $(EMPTY_ITEM) if HEAVY_TESTS THREAD_ONLY_TESTS += \ test_concurrent_stop \ test_quiesce \ $(EMPTY_ITEM) endif if HAVE_CURL_BINARY THREAD_ONLY_TESTS += \ test_quiesce_stream endif endif if HEAVY_TESTS if HAVE_POSIX_THREADS THREAD_ONLY_TESTS += \ perf_get_concurrent endif endif if RUN_LIBCURL_TESTS check_PROGRAMS = \ test_get \ test_head \ test_head10 \ test_get_iovec \ test_get_sendfile \ test_get_close \ test_get_close10 \ test_get_keep_alive \ test_get_keep_alive10 \ test_delete \ test_patch \ test_put \ test_add_conn \ test_add_conn_nolisten \ test_process_headers \ test_process_arguments \ test_toolarge_method \ test_toolarge_url \ test_toolarge_request_header_name \ test_toolarge_request_header_value \ test_toolarge_request_headers \ test_toolarge_reply_header_name \ test_toolarge_reply_header_value \ test_toolarge_reply_headers \ test_tricky_url \ test_tricky_header2 \ test_large_put \ test_get11 \ test_get_iovec11 \ test_get_sendfile11 \ test_patch11 \ test_put11 \ test_large_put11 \ test_large_put_inc11 \ test_put_broken_len10 \ test_put_broken_len \ test_get_chunked \ test_get_chunked_close \ test_get_chunked_string \ test_get_chunked_close_string \ test_get_chunked_empty \ test_get_chunked_close_empty \ test_get_chunked_string_empty \ test_get_chunked_close_string_empty \ test_get_chunked_sized \ test_get_chunked_close_sized \ test_get_chunked_empty_sized \ test_get_chunked_close_empty_sized \ test_get_chunked_forced \ test_get_chunked_close_forced \ test_get_chunked_empty_forced \ test_get_chunked_close_empty_forced \ test_put_chunked \ test_callback \ test_get_header_fold \ test_put_header_fold \ test_put_large_header_fold \ test_put_header_fold_last \ test_put_header_fold_large \ test_get_header_double_fold \ test_put_header_double_fold \ test_put_large_header_double_fold \ test_put_header_double_fold_last \ test_put_header_double_fold_large \ $(EMPTY_ITEM) if ENABLE_COOKIE check_PROGRAMS += \ test_parse_cookies_discp_p2 \ test_parse_cookies_discp_p1 \ test_parse_cookies_discp_zero \ test_parse_cookies_discp_n2 \ test_parse_cookies_discp_n3 endif if HEAVY_TESTS check_PROGRAMS += \ perf_get endif if ENABLE_BAUTH check_PROGRAMS += \ test_basicauth test_basicauth_preauth \ test_basicauth_oldapi test_basicauth_preauth_oldapi endif if HAVE_POSTPROCESSOR check_PROGRAMS += \ test_post \ test_postform \ test_post_loop \ test_post11 \ test_postform11 \ test_post_loop11 endif if ENABLE_DAUTH if ENABLE_MD5 THREAD_ONLY_TESTS += \ test_digestauth \ test_digestauth_with_arguments \ test_digestauth_concurrent endif if ENABLE_SHA256 THREAD_ONLY_TESTS += \ test_digestauth_sha256 endif if ENABLE_MD5 check_PROGRAMS += \ test_digestauth_emu_ext \ test_digestauth_emu_ext_oldapi \ test_digestauth2 \ test_digestauth2_rfc2069 \ test_digestauth2_rfc2069_userdigest \ test_digestauth2_oldapi1 \ test_digestauth2_oldapi2 \ test_digestauth2_userhash \ test_digestauth2_userdigest \ test_digestauth2_oldapi1_userdigest \ test_digestauth2_oldapi2_userdigest \ test_digestauth2_userhash_userdigest \ test_digestauth2_bind_all \ test_digestauth2_bind_uri \ test_digestauth2_oldapi1_bind_all \ test_digestauth2_oldapi1_bind_uri endif if ENABLE_SHA256 check_PROGRAMS += \ test_digestauth2_sha256 \ test_digestauth2_sha256_userhash \ test_digestauth2_oldapi2_sha256 \ test_digestauth2_sha256_userdigest \ test_digestauth2_oldapi2_sha256_userdigest \ test_digestauth2_sha256_userhash_userdigest endif endif if HEAVY_TESTS if HAVE_FORK_WAITPID if HAVE_CURL_BINARY check_PROGRAMS += test_get_response_cleanup endif endif endif if USE_POSIX_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif if USE_W32_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif TESTS = $(check_PROGRAMS) endif test_concurrent_stop_SOURCES = \ test_concurrent_stop.c test_concurrent_stop_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_concurrent_stop_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_head_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_head10_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_quiesce_SOURCES = \ test_quiesce.c mhd_has_param.h mhd_has_in_name.h test_quiesce_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_quiesce_stream_SOURCES = \ test_quiesce_stream.c test_quiesce_stream_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_stream_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_callback_SOURCES = \ test_callback.c perf_get_SOURCES = \ perf_get.c \ mhd_has_in_name.h perf_get_concurrent_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent_LDADD = \ $(PTHREAD_LIBS) $(LDADD) perf_get_concurrent11_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent11_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_basicauth_SOURCES = \ test_basicauth.c test_basicauth_preauth_SOURCES = \ test_basicauth.c test_basicauth_oldapi_SOURCES = \ test_basicauth.c test_basicauth_preauth_oldapi_SOURCES = \ test_basicauth.c test_digestauth_SOURCES = \ test_digestauth.c test_digestauth_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_sha256_SOURCES = \ test_digestauth_sha256.c test_digestauth_sha256_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_with_arguments_SOURCES = \ test_digestauth_with_arguments.c test_digestauth_with_arguments_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_concurrent_SOURCES = \ test_digestauth_concurrent.c test_digestauth_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_digestauth_concurrent_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) $(PTHREAD_LIBS) $(LDADD) test_digestauth_emu_ext_SOURCES = \ test_digestauth_emu_ext.c test_digestauth_emu_ext_oldapi_SOURCES = \ test_digestauth_emu_ext.c test_digestauth2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_get_iovec_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_wait_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_wait11_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait11_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_urlparse_SOURCES = \ test_urlparse.c mhd_has_in_name.h test_get_response_cleanup_SOURCES = \ test_get_response_cleanup.c mhd_has_in_name.h test_get_chunked_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_post_SOURCES = \ test_post.c mhd_has_in_name.h test_process_headers_SOURCES = \ test_process_headers.c mhd_has_in_name.h test_parse_cookies_discp_zero_SOURCES = \ test_parse_cookies.c mhd_has_in_name.h mhd_has_param.h test_parse_cookies_discp_p2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_p1_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n3_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_process_arguments_SOURCES = \ test_process_arguments.c mhd_has_in_name.h test_postform_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_delete_SOURCES = \ test_delete.c mhd_has_in_name.h test_patch_SOURCES = \ test_patch.c mhd_has_in_name.h test_patch11_SOURCES = \ test_patch.c mhd_has_in_name.h test_put_SOURCES = \ test_put.c mhd_has_in_name.h test_put_chunked_SOURCES = \ test_put_chunked.c test_add_conn_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get11_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_get_iovec11_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile11_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_close_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_close10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_post11_SOURCES = \ test_post.c mhd_has_in_name.h test_postform11_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform11_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop11_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_put11_SOURCES = \ test_put.c mhd_has_in_name.h test_large_put_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put_inc11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_long_header_SOURCES = \ test_long_header.c mhd_has_in_name.h test_long_header11_SOURCES = \ test_long_header.c mhd_has_in_name.h test_iplimit11_SOURCES = \ test_iplimit.c mhd_has_in_name.h test_termination_SOURCES = \ test_termination.c test_timeout_SOURCES = \ test_timeout.c mhd_has_in_name.h test_toolarge_method_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_url_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_tricky_url_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_tricky_header2_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len_SOURCES = \ test_put_broken_len.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len10_SOURCES = $(test_put_broken_len_SOURCES) test_put_header_fold_SOURCES = \ test_put_header_fold.c mhd_has_in_name.h mhd_has_param.h test_put_large_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_get_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_last_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_large_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_large_header_double_fold_SOURCES = $(test_put_large_header_fold_SOURCES) test_get_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_last_SOURCES = $(test_put_header_fold_last_SOURCES) test_put_header_double_fold_large_SOURCES = $(test_put_header_fold_large_SOURCES) libmicrohttpd-1.0.2/src/testcurl/test_large_put.c0000644000175000017500000006664514760713574017157 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_large_put.c * @brief Testcase for libmicrohttpd PUT operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_has_in_name.h" #include "mhd_has_param.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } static int oneone; static int incr_read; /* Use incremental read */ static int verbose; /* Be verbose */ #define PUT_SIZE (256 * 1024) static char *put_buffer; struct CBC { char *buf; size_t pos; size_t size; }; static char * alloc_init (size_t buf_size) { static const char template[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz"; static const size_t templ_size = sizeof(template) / sizeof(char) - 1; char *buf; char *fill_ptr; size_t to_fill; buf = malloc (buf_size); if (NULL == buf) externalErrorExit (); fill_ptr = buf; to_fill = buf_size; while (to_fill > 0) { const size_t to_copy = to_fill > templ_size ? templ_size : to_fill; memcpy (fill_ptr, template, to_copy); fill_ptr += to_copy; to_fill -= to_copy; } return buf; } static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = (size_t *) ptr; size_t wrt; wrt = size * nmemb; /* Check for overflow. */ if (wrt / size != nmemb) libcurlErrorExitDesc ("Too large buffer size"); if (wrt > PUT_SIZE - (*pos)) wrt = PUT_SIZE - (*pos); memcpy (stream, &put_buffer[*pos], wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) libcurlErrorExitDesc ("Too large buffer size"); memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; static size_t processed; if (NULL == cls) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, oneone ? MHD_HTTP_VERSION_1_1 : MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); if (NULL == url) mhdErrorExitDesc ("url parameter is NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != strcmp ("PUT", method)) mhdErrorExitDesc ("Unexpected request method"); /* unexpected method */ if ((*done) == 0) { size_t *pproc; if (NULL == *req_cls) { processed = 0; /* Safe as long as only one parallel request served. */ *req_cls = &processed; } pproc = (size_t *) *req_cls; if (0 == *upload_data_size) return MHD_YES; /* No data to process. */ if (*pproc + *upload_data_size > PUT_SIZE) mhdErrorExitDesc ("Incoming data larger than expected"); if ( (! incr_read) && (*upload_data_size != PUT_SIZE) ) return MHD_YES; /* Wait until whole request is received. */ if (0 != memcmp (upload_data, put_buffer + (*pproc), *upload_data_size)) mhdErrorExitDesc ("Incoming data does not match sent data"); *pproc += *upload_data_size; *upload_data_size = 0; /* Current block of data is fully processed. */ if (PUT_SIZE == *pproc) *done = 1; /* Whole request is processed. */ return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testPutInternalThread (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1270; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4 / 3)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutThreadPerConn (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1271; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutThreadPool (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1272; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutExternal (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1273; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; multi = NULL; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } multi = curl_multi_init (); if (multi == NULL) libcurlErrorExit (); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) libcurlErrorExit (); start = time (NULL); while ((time (NULL) - start < 45) && (multi != NULL)) { MHD_socket maxMHDsock; int maxcurlsock; maxMHDsock = MHD_INVALID_SOCKET; maxcurlsock = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_perform (multi, &running); if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret)) { fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ", curl_multi_strerror (mret)); libcurlErrorExit (); } if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxcurlsock)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMHDsock)) mhdErrorExit (); tv.tv_sec = 0; tv.tv_usec = 1000; #ifndef MHD_WINSOCK_SOCKETS if (maxMHDsock > maxcurlsock) maxcurlsock = maxMHDsock; #endif /* MHD_WINSOCK_SOCKETS */ if (-1 == select (maxcurlsock + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } mret = curl_multi_perform (multi, &running); if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret)) { fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ", curl_multi_strerror (mret)); libcurlErrorExit (); } if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "curl_multi_perform() failed: '%s' ", curl_easy_strerror (msg->data.result)); libcurlErrorExit (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code "); mhdErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) mhdErrorExitDesc ("Request has been aborted by timeout"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int lastErr; oneone = has_in_name (argv[0], "11"); incr_read = has_in_name (argv[0], "_inc"); verbose = has_param (argc, argv, "-v"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 99; put_buffer = alloc_init (PUT_SIZE); if (NULL == put_buffer) return 99; lastErr = testPutExternal (); if (verbose && (0 != lastErr)) fprintf (stderr, "Error during testing with external select().\n"); errorCount += lastErr; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { lastErr = testPutInternalThread (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with select().\n"); errorCount += lastErr; lastErr = testPutThreadPerConn (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread per connection with select().\n"); errorCount += lastErr; lastErr = testPutThreadPool (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with select().\n"); errorCount += lastErr; if (MHD_is_feature_supported (MHD_FEATURE_POLL)) { lastErr = testPutInternalThread (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with poll().\n"); errorCount += lastErr; lastErr = testPutThreadPerConn (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread per connection with poll().\n"); errorCount += lastErr; lastErr = testPutThreadPool (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with poll().\n"); errorCount += lastErr; } if (MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { lastErr = testPutInternalThread (MHD_USE_EPOLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with epoll.\n"); errorCount += lastErr; lastErr = testPutThreadPool (MHD_USE_EPOLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with epoll.\n"); errorCount += lastErr; } } free (put_buffer); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All checks passed successfully.\n"); curl_global_cleanup (); return (errorCount == 0) ? 0 : 1; } libmicrohttpd-1.0.2/src/testcurl/test_toolarge.c0000644000175000017500000016011114760713574016770 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_toolarge.c * @brief Testcase for handling of data larger then buffers. * @details Testcases for handling of various situations when data cannot fit * the buffers. Address sanitizers and debug asserts should increase * number of problems detected by this test (detect actual overrun). * Tests start with valid sizes to ensure that normal data is processed * correctly and then sizes are monotonically increased to ensure that * overflow is handled correctly at all stages in all codepaths. * Tests with valid sizes are repeated several times to ensure that * tests are failed because of overflow, but because of second run. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/a" #define URL_SCHEME_HOST "http:/" "/127.0.0.1" #define N1_HEADER_NAME "n" #define N1_HEADER_VALUE "1" #define N1_HEADER N1_HEADER_NAME ": " N1_HEADER_VALUE #define N1_HEADER_CRLF N1_HEADER "\r\n" #define BUFFER_SIZE 1024 /* The size of the test element that must pass the test */ #ifndef MHD_ASAN_POISON_ACTIVE #define TEST_OK_SIZE (BUFFER_SIZE - 384) #else /* MHD_ASAN_POISON_ACTIVE */ #define TEST_OK_SIZE (BUFFER_SIZE - 384 - 80) #endif /* MHD_ASAN_POISON_ACTIVE */ /* The size of the test element where tests are started */ #define TEST_START_SIZE (TEST_OK_SIZE - 16) /* The size of the test element that must definitely fail */ #define TEST_FAIL_SIZE (BUFFER_SIZE + 32) /* Special value for request many headers test. * MHD uses the same buffer to store headers strings and pointers to the strings * so allocation is multiplied for small request header. */ /* The size of the test element that must pass the test */ #define TEST_RQ_N1_OK_SIZE 50 /* The size of the test element where tests are started */ #define TEST_RQ_N1_START_SIZE (TEST_RQ_N1_OK_SIZE - 32) /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int large_req_method; /**< Large request method */ static int large_req_url; /**< Large request URL */ static int large_req_header_name; /**< Large request single header name */ static int large_req_header_value; /**< Large request single header value */ static int large_req_headers; /**< Large request headers */ static int large_rsp_header_name; /**< Large response single header name */ static int large_rsp_header_value; /**< Large response single header value */ static int large_rsp_headers; /**< Large response headers */ static int response_timeout_val = TIMEOUTS_VAL; /* Current test parameters */ /* * Moved to local variables * */ /* Static helper variables */ /* * None for this test * */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { unsigned int num_n1_headers; size_t large_header_name_size; size_t large_header_value_size; int large_header_valid; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((6 == data_size) && (0 == memcmp (N1_HEADER_CRLF, buffer, 6))) check_res->num_n1_headers++; else if ((5 <= data_size) && ('0' == buffer[0])) { const char *const col_ptr = memchr (buffer, ':', data_size); if (0 != check_res->large_header_value_size) mhdErrorExitDesc ("Expected only one large header, " \ "but found two large headers in the reply"); if (NULL == col_ptr) check_res->large_header_valid = 0; else if ((size_t) (col_ptr - buffer) >= data_size - 2) check_res->large_header_valid = 0; else if (*(col_ptr + 1) != ' ') check_res->large_header_valid = 0; else { const char *const name = buffer; const size_t name_len = (size_t) (col_ptr - buffer); const size_t val_pos = name_len + 2; const size_t val_len = data_size - val_pos - 2; /* 2 = strlen("\r\n") */ const char *const value = buffer + val_pos; size_t i; check_res->large_header_name_size = name_len; check_res->large_header_value_size = val_len; check_res->large_header_valid = 1; /* To be reset if any problem found */ for (i = 1; i < name_len; i++) if ('a' + (char) (i % ('z' - 'a' + 1)) != name[i]) { fprintf (stderr, "Wrong sequence in reply header name " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'a' + (char) (i % ('z' - 'a' + 1)), name[i]); check_res->large_header_valid = 0; break; } for (i = 0; i < val_len; i++) if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i]) { fprintf (stderr, "Wrong sequence in reply header value " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'Z' - (char) (i % ('Z' - 'A' + 1)), value[i]); check_res->large_header_valid = 0; break; } } } return data_size; } struct lcurl_data_cb_param { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct lcurl_data_cb_param *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct check_uri_cls { const char *volatile uri; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; (void) con; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: `%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } struct mhd_header_checker_param { unsigned int num_n1_headers; size_t large_header_name_size; size_t large_header_value_size; int large_header_valid; }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((1 == key_size) && (1 == value_size) && ('n' == key[0]) && ('1' == value[0])) param->num_n1_headers++; else if ('0' == key[0]) { /* Found 'large' header */ size_t i; param->large_header_name_size = key_size; param->large_header_value_size = value_size; param->large_header_valid = 1; for (i = 1; i < key_size; i++) if ('a' + (char) (i % ('z' - 'a' + 1)) != key[i]) { fprintf (stderr, "Wrong sequence in request header name " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'a' + (char) (i % ('z' - 'a' + 1)), key[i]); param->large_header_valid = 0; break; } for (i = 0; i < value_size; i++) if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i]) { fprintf (stderr, "Wrong sequence in request header value " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'Z' - (char) (i % ('Z' - 'A' + 1)), value[i]); param->large_header_valid = 0; break; } } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; volatile size_t rp_num_n1_hdrs; volatile size_t rp_large_hdr_name_size; volatile size_t rp_large_hdr_value_size; struct mhd_header_checker_param header_check_param; const char *volatile rq_method; const char *volatile rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; size_t i; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, ¶m->header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); response = MHD_create_response_from_buffer_copy (param->rp_data_size, (const void *) param->rp_data); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); for (i = 0; i < param->rp_num_n1_hdrs; i++) if (MHD_YES != MHD_add_response_header (response, N1_HEADER_NAME, N1_HEADER_VALUE)) mhdErrorExitDesc ("Cannot add header"); if (0 != param->rp_large_hdr_name_size) { const size_t large_hdr_name_size = param->rp_large_hdr_name_size; char *large_hrd_name; const size_t large_hdr_value_size = param->rp_large_hdr_value_size; char *large_hrd_value; large_hrd_name = malloc (large_hdr_name_size + 1); if (NULL == large_hrd_name) externalErrorExit (); if (0 != large_hdr_value_size) large_hrd_value = malloc (large_hdr_value_size + 1); else large_hrd_value = NULL; if ((0 != large_hdr_value_size) && (NULL == large_hrd_value)) externalErrorExit (); large_hrd_name[0] = '0'; /* Name starts with zero for unique identification */ for (i = 1; i < large_hdr_name_size; i++) large_hrd_name[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); large_hrd_name[large_hdr_name_size] = 0; for (i = 0; i < large_hdr_value_size; i++) large_hrd_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); if (NULL != large_hrd_value) large_hrd_value[large_hdr_value_size] = 0; if (MHD_YES != MHD_add_response_header (response, large_hrd_name, large_hrd_value)) mhdErrorExitDesc ("Cannot add large header"); if (NULL != large_hrd_value) free (large_hrd_value); free (large_hrd_name); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static CURL * curlEasyInitForTest (const char *queryPath, const char *method, uint16_t port, struct lcurl_data_cb_param *dcbp, struct headers_check_result *hdr_chk_result, struct curl_slist *headers) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, method)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for CURL query */ uint16_t queryPort; /* List of additional request headers */ struct curl_slist *headers; /* CURL query result error flag */ volatile unsigned int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* Returns zero for successful response and non-zero for failed response */ static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, struct headers_check_result *hdr_res, const char *expected_data, size_t expected_data_size) { const union MHD_DaemonInfo *dinfo; CURL *c; struct lcurl_data_cb_param dcbp; CURLcode errornum; int use_external_poll; long resp_code; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); /* Test must not fail due to test's internal buffer shortage */ dcbp.size = TEST_FAIL_SIZE * 2 + 1; dcbp.buf = malloc (dcbp.size); if (NULL == dcbp.buf) externalErrorExit (); dcbp.pos = 0; memset (hdr_res, 0, sizeof(*hdr_res)); c = curlEasyInitForTest (p->queryPath, p->method, p->queryPort, &dcbp, hdr_res, p->headers); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code)) libcurlErrorExitDesc ("curl_easy_getinfo() failed"); p->responseCode = (int) resp_code; if ((CURLE_OK == errornum) && (200 != resp_code)) { fprintf (stderr, "Got reply with unexpected status code: %d\n", p->responseCode); mhdErrorExit (); } if (CURLE_OK != errornum) { if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum) && (CURLE_HTTP_RETURNED_ERROR != errornum)) { if (CURLE_OPERATION_TIMEDOUT == errornum) mhdErrorExitDesc ("Request was aborted due to timeout"); fprintf (stderr, "libcurl returned unexpected error: %s\n", curl_easy_strerror (errornum)); mhdErrorExitDesc ("Request failed due to unexpected error"); } p->queryError = 1; switch (resp_code) { case 0: /* No parsed response */ case 413: /* "Content Too Large" */ case 414: /* "URI Too Long" */ case 431: /* "Request Header Fields Too Large" */ case 501: /* "Not Implemented" */ /* Expected error codes */ break; default: fprintf (stderr, "Got reply with unexpected status code: %ld\n", resp_code); mhdErrorExit (); } } else { if (dcbp.pos != expected_data_size) mhdErrorExit ("libcurl reports wrong size of MHD reply body data"); else if (0 != memcmp (expected_data, dcbp.buf, expected_data_size)) mhdErrorExit ("libcurl reports wrong MHD reply body data"); else p->queryError = 0; } curl_easy_cleanup (c); free (dcbp.buf); return p->queryError; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ struct headers_check_result rp_headers_check; char *buf; size_t i; size_t first_failed_at = 0; buf = malloc (TEST_FAIL_SIZE + 1 + strlen (URL_SCHEME_HOST)); if (NULL == buf) externalErrorExit (); /* Common parameters, to be individually overridden by specific test cases */ qParam.queryPort = d_port; qParam.method = NULL; /* Use libcurl default: GET */ qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH; qParam.headers = NULL; /* No additional headers */ uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = "GET"; /* Default expected method */ ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->rp_large_hdr_name_size = 0; ahc_param->rp_large_hdr_value_size = 0; ahc_param->rp_num_n1_hdrs = 0; if (large_req_method) { for (i = 0; i < TEST_START_SIZE; i++) buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { buf[i] = 0; qParam.method = buf; ahc_param->rq_method = buf; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (501 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, " "while code 501 (\"Not Implemented\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1)); } } else if (large_req_url) { const size_t base_size = strlen (URL_SCHEME_HOST); char *const url = buf + base_size; memcpy (buf, URL_SCHEME_HOST, base_size); url[0] = '/'; for (i = 1; i < TEST_START_SIZE; i++) url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { url[i] = 0; qParam.queryPath = buf; uri_cb_param->uri = url; ahc_param->rq_url = url; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (414 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, " "while code 414 (\"URI Too Long\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); } } else if (large_req_header_name) { buf[0] = '0'; /* Name starts with zero for unique identification */ for (i = 1; i < TEST_START_SIZE; i++) buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { struct curl_slist *curl_headers; curl_headers = NULL; memcpy (buf + i, ": Z", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */ buf[i + 3] = 0; curl_headers = curl_slist_append (curl_headers, buf); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.large_header_name_size) { /* If large header was processed, it must be valid */ if (i != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (1 != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (i != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (1 != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_slist_free_all (curl_headers); buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); } } else if (large_req_header_value) { char *const hdr_value = buf + 3; /* Name starts with zero for unique identification */ memcpy (buf, "0: ", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */ for (i = 0; i < TEST_START_SIZE; i++) hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { struct curl_slist *curl_headers; curl_headers = NULL; hdr_value[i] = 0; curl_headers = curl_slist_append (curl_headers, buf); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.large_header_name_size) { /* If large header was processed, it must be valid */ if (1 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (i != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (1 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (i != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_slist_free_all (curl_headers); hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); } } else if (large_req_headers) { unsigned int num_hdrs = 0; struct curl_slist *curl_headers; const size_t hdr_size = strlen (N1_HEADER_CRLF); curl_headers = NULL; for (i = 0; i < TEST_RQ_N1_START_SIZE; i += hdr_size) { curl_headers = curl_slist_append (curl_headers, N1_HEADER); if (NULL == curl_headers) externalErrorExit (); num_hdrs++; } for (; i <= TEST_FAIL_SIZE; i += hdr_size) { qParam.headers = curl_headers; ahc_param->header_check_param.num_n1_headers = num_hdrs; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.num_n1_headers) { /* If headers were processed, they must be valid */ if (num_hdrs != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of request headers"); } if (TEST_RQ_N1_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (num_hdrs != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of request headers"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_headers = curl_slist_append (curl_headers, N1_HEADER); if (NULL == curl_headers) externalErrorExit (); num_hdrs++; } curl_slist_free_all (curl_headers); } else if (large_rsp_header_name) { for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++) { ahc_param->rp_large_hdr_name_size = i; ahc_param->rp_large_hdr_value_size = 1; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (i != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected wrong large reply header name size"); if (1 != rp_headers_check.large_header_value_size) mhdErrorExitDesc ("Detected wrong large reply header value size"); if (0 == rp_headers_check.large_header_valid) mhdErrorExitDesc ("Detected wrong large reply header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); } } else if (large_rsp_header_value) { for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++) { ahc_param->rp_large_hdr_name_size = 1; ahc_param->rp_large_hdr_value_size = i; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (1 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected wrong large reply header name size"); if (i != rp_headers_check.large_header_value_size) mhdErrorExitDesc ("Detected wrong large reply header value size"); if (0 == rp_headers_check.large_header_valid) mhdErrorExitDesc ("Detected wrong large reply header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); } } else if (large_rsp_headers) { size_t num_hrds; const size_t hdr_size = strlen (N1_HEADER_CRLF); for (num_hrds = TEST_START_SIZE / hdr_size; num_hrds * hdr_size <= TEST_FAIL_SIZE; num_hrds++) { i = num_hrds * hdr_size; ahc_param->rp_num_n1_hdrs = num_hrds; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (num_hrds != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of reply headers"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); } } else externalErrorExitDesc ("No valid test test was selected"); MHD_stop_daemon (d); free (buf); free (uri_cb_param); free (ahc_param); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param)) abort (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4100; if (large_req_method) *pport += 1; if (large_req_url) *pport += 2; if (large_req_header_name) *pport += 3; if (large_req_header_value) *pport += 4; if (large_req_headers) *pport += 5; if (large_rsp_header_name) *pport += 6; if (large_rsp_header_value) *pport += 7; if (large_rsp_headers) *pport += 8; if (! oneone) *pport += 16; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); large_req_method = has_in_name (argv[0], "_method") ? 1 : 0; large_req_url = has_in_name (argv[0], "_url") ? 1 : 0; large_req_header_name = has_in_name (argv[0], "_request_header_name") ? 1 : 0; large_req_header_value = has_in_name (argv[0], "_request_header_value") ? 1 : 0; large_req_headers = has_in_name (argv[0], "_request_headers") ? 1 : 0; large_rsp_header_name = has_in_name (argv[0], "_reply_header_name") ? 1 : 0; large_rsp_header_value = has_in_name (argv[0], "_reply_header_value") ? 1 : 0; large_rsp_headers = has_in_name (argv[0], "_reply_headers") ? 1 : 0; if (large_req_method + large_req_url + large_req_header_name + large_req_header_value + large_req_headers + large_rsp_header_name + large_rsp_header_value + large_rsp_headers != 1) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_get_response_cleanup.c0000644000175000017500000002576314760713574021375 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_get_response_cleanup.c * @brief Testcase for libmicrohttpd response cleanup * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #endif /* _WIN32 */ #ifndef WINDOWS #include #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "mhd_has_in_name.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; static int ok; static pid_t fork_curl (const char *url) { pid_t ret; ret = fork (); if (ret != 0) return ret; execlp ("curl", "curl", "-s", "-N", "-o", "/dev/null", "-GET", url, NULL); fprintf (stderr, "Failed to exec curl: %s\n", strerror (errno)); _exit (-1); } static void kill_curl (pid_t pid) { int status; /* fprintf (stderr, "Killing curl\n"); */ kill (pid, SIGTERM); waitpid (pid, &status, 0); } static ssize_t push_callback (void *cls, uint64_t pos, char *buf, size_t max) { (void) cls; (void) pos; /* Unused. Silent compiler warning. */ if (max == 0) return 0; buf[0] = 'd'; return 1; } static void push_free_callback (void *cls) { int *ok_p = cls; /* fprintf (stderr, "Cleanup callback called!\n"); */ *ok_p = 0; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &push_callback, &ok, &push_free_callback); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1180; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 2; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1181; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 2, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); /* fprintf (stderr, "Forking cURL!\n"); */ curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); curl = fork_curl (url); (void) sleep (1); if (ok != 0) { kill_curl (curl); MHD_stop_daemon (d); return 64; } kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 32; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1182; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 64; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 128; return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket max; time_t start; struct timeval tv; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1183; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); start = time (NULL); while ((time (NULL) - start < 2)) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run (d); } kill_curl (curl); start = time (NULL); while ((time (NULL) - start < 2)) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run (d); } /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 1024; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ #ifndef _WIN32 /* Solaris has no way to disable SIGPIPE on socket disconnect. */ if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { struct sigaction act; act.sa_handler = SIG_IGN; sigaction (SIGPIPE, &act, NULL); } #endif /* _WIN32 */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_get.c0000644000175000017500000007333314760713574015744 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get.c * @brief Testcase for libmicrohttpd GET operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ #define EXPECTED_URI_PATH "/hello_world?a=%26&b=c" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; static uint16_t global_port; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_PATH)) { fprintf (stderr, "Wrong URI: `%s'\n", uri); _exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *v; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; v = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "a"); if ( (NULL == v) || (0 != strcmp ("&", v)) ) { fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n", NULL == v ? "NULL" : v); _exit (17); } v = NULL; if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_GET_ARGUMENT_KIND, "b", 1, &v, NULL)) { fprintf (stderr, "Not found 'b' GET argument.\n"); _exit (18); } if ( (NULL == v) || (0 != strcmp ("c", v)) ) { fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n", NULL == v ? "NULL" : v); _exit (19); } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (19); } return ret; } static unsigned int testInternalGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1220; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1221; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1222; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; int running; struct CURLMsg *msg; time_t start; struct timeval tv; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1223; if (oneone) global_port += 20; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } static unsigned int testUnknownPortGet (uint32_t poll_flag) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u%s", (unsigned int) port, EXPECTED_URI_PATH); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 1048576; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 2097152; return 0; } static unsigned int testStopRace (uint32_t poll_flag) { struct sockaddr_in sin; MHD_socket fd; struct MHD_Daemon *d; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1224; if (oneone) global_port += 20; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } fd = socket (PF_INET, SOCK_STREAM, 0); if (fd == MHD_INVALID_SOCKET) { fprintf (stderr, "socket error\n"); return 256; } memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (global_port); sin.sin_addr.s_addr = htonl (0x7f000001); if (connect (fd, (struct sockaddr *) (&sin), sizeof(sin)) < 0) { fprintf (stderr, "connect error\n"); MHD_socket_close_chk_ (fd); return 512; } /* printf("Waiting\n"); */ /* Let the thread get going. */ usleep (500000); /* printf("Stopping daemon\n"); */ MHD_stop_daemon (d); MHD_socket_close_chk_ (fd); /* printf("good\n"); */ return 0; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("GET", method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silent compiler warning. */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); verbose = has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; global_port = 0; test_result = testExternalGet (! 0); if (test_result) fprintf (stderr, "FAILED: testExternalGet (!0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result += testExternalGet (0); if (test_result) fprintf (stderr, "FAILED: testExternalGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; test_result += testInternalGet (0); if (test_result) fprintf (stderr, "FAILED: testInternalGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (0).\n"); errorCount += test_result; test_result += testMultithreadedGet (0); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (0).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (0); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (0).\n"); errorCount += test_result; test_result += testUnknownPortGet (0); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (0).\n"); errorCount += test_result; test_result += testStopRace (0); if (test_result) fprintf (stderr, "FAILED: testStopRace (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (0).\n"); errorCount += test_result; test_result += testEmptyGet (0); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (0).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result += testInternalGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testInternalGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testMultithreadedGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testUnknownPortGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testStopRace (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testStopRace (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testEmptyGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (MHD_USE_POLL).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result += testInternalGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testInternalGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testUnknownPortGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testEmptyGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (MHD_USE_EPOLL).\n"); errorCount += test_result; } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_digestauth_sha256.c0000644000175000017500000002364614760713574020420 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2018 Christian Grothoff Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth_sha256.c * @brief Testcase for libmicrohttpd Digest Auth with SHA256 * @author Amr Ali * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_SHA256); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testDigestAuth (void) { CURL *c; CURLcode errornum; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; char url[128]; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1167; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", GetLastError ()); return 1; } b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (b == 0) return 1; } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/bar%%20foo?key=value", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) return 4; if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) return 8; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; curl_version_info_data *d = curl_version_info (CURLVERSION_NOW); (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing" "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ #ifdef CURL_VERSION_SSPI if (0 != (d->features & CURL_VERSION_SSPI)) return 77; /* Skip test, W32 SSPI doesn't support sha256 digest */ #endif /* CURL_VERSION_SSPI */ /* curl added SHA256 support in 7.57 = 7.0x39 */ if (d->version_num < 0x073900) return 77; /* skip test, curl is too old */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/testcurl/test_put_chunked.c0000644000175000017500000003715614760713574017501 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_put_chunked.c * @brief Testcase for libmicrohttpd PUT operations with chunked encoding * for the upload data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); if (wrt > 4) wrt = 4; /* only send half at first => force multiple chunks! */ memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { size_t *done = cls; struct MHD_Response *response; enum MHD_Result ret; size_t have; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PUT", method)) return MHD_NO; /* unexpected method */ if ((*done) < 8) { have = *upload_data_size; if (have + *done > 8) { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } if (0 == have) return MHD_YES; if (0 == memcmp (upload_data, &"Hello123"[*done], have)) { *done += have; *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } #if 0 fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8); #endif return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1440; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1441; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1442; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; size_t done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1443; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/examples/0000755000175000017500000000000015035216652013771 500000000000000libmicrohttpd-1.0.2/src/examples/websocket_chatserver_example.c0000644000175000017500000023637314760713574022033 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021 David Gausmann (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file websocket_chatserver_example.c * @brief example for how to use websockets * @author David Gausmann * * Access the HTTP server with your webbrowser. * The webbrowser must support JavaScript and WebSockets. * The websocket access will be initiated via the JavaScript on the website. * You will get an example chat room, which uses websockets. * For testing with multiple users, just start several instances of your webbrowser. * */ #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) #define _CRT_SECURE_NO_WARNINGS #endif #include "platform.h" #include #include #include #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) /* Workaround for Windows systems, because the NuGet version of pthreads is buggy. This is a simple replacement. It doesn't offer all functions of pthread, but has everything, what is required for this example. See: https://github.com/coapp-packages/pthreads/issues/2 */ #include "pthread_windows.h" /* On Windows we will use stricmp instead of strcasecmp (strcasecmp is undefined there). */ #define strcasecmp stricmp #else /* On Unix systems we can use pthread. */ #include #endif /* * Specify with this constant whether or not to use HTTPS. * 0 means HTTP, 1 means HTTPS. * Please note that you must enter a valid private key/certificate pair * in the main procedure to running this example with HTTPS. */ #define USE_HTTPS 0 /** * This is the main website. * The HTML, CSS and JavaScript code is all in there. */ #define PAGE \ "" \ "" \ "" \ "" \ "libmicrohttpd websocket chatserver demo" \ "" \ "" \ "" \ "" \ "" #define PAGE_NOT_FOUND \ "404 Not Found" #define PAGE_INVALID_WEBSOCKET_REQUEST \ "Invalid WebSocket request!" /** * This struct is used to keep the data of a connected chat user. * It is passed to the socket-receive thread (connecteduser_receive_messages) as well as to * the socket-send thread (connecteduser_send_messages). * It can also be accessed via the global array users (mutex protected). */ struct ConnectedUser { /* the TCP/IP socket for reading/writing */ MHD_socket fd; /* the UpgradeResponseHandle of libmicrohttpd (needed for closing the socket) */ struct MHD_UpgradeResponseHandle *urh; /* the websocket encode/decode stream */ struct MHD_WebSocketStream *ws; /* the possibly read data at the start (only used once) */ char *extra_in; size_t extra_in_size; /* the unique user id (counting from 1, ids will never be re-used) */ size_t user_id; /* the current user name */ char *user_name; size_t user_name_len; /* the zero-based index of the next message; may be decremented when old messages are deleted */ size_t next_message_index; /* specifies whether the websocket shall be closed (1) or not (0) */ int disconnect; /* condition variable to wake up the sender of this connection */ pthread_cond_t wake_up_sender; /* mutex to ensure that no send actions are mixed (sending can be done by send and recv thread; may not be simultaneously locked with chat_mutex by the same thread) */ pthread_mutex_t send_mutex; /* specifies whether a ping shall be executed (1), is being executed (2) or no ping is pending (0) */ int ping_status; /* the start time of the ping, if a ping is running */ struct timespec ping_start; /* the message used for the ping (must match the pong response)*/ char ping_message[128]; /* the length of the ping message (may not exceed 125) */ size_t ping_message_len; /* the numeric ping message suffix to detect ping messages, which are too old */ int ping_counter; }; /** * A single message, which has been send via the chat. * This can be text, an image or a command. */ struct Message { /* The user id of the sender. This is 0 if it is a system message- */ size_t from_user_id; /* The user id of the recipient. This is 0 if every connected user shall receive it */ size_t to_user_id; /* The data of the message. */ char *data; size_t data_len; /* Specifies whether the data is UTF-8 encoded text (0) or binary data (1) */ int is_binary; }; /* the unique user counter for new users (only accessed by main thread) */ size_t unique_user_id = 0; /* the chat data (users and messages; may be accessed by all threads, but is protected by mutex) */ pthread_mutex_t chat_mutex; struct ConnectedUser **users = NULL; size_t user_count = 0; struct Message **messages = NULL; size_t message_count = 0; /* specifies whether all websockets must close (1) or not (0) */ volatile int disconnect_all = 0; /* a counter for cleaning old messages (each 10 messages we will try to clean the list */ int clean_count = 0; #define CLEANUP_LIMIT 10 /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) abort (); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Sends all data of the given buffer via the TCP/IP socket * * @param fd The TCP/IP socket which is used for sending * @param buf The buffer with the data to send * @param len The length in bytes of the data in the buffer */ static void send_all (struct ConnectedUser *cu, const char *buf, size_t len) { ssize_t ret; size_t off; if (0 != pthread_mutex_lock (&cu->send_mutex)) abort (); for (off = 0; off < len; off += ret) { ret = send (cu->fd, &buf[off], (int) (len - off), 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } if (0 != pthread_mutex_unlock (&cu->send_mutex)) abort (); } /** * Adds a new chat message to the list of messages. * * @param from_user_id the user id of the sender (0 means system) * @param to_user_id the user id of the recipiend (0 means everyone) * @param data the data to send (UTF-8 text or binary; will be copied) * @param data_len the length of the data to send * @param is_binary specifies whether the data is UTF-8 text (0) or binary (1) * @param needs_lock specifies whether the caller has already locked the global chat mutex (0) or * if this procedure needs to lock it (1) * * @return 0 on success, other values on error */ static int chat_addmessage (size_t from_user_id, size_t to_user_id, char *data, size_t data_len, int is_binary, int needs_lock) { /* allocate the buffer and fill it with data */ struct Message *message = (struct Message *) malloc (sizeof (struct Message)); if (NULL == message) return 1; memset (message, 0, sizeof (struct Message)); message->from_user_id = from_user_id; message->to_user_id = to_user_id; message->is_binary = is_binary; message->data_len = data_len; message->data = malloc (data_len + 1); if (NULL == message->data) { free (message); return 1; } memcpy (message->data, data, data_len); message->data[data_len] = 0; /* lock the global mutex if needed */ if (0 != needs_lock) { if (0 != pthread_mutex_lock (&chat_mutex)) abort (); } /* add the new message to the global message list */ size_t message_count_ = message_count + 1; struct Message **messages_ = (struct Message **) realloc (messages, message_count_ * sizeof (struct Message *)); if (NULL == messages_) { free (message); if (0 != needs_lock) if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 1; } messages_[message_count] = message; messages = messages_; message_count = message_count_; /* inform the sender threads about the new message */ for (size_t i = 0; i < user_count; ++i) pthread_cond_signal (&users[i]->wake_up_sender); /* unlock the global mutex if needed */ if (0 != needs_lock) { if (0 != needs_lock) if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); } return 0; } /** * Cleans up old messages * * @param needs_lock specifies whether the caller has already locked the global chat mutex (0) or * if this procedure needs to lock it (1) * @return 0 on success, other values on error */ static int chat_clearmessages (int needs_lock) { /* lock the global mutex if needed */ if (0 != needs_lock) { if (0 != pthread_mutex_lock (&chat_mutex)) abort (); } /* update the clean counter and check whether we need cleaning */ ++clean_count; if (CLEANUP_LIMIT > clean_count) { /* no cleanup required */ if (0 != needs_lock) { if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); } return 0; } clean_count = 0; /* check whether we got any messages (without them no cleaning is required */ if (0 < message_count) { /* then check whether we got any connected users */ if (0 < user_count) { /* determine the minimum index for the next message of all connected users */ size_t min_message = users[0]->next_message_index; for (size_t i = 1; i < user_count; ++i) { if (min_message > users[i]->next_message_index) min_message = users[i]->next_message_index; } if (0 < min_message) { /* remove all messages with index below min_message and update the message indices of the users */ for (size_t i = 0; i < min_message; ++i) { free (messages[i]->data); free (messages[i]); } for (size_t i = min_message; i < message_count; ++i) messages[i - min_message] = messages[i]; message_count -= min_message; for (size_t i = 0; i < user_count; ++i) users[i]->next_message_index -= min_message; } } else { /* without connected users, simply remove all messages */ for (size_t i = 0; i < message_count; ++i) { free (messages[i]->data); free (messages[i]); } free (messages); messages = NULL; message_count = 0; } } /* unlock the global mutex if needed */ if (0 != needs_lock) { if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); } return 0; } /** * Adds a new chat user to the global user list. * This will be called at the start of connecteduser_receive_messages. * * @param cu The connected user * @return 0 on success, other values on error */ static int chat_adduser (struct ConnectedUser *cu) { /* initialize the notification message of the new user */ char user_index[32]; snprintf (user_index, 32, "%d", (int) cu->user_id); size_t user_index_len = strlen (user_index); size_t data_len = user_index_len + cu->user_name_len + 9; char *data = (char *) malloc (data_len + 1); if (NULL == data) return 1; strcpy (data, "useradd|"); strcat (data, user_index); strcat (data, "|"); strcat (data, cu->user_name); /* lock the mutex */ if (0 != pthread_mutex_lock (&chat_mutex)) abort (); /* inform the other chat users about the new user */ if (0 != chat_addmessage (0, 0, data, data_len, 0, 0)) { free (data); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 1; } free (data); /* add the new user to the list */ size_t user_count_ = user_count + 1; struct ConnectedUser **users_ = (struct ConnectedUser **) realloc (users, user_count_ * sizeof (struct ConnectedUser *)); if (NULL == users_) { /* realloc failed */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 1; } users_[user_count] = cu; users = users_; user_count = user_count_; /* Initialize the next message index to the current message count. */ /* This will skip all old messages for this new connected user. */ cu->next_message_index = message_count; /* unlock the mutex */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 0; } /** * Removes a chat user from the global user list. * * @param cu The connected user * @return 0 on success, other values on error */ static int chat_removeuser (struct ConnectedUser *cu) { char user_index[32]; /* initialize the chat message for the removed user */ snprintf (user_index, 32, "%d", (int) cu->user_id); size_t user_index_len = strlen (user_index); size_t data_len = user_index_len + 9; char *data = (char *) malloc (data_len + 1); if (NULL == data) return 1; strcpy (data, "userdel|"); strcat (data, user_index); strcat (data, "|"); /* lock the mutex */ if (0 != pthread_mutex_lock (&chat_mutex)) abort (); /* inform the other chat users that the user is gone */ int got_error = 0; if (0 != chat_addmessage (0, 0, data, data_len, 0, 0)) { free (data); got_error = 1; } /* remove the user from the list */ int found = 0; for (size_t i = 0; i < user_count; ++i) { if (cu == users[i]) { found = 1; for (size_t j = i + 1; j < user_count; ++j) { users[j - 1] = users[j]; } --user_count; break; } } if (0 == found) got_error = 1; /* unlock the mutex */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return got_error; } /** * Renames a chat user * * @param cu The connected user * @param new_name The new user name. On success this pointer will be taken. * @param new_name_len The length of the new name * @return 0 on success, other values on error. 2 means name already in use. */ static int chat_renameuser (struct ConnectedUser *cu, char *new_name, size_t new_name_len) { /* lock the mutex */ if (0 != pthread_mutex_lock (&chat_mutex)) abort (); /* check whether the name is already in use */ for (size_t i = 0; i < user_count; ++i) { if (cu != users[i]) { if ((users[i]->user_name_len == new_name_len) && (0 == strcasecmp (users[i]->user_name, new_name))) { if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 2; } } } /* generate the notification message */ char user_index[32]; snprintf (user_index, 32, "%d", (int) cu->user_id); size_t user_index_len = strlen (user_index); size_t data_len = user_index_len + new_name_len + 10; char *data = (char *) malloc (data_len + 1); if (NULL == data) return 1; strcpy (data, "username|"); strcat (data, user_index); strcat (data, "|"); strcat (data, new_name); /* inform the other chat users about the new name */ if (0 != chat_addmessage (0, 0, data, data_len, 0, 0)) { free (data); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 1; } free (data); /* accept the new user name */ free (cu->user_name); cu->user_name = new_name; cu->user_name_len = new_name_len; /* unlock the mutex */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return 0; } /** * Parses received data from the TCP/IP socket with the websocket stream * * @param cu The connected user * @param new_name The new user name * @param new_name_len The length of the new name * @return 0 on success, other values on error */ static int connecteduser_parse_received_websocket_stream (struct ConnectedUser *cu, char *buf, size_t buf_len) { size_t buf_offset = 0; while (buf_offset < buf_len) { size_t new_offset = 0; char *frame_data = NULL; size_t frame_len = 0; int status = MHD_websocket_decode (cu->ws, buf + buf_offset, buf_len - buf_offset, &new_offset, &frame_data, &frame_len); if (0 > status) { /* an error occurred and the connection must be closed */ if (NULL != frame_data) { /* depending on the WebSocket flag */ /* MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR */ /* close frames might be generated on errors */ send_all (cu, frame_data, frame_len); MHD_websocket_free (cu->ws, frame_data); } return 1; } else { buf_offset += new_offset; if (0 < status) { /* the frame is complete */ switch (status) { case MHD_WEBSOCKET_STATUS_TEXT_FRAME: case MHD_WEBSOCKET_STATUS_BINARY_FRAME: /** * a text or binary frame has been received. * in this chat server example we use a simple protocol where * the JavaScript added a prefix like "||data". * Some examples: * "||test" means a regular chat message to everyone with the message "test". * "private|1|secret" means a private chat message to user with id 1 with the message "secret". * "name||MyNewName" means that the user requests a rename to "MyNewName" * "ping|1|" means that the user with id 1 shall get a ping * * Binary data is handled here like text data. * The difference in the data is only checked by the JavaScript. */ { size_t command = 1000; size_t from_user_id = cu->user_id; size_t to_user_id = 0; size_t i; /* parse the command */ for (i = 0; i < frame_len; ++i) { if ('|' == frame_data[i]) { frame_data[i] = 0; ++i; break; } } if (0 < i) { if (i == 1) { /* no command means regular message */ command = 0; } else if (0 == strcasecmp (frame_data, "private")) { /* private means private message */ command = 1; } else if (0 == strcasecmp (frame_data, "name")) { /* name means chat user rename */ command = 2; } else if (0 == strcasecmp (frame_data, "ping")) { /* ping means a ping request */ command = 3; } else { /* no other commands supported, so this means invalid */ command = 1000; } } /* parse the to_user_id, if given */ size_t j = i; for (; j < frame_len; ++j) { if ('|' == frame_data[j]) { frame_data[j] = 0; ++j; break; } } if (i + 1 < j) { to_user_id = (size_t) atoi (frame_data + i); } /* decide via the command what action to do */ if (frame_len >= j) { int is_binary = (MHD_WEBSOCKET_STATUS_BINARY_FRAME == status ? 1 : 0); switch (command) { case 0: /* regular chat message */ { /** * Generate the message for the message list. * Regular chat messages get the command "regular". * After that we add the from_user_id, followed by the content. * The content must always be copied with memcpy instead of strcat, * because the data (binary as well as UTF-8 encoded) is allowed * to contain the NUL character. * However we will add a terminating NUL character, * which is not included in the data length * (and thus will not be send to the recipients). * This is useful for debugging with an IDE. */ char user_index[32]; snprintf (user_index, 32, "%d", (int) cu->user_id); size_t user_index_len = strlen (user_index); size_t data_len = user_index_len + frame_len - j + 9; char *data = (char *) malloc (data_len + 1); if (NULL != data) { strcpy (data, "regular|"); strcat (data, user_index); strcat (data, "|"); size_t offset = strlen (data); memcpy (data + offset, frame_data + j, frame_len - j); data[data_len] = 0; /* add the chat message to the global list */ chat_addmessage (from_user_id, 0, data, data_len, is_binary, 1); free (data); } } break; case 1: /* private chat message */ if (0 != to_user_id) { /** * Generate the message for the message list. * This is similar to the code for regular messages above. * The difference is the prefix "private" */ char user_index[32]; snprintf (user_index, 32, "%d", (int) cu->user_id); size_t user_index_len = strlen (user_index); size_t data_len = user_index_len + frame_len - j + 9; char *data = (char *) malloc (data_len + 1); if (NULL != data) { strcpy (data, "private|"); strcat (data, user_index); strcat (data, "|"); size_t offset = strlen (data); memcpy (data + offset, frame_data + j, frame_len - j); data[data_len] = 0; /* add the chat message to the global list */ chat_addmessage (from_user_id, to_user_id, data, data_len, is_binary, 1); free (data); } } break; case 2: /* rename */ { /* check whether the new name is valid and allocate a new buffer for it */ size_t new_name_len = frame_len - j; if (0 == new_name_len) { chat_addmessage (0, from_user_id, "error||Your new name is invalid. You haven't been renamed.", 58, 0, 1); break; } char *new_name = (char *) malloc (new_name_len + 1); if (NULL == new_name) { chat_addmessage (0, from_user_id, "error||Error while renaming. You haven't been renamed.", 54, 0, 1); break; } new_name[new_name_len] = 0; for (size_t k = 0; k < new_name_len; ++k) { char c = frame_data[j + k]; if ((32 >= c) || (c >= 127)) { free (new_name); new_name = NULL; chat_addmessage (0, from_user_id, "error||Your new name contains invalid characters. You haven't been renamed.", 75, 0, 1); break; } new_name[k] = c; } if (NULL == new_name) break; /* rename the user */ int rename_result = chat_renameuser (cu, new_name, new_name_len); if (0 != rename_result) { /* the buffer will only be freed if no rename was possible */ free (new_name); if (2 == rename_result) { chat_addmessage (0, from_user_id, "error||Your new name is already in use by another user. You haven't been renamed.", 81, 0, 1); } else { chat_addmessage (0, from_user_id, "error||Error while renaming. You haven't been renamed.", 54, 0, 1); } } } break; case 3: /* ping */ { if (0 != pthread_mutex_lock (&chat_mutex)) abort (); /* check whether the to_user exists */ struct ConnectedUser *ping_user = NULL; for (size_t k = 0; k < user_count; ++k) { if (users[k]->user_id == to_user_id) { ping_user = users[k]; break; } } if (NULL == ping_user) { chat_addmessage (0, from_user_id, "error||Couldn't find the specified user for pinging.", 52, 0, 0); } else { /* if pinging is requested, */ /* we mark the user and inform the sender about this */ if (0 == ping_user->ping_status) { ping_user->ping_status = 1; pthread_cond_signal (&ping_user->wake_up_sender); } } if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); } break; default: /* invalid command */ chat_addmessage (0, from_user_id, "error||You sent an invalid command.", 35, 0, 1); break; } } } MHD_websocket_free (cu->ws, frame_data); return 0; case MHD_WEBSOCKET_STATUS_CLOSE_FRAME: /* if we receive a close frame, we will respond with one */ MHD_websocket_free (cu->ws, frame_data); { char *result = NULL; size_t result_len = 0; int er = MHD_websocket_encode_close (cu->ws, MHD_WEBSOCKET_CLOSEREASON_REGULAR, NULL, 0, &result, &result_len); if (MHD_WEBSOCKET_STATUS_OK == er) { send_all (cu, result, result_len); MHD_websocket_free (cu->ws, result); } } return 1; case MHD_WEBSOCKET_STATUS_PING_FRAME: /* if we receive a ping frame, we will respond */ /* with the corresponding pong frame */ { char *pong = NULL; size_t pong_len = 0; int er = MHD_websocket_encode_pong (cu->ws, frame_data, frame_len, &pong, &pong_len); MHD_websocket_free (cu->ws, frame_data); if (MHD_WEBSOCKET_STATUS_OK == er) { send_all (cu, pong, pong_len); MHD_websocket_free (cu->ws, pong); } } return 0; case MHD_WEBSOCKET_STATUS_PONG_FRAME: /* if we receive a pong frame, */ /* we will check whether we requested this frame and */ /* whether it is the last requested pong */ if (2 == cu->ping_status) { cu->ping_status = 0; struct timespec now; timespec_get (&now, TIME_UTC); if ((cu->ping_message_len == frame_len) && (0 == strcmp (frame_data, cu->ping_message))) { int ping = (int) (((int64_t) (now.tv_sec - cu->ping_start.tv_sec)) * 1000 + ((int64_t) (now.tv_nsec - cu->ping_start.tv_nsec)) / 1000000); char result_text[240]; strcpy (result_text, "ping|"); snprintf (result_text + 5, 235, "%d", (int) cu->user_id); strcat (result_text, "|"); snprintf (result_text + strlen (result_text), 240 - strlen (result_text), "%d", (int) ping); chat_addmessage (0, 0, result_text, strlen (result_text), 0, 1); } } MHD_websocket_free (cu->ws, frame_data); return 0; default: /* This case should really never happen, */ /* because there are only five types of (finished) websocket frames. */ /* If it is ever reached, it means that there is memory corruption. */ MHD_websocket_free (cu->ws, frame_data); return 1; } } } } return 0; } /** * Sends messages from the message list over the TCP/IP socket * after encoding it with the websocket stream. * This is also used for server-side actions, * because the thread for receiving messages waits for * incoming data and cannot be woken up. * But the sender thread can be woken up easily. * * @param cls The connected user * @return Always NULL */ static void * connecteduser_send_messages (void *cls) { struct ConnectedUser *cu = cls; /* the main loop of sending messages requires to lock the mutex */ if (0 != pthread_mutex_lock (&chat_mutex)) abort (); for (;;) { /* loop while not all messages processed */ int all_messages_read = 0; while (0 == all_messages_read) { if (1 == disconnect_all) { /* the application closes and want that we disconnect all users */ struct MHD_UpgradeResponseHandle *urh = cu->urh; if (NULL != urh) { /* Close the TCP/IP socket. */ /* This will also wake-up the waiting receive-thread for this connected user. */ cu->urh = NULL; MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return NULL; } else if (1 == cu->disconnect) { /* The sender thread shall close. */ /* This is only requested by the receive thread, so we can just leave. */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); return NULL; } else if (1 == cu->ping_status) { /* A pending ping is requested */ ++cu->ping_counter; strcpy (cu->ping_message, "libmicrohttpdchatserverpingdata"); snprintf (cu->ping_message + 31, 97, "%d", (int) cu->ping_counter); cu->ping_message_len = strlen (cu->ping_message); char *frame_data = NULL; size_t frame_len = 0; int er = MHD_websocket_encode_ping (cu->ws, cu->ping_message, cu->ping_message_len, &frame_data, &frame_len); if (MHD_WEBSOCKET_STATUS_OK == er) { cu->ping_status = 2; timespec_get (&cu->ping_start, TIME_UTC); /* send the data via the TCP/IP socket and */ /* unlock the mutex while sending */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); send_all (cu, frame_data, frame_len); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); } MHD_websocket_free (cu->ws, frame_data); } else if (cu->next_message_index < message_count) { /* a chat message or command is pending */ char *frame_data = NULL; size_t frame_len = 0; int er = 0; { struct Message *msg = messages[cu->next_message_index]; if ((0 == msg->to_user_id) || (cu->user_id == msg->to_user_id) || (cu->user_id == msg->from_user_id) ) { if (0 == msg->is_binary) { er = MHD_websocket_encode_text (cu->ws, msg->data, msg->data_len, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame_data, &frame_len, NULL); } else { er = MHD_websocket_encode_binary (cu->ws, msg->data, msg->data_len, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame_data, &frame_len); } } } ++cu->next_message_index; /* send the data via the TCP/IP socket and */ /* unlock the mutex while sending */ if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); if (MHD_WEBSOCKET_STATUS_OK == er) { send_all (cu, frame_data, frame_len); } MHD_websocket_free (cu->ws, frame_data); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); /* check whether there are still pending messages */ all_messages_read = (cu->next_message_index < message_count) ? 0 : 1; } else { all_messages_read = 1; } } /* clear old messages */ chat_clearmessages (0); /* Wait for wake up. */ /* This will automatically unlock the mutex while waiting and */ /* lock the mutex after waiting */ pthread_cond_wait (&cu->wake_up_sender, &chat_mutex); } return NULL; } /** * Receives messages from the TCP/IP socket and * initializes the connected user. * * @param cls The connected user * @return Always NULL */ static void * connecteduser_receive_messages (void *cls) { struct ConnectedUser *cu = cls; char buf[128]; ssize_t got; int result; /* make the socket blocking */ make_blocking (cu->fd); /* generate the user name */ { char user_name[32]; strcpy (user_name, "User"); snprintf (user_name + 4, 28, "%d", (int) cu->user_id); cu->user_name_len = strlen (user_name); cu->user_name = malloc (cu->user_name_len + 1); if (NULL == cu->user_name) { free (cu->extra_in); free (cu); MHD_upgrade_action (cu->urh, MHD_UPGRADE_ACTION_CLOSE); return NULL; } strcpy (cu->user_name, user_name); } /* initialize the wake-up-sender condition variable */ if (0 != pthread_cond_init (&cu->wake_up_sender, NULL)) { MHD_upgrade_action (cu->urh, MHD_UPGRADE_ACTION_CLOSE); free (cu->user_name); free (cu->extra_in); free (cu); return NULL; } /* initialize the send mutex */ if (0 != pthread_mutex_init (&cu->send_mutex, NULL)) { MHD_upgrade_action (cu->urh, MHD_UPGRADE_ACTION_CLOSE); pthread_cond_destroy (&cu->wake_up_sender); free (cu->user_name); free (cu->extra_in); free (cu); return NULL; } /* add the user to the chat user list */ chat_adduser (cu); /* initialize the web socket stream for encoding/decoding */ result = MHD_websocket_stream_init (&cu->ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0); if (MHD_WEBSOCKET_STATUS_OK != result) { chat_removeuser (cu); pthread_cond_destroy (&cu->wake_up_sender); pthread_mutex_destroy (&cu->send_mutex); MHD_upgrade_action (cu->urh, MHD_UPGRADE_ACTION_CLOSE); free (cu->user_name); free (cu->extra_in); free (cu); return NULL; } /* send a list of all currently connected users (bypassing the messaging system) */ { struct UserInit { char *user_init; size_t user_init_len; }; struct UserInit *init_users = NULL; size_t init_users_len = 0; /* first collect all users without sending (so the mutex isn't locked too long) */ if (0 != pthread_mutex_lock (&chat_mutex)) abort (); if (0 < user_count) { init_users = (struct UserInit *) malloc (user_count * sizeof (struct UserInit)); if (NULL != init_users) { init_users_len = user_count; for (size_t i = 0; i < user_count; ++i) { char user_index[32]; snprintf (user_index, 32, "%d", (int) users[i]->user_id); size_t user_index_len = strlen (user_index); struct UserInit iu; iu.user_init_len = user_index_len + users[i]->user_name_len + 10; iu.user_init = (char *) malloc (iu.user_init_len + 1); if (NULL != iu.user_init) { strcpy (iu.user_init, "userinit|"); strcat (iu.user_init, user_index); strcat (iu.user_init, "|"); if (0 < users[i]->user_name_len) strcat (iu.user_init, users[i]->user_name); } init_users[i] = iu; } } } if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); /* then send all users to the connected client */ for (size_t i = 0; i < init_users_len; ++i) { char *frame_data = NULL; size_t frame_len = 0; if ((0 < init_users[i].user_init_len) && (NULL != init_users[i].user_init) ) { int status = MHD_websocket_encode_text (cu->ws, init_users[i].user_init, init_users[i].user_init_len, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame_data, &frame_len, NULL); if (MHD_WEBSOCKET_STATUS_OK == status) { send_all (cu, frame_data, frame_len); MHD_websocket_free (cu->ws, frame_data); } free (init_users[i].user_init); } } free (init_users); } /* send the welcome message to the user (bypassing the messaging system) */ { char *frame_data = NULL; size_t frame_len = 0; const char *welcome_msg = "moderator||" \ "Welcome to the libmicrohttpd WebSocket chatserver example.\n" \ "Supported commands are:\n" \ " /m - sends a private message to the specified user\n" \ " /ping - sends a ping to the specified user\n" \ " /name - changes your name to the specified name\n" \ " /disconnect - disconnects your websocket\n\n" \ "All messages, which does not start with a slash, " \ "are regular messages and will be sent to the selected user.\n\n" \ "Have fun!"; MHD_websocket_encode_text (cu->ws, welcome_msg, strlen (welcome_msg), MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame_data, &frame_len, NULL); send_all (cu, frame_data, frame_len); MHD_websocket_free (cu->ws, frame_data); } /* start the message-send thread */ pthread_t pt; if (0 != pthread_create (&pt, NULL, &connecteduser_send_messages, cu)) abort (); /* start by parsing extra data MHD may have already read, if any */ if (0 != cu->extra_in_size) { if (0 != connecteduser_parse_received_websocket_stream (cu, cu->extra_in, cu->extra_in_size)) { chat_removeuser (cu); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); cu->disconnect = 1; pthread_cond_signal (&cu->wake_up_sender); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); pthread_join (pt, NULL); struct MHD_UpgradeResponseHandle *urh = cu->urh; if (NULL != urh) { cu->urh = NULL; MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } pthread_cond_destroy (&cu->wake_up_sender); pthread_mutex_destroy (&cu->send_mutex); MHD_websocket_stream_free (cu->ws); free (cu->user_name); free (cu->extra_in); free (cu); return NULL; } free (cu->extra_in); cu->extra_in = NULL; } /* the main loop for receiving data */ while (1) { got = recv (cu->fd, buf, sizeof (buf), 0); if (0 >= got) { /* the TCP/IP socket has been closed */ break; } if (0 < got) { if (0 != connecteduser_parse_received_websocket_stream (cu, buf, (size_t) got)) { /* A websocket protocol error occurred */ chat_removeuser (cu); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); cu->disconnect = 1; pthread_cond_signal (&cu->wake_up_sender); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); pthread_join (pt, NULL); struct MHD_UpgradeResponseHandle *urh = cu->urh; if (NULL != urh) { cu->urh = NULL; MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } pthread_cond_destroy (&cu->wake_up_sender); pthread_mutex_destroy (&cu->send_mutex); MHD_websocket_stream_free (cu->ws); free (cu->user_name); free (cu); return NULL; } } } /* cleanup */ chat_removeuser (cu); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); cu->disconnect = 1; pthread_cond_signal (&cu->wake_up_sender); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); pthread_join (pt, NULL); struct MHD_UpgradeResponseHandle *urh = cu->urh; if (NULL != urh) { cu->urh = NULL; MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } pthread_cond_destroy (&cu->wake_up_sender); pthread_mutex_destroy (&cu->send_mutex); MHD_websocket_stream_free (cu->ws); free (cu->user_name); free (cu); return NULL; } /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { struct ConnectedUser *cu; pthread_t pt; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ /* This callback must return as soon as possible. */ /* allocate new connected user */ cu = malloc (sizeof (struct ConnectedUser)); if (NULL == cu) abort (); memset (cu, 0, sizeof (struct ConnectedUser)); if (0 != extra_in_size) { cu->extra_in = malloc (extra_in_size); if (NULL == cu->extra_in) abort (); memcpy (cu->extra_in, extra_in, extra_in_size); } cu->extra_in_size = extra_in_size; cu->fd = fd; cu->urh = urh; cu->user_id = ++unique_user_id; cu->user_name = NULL; cu->user_name_len = 0; /* create thread for the new connected user */ if (0 != pthread_create (&pt, NULL, &connecteduser_receive_messages, cu)) abort (); pthread_detach (pt); } /** * Function called by the MHD_daemon when the client tries to access a page. * * This is used to provide the main page * (in this example HTML + CSS + JavaScript is all in the same file) * and to initialize a websocket connection. * The rules for the initialization of a websocket connection * are listed near the URL check of "/ChatServerWebSocket". * * @param cls closure, whatever was given to #MHD_start_daemon(). * @param connection The HTTP connection handle * @param url The requested URL * @param method The request method (typically "GET") * @param version The HTTP version * @param upload_data Given upload data for POST requests * @param upload_data_size The size of the upload data * @param req_cls A pointer for request specific data * @return MHD_YES on success or MHD_NO on error. */ static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; int ret; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ if (0 == strcmp (url, "/")) { /* Default page for visiting the server */ struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else if (0 == strcmp (url, "/ChatServerWebSocket")) { /** * The path for the chat has been accessed. * For a valid WebSocket request, at least five headers are required: * 1. "Host: " * 2. "Connection: Upgrade" * 3. "Upgrade: websocket" * 4. "Sec-WebSocket-Version: 13" * 5. "Sec-WebSocket-Key: " * Values are compared in a case-insensitive manner. * Furthermore it must be a HTTP/1.1 or higher GET request. * See: https://tools.ietf.org/html/rfc6455#section-4.2.1 * * To make this example portable we skip the Host check */ char is_valid = 1; const char *value = NULL; char sec_websocket_accept[29]; /* check whether an websocket upgrade is requested */ if (0 != MHD_websocket_check_http_version (version)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (0 != MHD_websocket_check_connection_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE); if (0 != MHD_websocket_check_upgrade_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION); if (0 != MHD_websocket_check_version_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY); if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept)) { is_valid = 0; } if (1 == is_valid) { /* create the response for upgrade */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); /** * For the response we need at least the following headers: * 1. "Connection: Upgrade" * 2. "Upgrade: websocket" * 3. "Sec-WebSocket-Accept: " * The value for Sec-WebSocket-Accept can be generated with MHD_websocket_create_accept_header. * It requires the value of the Sec-WebSocket-Key header of the request. * See also: https://tools.ietf.org/html/rfc6455#section-4.2.2 */ MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "websocket"); MHD_add_response_header (response, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT, sec_websocket_accept); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); } else { /* return error page */ struct MHD_Response *response; response = MHD_create_response_from_buffer_static ( \ strlen (PAGE_INVALID_WEBSOCKET_REQUEST), PAGE_INVALID_WEBSOCKET_REQUEST); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); } } else { struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (PAGE_NOT_FOUND), PAGE_NOT_FOUND); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } return ret; } /** * The main routine for this example * * This starts the daemon and waits for a key hit. * After this it will shutdown the daemon. */ int main (int argc, char *const *argv) { (void) argc; /* Unused. Silent compiler warning. */ (void) argv; /* Unused. Silent compiler warning. */ struct MHD_Daemon *d; if (0 != pthread_mutex_init (&chat_mutex, NULL)) return 1; #if USE_HTTPS == 1 const char private_key[] = "TODO: Enter your key in PEM format here"; const char certificate[] = "TODO: Enter your certificate in PEM format here"; d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, 443, NULL, NULL, &access_handler, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_HTTPS_MEM_KEY, private_key, MHD_OPTION_HTTPS_MEM_CERT, certificate, MHD_OPTION_END); #else d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 80, NULL, NULL, &access_handler, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); #endif if (NULL == d) return 1; (void) getc (stdin); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); disconnect_all = 1; for (size_t i = 0; i < user_count; ++i) pthread_cond_signal (&users[i]->wake_up_sender); if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); sleep (2); if (0 != pthread_mutex_lock (&chat_mutex)) abort (); for (size_t i = 0; i < user_count; ++i) { struct MHD_UpgradeResponseHandle *urh = users[i]->urh; if (NULL != urh) { users[i]->urh = NULL; MHD_upgrade_action (users[i]->urh, MHD_UPGRADE_ACTION_CLOSE); } } if (0 != pthread_mutex_unlock (&chat_mutex)) abort (); sleep (2); /* usually we should wait here in a safe way for all threads to disconnect, */ /* but we skip this in the example */ pthread_mutex_destroy (&chat_mutex); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/upgrade_example.c0000644000175000017500000002237614760713574017242 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file upgrade_example.c * @brief example for how to use libmicrohttpd upgrade * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * * Telnet to the HTTP server, use this in the request: * GET / http/1.1 * Connection: Upgrade * * After this, whatever you type will be echo'ed back to you. */ #include "platform.h" #include #include #include #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) abort (); #endif /* MHD_WINSOCK_SOCKETS */ } static void send_all (MHD_socket sock, const char *buf, size_t len) { ssize_t ret; size_t off; make_blocking (sock); for (off = 0; off < len; off += (size_t) ret) { ret = send (sock, &buf[off], #if ! defined(_WIN32) || defined(__CYGWIN__) len - off, #else /* Native W32 */ (int) (len - off), #endif /* Native W32 */ 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } } struct MyData { struct MHD_UpgradeResponseHandle *urh; char *extra_in; size_t extra_in_size; MHD_socket sock; }; /** * Main function for the thread that runs the interaction with * the upgraded socket. Writes what it reads. * * @param cls the `struct MyData` */ static void * run_usock (void *cls) { struct MyData *md = cls; struct MHD_UpgradeResponseHandle *urh = md->urh; char buf[128]; ssize_t got; make_blocking (md->sock); /* start by sending extra data MHD may have already read, if any */ if (0 != md->extra_in_size) { send_all (md->sock, md->extra_in, md->extra_in_size); free (md->extra_in); } /* now echo in a loop */ while (1) { got = recv (md->sock, buf, sizeof (buf), 0); if (0 >= got) break; send_all (md->sock, buf, (size_t) got); } free (md); MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return NULL; } /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ static void uh_cb (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { struct MyData *md; pthread_t pt; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ md = malloc (sizeof (struct MyData)); if (NULL == md) abort (); memset (md, 0, sizeof (struct MyData)); if (0 != extra_in_size) { md->extra_in = malloc (extra_in_size); if (NULL == md->extra_in) abort (); memcpy (md->extra_in, extra_in, extra_in_size); } md->extra_in_size = extra_in_size; md->sock = sock; md->urh = urh; if (0 != pthread_create (&pt, NULL, &run_usock, md)) abort (); /* Note that by detaching like this we make it impossible to ensure a clean shutdown, as the we stop the daemon even if a worker thread is still running. Alas, this is a simple example... */ pthread_detach (pt); /* This callback must return as soon as possible. */ /* Data forwarding to "upgraded" socket will be started * after return from this callback. */ } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_for_upgrade (&uh_cb, NULL); MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "Echo Server"); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/fileserver_example.c0000644000175000017500000001042714760713574017753 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example.c * @brief minimal example for how to use libmicrohttpd to serve files * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_SYS_STAT_H #include #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_FCNTL_H #include #endif /* HAVE_FCNTL_H */ #define PAGE \ "File not foundFile not found" #ifndef S_ISREG #define S_ISREG(x) (S_IFREG == (x & S_IFREG)) #endif /* S_ISREG */ static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) ) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* WARNING: direct usage of url as filename is for example only! * NEVER pass received data directly as parameter to file manipulation * functions. Always check validity of data before using. */ if (NULL != strstr (url, "../")) /* Very simplified check! */ fd = -1; /* Do not allow usage of parent directories. */ else fd = open (url + 1, O_RDONLY); if (-1 != fd) { if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ if (0 != close (fd)) abort (); fd = -1; } } if (-1 == fd) { response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_fd64 ((uint64_t) buf.st_size, fd); if (NULL == response) { if (0 != close (fd)) abort (); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/benchmark.c0000644000175000017500000001313014760713574016016 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file benchmark.c * @brief minimal code to benchmark MHD GET performance * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define SMALL (1024 * 128) /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT static unsigned int small_deltas[SMALL]; static struct MHD_Response *response; /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback * @param toe reason for request termination * @see MHD_OPTION_NOTIFY_COMPLETED */ static void completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct timeval *tv = *req_cls; struct timeval tve; uint64_t delta; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == tv) return; gettimeofday (&tve, NULL); delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec; if (delta < SMALL) small_deltas[delta]++; else fprintf (stdout, "D: %" PRIu64 " 1\n", delta); free (tv); } static void * uri_logger_cb (void *cls, const char *uri) { struct timeval *tv = malloc (sizeof (struct timeval)); (void) cls; /* Unused. Silent compiler warning. */ (void) uri; /* Unused. Silent compiler warning. */ if (NULL != tv) gettimeofday (tv, NULL); return tv; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ return MHD_queue_response (connection, MHD_HTTP_OK, response); } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int i; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); #if 0 (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SUPPRESS_DATE_NO_CLOCK #ifdef EPOLL_SUPPORT | MHD_USE_EPOLL | MHD_USE_TURBO #endif , (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL, MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (response); for (i = 0; i < SMALL; i++) if (0 != small_deltas[i]) fprintf (stdout, "D: %u %u\n", i, small_deltas[i]); return 0; } libmicrohttpd-1.0.2/src/examples/suspend_resume_epoll.c0000644000175000017500000001310514760713574020322 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2018 Christian Grothoff (and other contributing authors) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file suspend_resume_epoll.c * @brief example for how to use libmicrohttpd with epoll() and * resume a suspended connection * @author Robert D Kocisko * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #define TIMEOUT_INFINITE -1 struct Request { struct MHD_Connection *connection; int timerfd; }; static int epfd; static struct epoll_event evt; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; struct Request *req; struct itimerspec ts; (void) cls; (void) method; (void) version; /* Unused. Silence compiler warning. */ (void) upload_data; /* Unused. Silence compiler warning. */ (void) upload_data_size; /* Unused. Silence compiler warning. */ req = *req_cls; if (NULL == req) { req = malloc (sizeof(struct Request)); if (NULL == req) return MHD_NO; req->connection = connection; req->timerfd = -1; *req_cls = req; return MHD_YES; } if (-1 != req->timerfd) { /* send response (echo request url) */ response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /* create timer and suspend connection */ req->timerfd = timerfd_create (CLOCK_MONOTONIC, TFD_NONBLOCK); if (-1 == req->timerfd) { printf ("timerfd_create: %s", strerror (errno)); return MHD_NO; } evt.events = EPOLLIN; evt.data.ptr = req; if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, req->timerfd, &evt)) { printf ("epoll_ctl: %s", strerror (errno)); return MHD_NO; } ts.it_value.tv_sec = 1; ts.it_value.tv_nsec = 0; ts.it_interval.tv_sec = 0; ts.it_interval.tv_nsec = 0; if (-1 == timerfd_settime (req->timerfd, 0, &ts, NULL)) { printf ("timerfd_settime: %s", strerror (errno)); return MHD_NO; } MHD_suspend_connection (connection); return MHD_YES; } static void connection_done (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *req = *req_cls; (void) cls; (void) connection; (void) toe; if (-1 != req->timerfd) if (0 != close (req->timerfd)) abort (); free (req); } int main (int argc, char *const *argv) { struct MHD_Daemon *d; const union MHD_DaemonInfo *info; int current_event_count; struct epoll_event events_list[1]; struct Request *req; uint64_t timer_expirations; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_EPOLL | MHD_ALLOW_SUSPEND_RESUME, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &connection_done, NULL, MHD_OPTION_END); if (d == NULL) return 1; info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_EPOLL_FD); if (info == NULL) return 1; epfd = epoll_create1 (EPOLL_CLOEXEC); if (-1 == epfd) return 1; evt.events = EPOLLIN; evt.data.ptr = NULL; if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, info->epoll_fd, &evt)) return 1; while (1) { current_event_count = epoll_wait (epfd, events_list, 1, MHD_get_timeout_i (d)); if (1 == current_event_count) { if (events_list[0].data.ptr) { /* A timer has timed out */ req = events_list[0].data.ptr; /* read from the fd so the system knows we heard the notice */ if (-1 == read (req->timerfd, &timer_expirations, sizeof(timer_expirations))) { return 1; } /* Now resume the connection */ MHD_resume_connection (req->connection); } } else if (0 == current_event_count) { /* no events: continue */ } else { /* error */ return 1; } if (! MHD_run (d)) return 1; } return 0; } libmicrohttpd-1.0.2/src/examples/querystring_example.c0000644000175000017500000000756514760713574020212 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file querystring_example.c * @brief example for how to get the query string from libmicrohttpd * Call with an URI ending with something like "?q=QUERY" * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demoQuery string for "%s" was "%s"" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; const char *val; char *me; struct MHD_Response *response; enum MHD_Result ret; int resp_len; size_t buf_size; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "q"); if (NULL == val) return MHD_NO; /* No "q" argument was found */ resp_len = snprintf (NULL, 0, PAGE, "q", val); if (0 >= resp_len) return MHD_NO; /* Error calculating response size */ buf_size = (size_t) resp_len + 1; /* Add one byte for zero-termination */ me = malloc (buf_size); if (me == NULL) return MHD_NO; /* Error allocating memory */ if (resp_len != snprintf (me, buf_size, PAGE, "q", val)) { free (me); return MHD_NO; /* Error forming the response body */ } response = MHD_create_response_from_buffer_with_free_callback (buf_size - 1, (void *) me, &free); if (response == NULL) { free (me); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (port < 0) || (port > UINT16_MAX) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/digest_auth_example.c0000644000175000017500000001401214760713574020077 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digest_auth_example.c * @brief minimal example for how to use digest auth with libmicrohttpd * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #if defined(_WIN32) && ! defined(__CYGWIN__) # include #endif /* _WIN32 && ! __CYGWIN__ */ #define PAGE \ "libmicrohttpd demo" \ "Access granted" #define DENIED \ "libmicrohttpd demo" \ "Access denied" #define MY_OPAQUE_STR "11733b200778ce33060f31c9af70a870ba96ddd4" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; /* Only one user has access to the page */ static const char *username = "testuser"; static const char *password = "testpass"; static const char *realm = "test@example.com"; enum MHD_DigestAuthResult res_e; enum MHD_Result ret; static int already_called_marker; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } /* No need to call MHD_digest_auth_get_username3() as the only * one user has an access. The username match is checked by * MHD_digest_auth_check3() function. */ res_e = MHD_digest_auth_check3 ( connection, realm, username, password, 0, 0, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION); if (res_e != MHD_DAUTH_OK) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_required_response3 ( connection, realm, MY_OPAQUE_STR, NULL, response, (res_e == MHD_DAUTH_NONCE_STALE) ? MHD_YES : MHD_NO, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION, MHD_NO, MHD_YES); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { char rnd[8]; struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } if (1) { #if ! defined(_WIN32) || defined(__CYGWIN__) int fd; ssize_t len; size_t off; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } for (off = 0; off < sizeof(rnd); off += (size_t) len) { len = read (fd, rnd, 8); if (0 > len) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } } (void) close (fd); #else /* Native W32 */ HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (FALSE == b) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", (unsigned long) GetLastError ()); return 1; } b = CryptGenRandom (cc, sizeof(rnd), (BYTE *) rnd); if (FALSE == b) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (FALSE == b) return 1; #endif /* Native W32 */ } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* end of digest_auth_example.c */ libmicrohttpd-1.0.2/src/examples/authorization_example.c0000644000175000017500000001076414760713574020511 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file authorization_example.c * @brief example for how to use libmicrohttpd with HTTP authentication * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define DENIED \ "Access deniedAccess denied" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_BasicAuthInfo *auth_info; int fail; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* require: "Aladdin" with password "open sesame" */ auth_info = MHD_basic_auth_get_username_password3 (connection); fail = ( (NULL == auth_info) || (strlen ("Aladdin") != auth_info->username_len) || (0 != memcmp (auth_info->username, "Aladdin", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("open sesame") != auth_info->password_len) || (0 != memcmp (auth_info->password, "open sesame", auth_info->password_len)) ); if (fail) { response = MHD_create_response_from_buffer_static (strlen (DENIED), (const void *) DENIED); ret = MHD_queue_basic_auth_required_response3 (connection, "TestRealm", MHD_NO, response); } else { response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/minimal_example_comet.c0000644000175000017500000000645214760713574020425 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to generate an infinite stream with libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static ssize_t data_generator (void *cls, uint64_t pos, char *buf, size_t max) { (void) cls; /* Unused. Silent compiler warning. */ (void) pos; /* Unused. Silent compiler warning. */ if (max < 80) return 0; memset (buf, 'A', max - 1); buf[79] = '\n'; return 80; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 80, &data_generator, NULL, NULL); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/chunked_example.c0000644000175000017500000001356214760713574017231 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file chunked_example.c * @brief example for generating chunked encoding with libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include struct ResponseContentCallbackParam { const char *response_data; size_t response_size; }; static ssize_t callback (void *cls, uint64_t pos, char *buf, size_t buf_size) { size_t size_to_copy; struct ResponseContentCallbackParam *const param = (struct ResponseContentCallbackParam *) cls; /* Note: 'pos' will never exceed size of transmitted data. */ /* You can use 'pos == param->response_size' in next check. */ if (pos >= param->response_size) { /* Whole response was sent. Signal end of response. */ return MHD_CONTENT_READER_END_OF_STREAM; } /* Pseudo code. * if (data_not_ready) { // Callback will be called again on next loop. // Consider suspending connection until data will be ready. return 0; } * End of pseudo code. */ if (buf_size < (param->response_size - pos)) size_to_copy = buf_size; else size_to_copy = (size_t) (param->response_size - pos); memcpy (buf, param->response_data + pos, size_to_copy); /* Pseudo code. * if (error_preparing_response) { // Close connection with error. return MHD_CONTENT_READER_END_WITH_ERROR; } * End of pseudo code. */ /* Return amount of data copied to buffer. */ /* The 'buf_size' is always smaller than SSIZE_MAX therefore it's safe * to cast 'size_to_copy' to 'ssize_t'. */ /* assert (size_to_copy <= buf_size); */ return (ssize_t) size_to_copy; } static void free_callback_param (void *cls) { free (cls); } static const char simple_response_text[] = "Simple response" "Simple response text"; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct ResponseContentCallbackParam *callback_param; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } callback_param = malloc (sizeof(struct ResponseContentCallbackParam)); if (NULL == callback_param) return MHD_NO; /* Not enough memory. */ callback_param->response_data = simple_response_text; callback_param->response_size = (sizeof(simple_response_text) / sizeof(char)) - 1; *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &callback, callback_param, &free_callback_param); if (NULL == response) { free (callback_param); return MHD_NO; } /* Enforce chunked response, even for non-keep-alive connection. */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { free (callback_param); MHD_destroy_response (response); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > UINT16_MAX) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/demo.c0000644000175000017500000007111315035214301014771 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file demo.c * @brief complex demonstration site: create directory index, offer * upload via form and HTTP POST, download with mime type detection * and error reporting (403, etc.) --- and all of this with * high-performance settings (large buffers, thread pool). * If you want to benchmark MHD, this code should be used to * run tests against. Note that the number of threads may need * to be adjusted depending on the number of available cores. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifdef MHD_HAVE_LIBMAGIC #include #endif /* MHD_HAVE_LIBMAGIC */ #include #include #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef PATH_MAX /* Some platforms (namely: GNU Hurd) do no define PATH_MAX. As it is only example for MHD, just use reasonable value for PATH_MAX. */ #define PATH_MAX 16384 #endif /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT #ifdef MHD_HAVE_LIBMAGIC /** * How many bytes of a file do we give to libmagic to determine the mime type? * 16k might be a bit excessive, but ought not hurt performance much anyway, * and should definitively be on the safe side. */ #define MAGIC_HEADER_SIZE (16 * 1024) #endif /* MHD_HAVE_LIBMAGIC */ /** * Page returned for file-not-found. */ #define FILE_NOT_FOUND_PAGE \ "File not foundFile not found" /** * Page returned for internal errors. */ #define INTERNAL_ERROR_PAGE \ "Internal errorInternal error" /** * Page returned for refused requests. */ #define REQUEST_REFUSED_PAGE \ "Request refusedRequest refused (file exists?)" /** * Head of index page. */ #define INDEX_PAGE_HEADER \ "\nWelcome\n\n" \ "

Upload

\n" \ "
\n" \ "
Content type:
" \ "Book" \ "Image" \ "Music" \ "Software" \ "Videos\n" \ "Other
" \ "
Language:
" \ "none" \ "English" \ "German" \ "French" \ "Spanish
\n" \ "
File:
" \ "
" \ "\n" \ "
\n" \ "

Download

\n" \ "
    \n" /** * Footer of index page. */ #define INDEX_PAGE_FOOTER "
\n\n" /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const char *const categories[] = { "books", "images", "music", "software", "videos", "other", NULL, }; /** * Specification of a supported language. */ struct Language { /** * Directory name for the language. */ const char *dirname; /** * Long name for humans. */ const char *longname; }; /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const struct Language languages[] = { { "no-lang", "No language specified" }, { "en", "English" }, { "de", "German" }, { "fr", "French" }, { "es", "Spanish" }, { NULL, NULL }, }; /** * Response returned if the requested file does not exist (or is not accessible). */ static struct MHD_Response *file_not_found_response; /** * Response returned for internal errors. */ static struct MHD_Response *internal_error_response; /** * Response returned for '/' (GET) to list the contents of the directory and allow upload. */ static struct MHD_Response *cached_directory_response; /** * Response returned for refused uploads. */ static struct MHD_Response *request_refused_response; /** * Mutex used when we update the cached directory response object. */ static pthread_mutex_t mutex; #ifdef MHD_HAVE_LIBMAGIC /** * Global handle to MAGIC data. */ static magic_t magic; #endif /* MHD_HAVE_LIBMAGIC */ /** * Mark the given response as HTML for the browser. * * @param response response to mark */ static void mark_as_html (struct MHD_Response *response) { (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); } /** * Replace the existing 'cached_directory_response' with the * given response. * * @param response new directory response */ static void update_cached_response (struct MHD_Response *response) { (void) pthread_mutex_lock (&mutex); if (NULL != cached_directory_response) MHD_destroy_response (cached_directory_response); cached_directory_response = response; (void) pthread_mutex_unlock (&mutex); } /** * Context keeping the data for the response we're building. */ struct ResponseDataContext { /** * Response data string. */ char *buf; /** * Number of bytes allocated for 'buf'. */ size_t buf_len; /** * Current position where we append to 'buf'. Must be smaller or equal to 'buf_len'. */ size_t off; }; /** * Create a listing of the files in 'dirname' in HTML. * * @param rdc where to store the list of files * @param dirname name of the directory to list * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result list_directory (struct ResponseDataContext *rdc, const char *dirname) { char fullname[PATH_MAX]; struct stat sbuf; DIR *dir; struct dirent *de; if (NULL == (dir = opendir (dirname))) return MHD_NO; while (NULL != (de = readdir (dir))) { int res; if ('.' == de->d_name[0]) continue; if (sizeof (fullname) <= (unsigned int) snprintf (fullname, sizeof (fullname), "%s/%s", dirname, de->d_name)) continue; /* ugh, file too long? how can this be!? */ if (0 != stat (fullname, &sbuf)) continue; /* ugh, failed to 'stat' */ if (! S_ISREG (sbuf.st_mode)) continue; /* not a regular file, skip */ if (rdc->off + 1024 > rdc->buf_len) { void *r; if ( (2 * rdc->buf_len + 1024) < rdc->buf_len) break; /* more than SIZE_T _index_ size? Too big for us */ rdc->buf_len = 2 * rdc->buf_len + 1024; if (NULL == (r = realloc (rdc->buf, rdc->buf_len))) break; /* out of memory */ rdc->buf = r; } res = snprintf (&rdc->buf[rdc->off], rdc->buf_len - rdc->off, "
  • %s
  • \n", fullname, de->d_name); if (0 >= res) continue; /* snprintf() error */ if (rdc->buf_len - rdc->off <= (size_t) res) continue; /* buffer too small?? */ rdc->off += (size_t) res; } (void) closedir (dir); return MHD_YES; } /** * Re-scan our local directory and re-build the index. */ static void update_directory (void) { static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */ struct MHD_Response *response; struct ResponseDataContext rdc; unsigned int language_idx; unsigned int category_idx; const struct Language *language; const char *category; char dir_name[128]; struct stat sbuf; int res; size_t len; rdc.buf_len = initial_allocation; if (NULL == (rdc.buf = malloc (rdc.buf_len))) { update_cached_response (NULL); return; } len = strlen (INDEX_PAGE_HEADER); if (rdc.buf_len <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (rdc.buf, INDEX_PAGE_HEADER, len); rdc.off = len; for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++) { language = &languages[language_idx]; if (0 != stat (language->dirname, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", language->longname); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; for (category_idx = 0; NULL != categories[category_idx]; category_idx++) { category = categories[category_idx]; res = snprintf (dir_name, sizeof (dir_name), "%s/%s", language->dirname, category); if ((0 >= res) || (sizeof (dir_name) <= (size_t) res)) continue; /* cannot print dir name */ if (0 != stat (dir_name, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", category); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; if (MHD_NO == list_directory (&rdc, dir_name)) { free (rdc.buf); update_cached_response (NULL); return; } } } /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the footer without need for a final reallocation check. */ len = strlen (INDEX_PAGE_FOOTER); if (rdc.buf_len - rdc.off <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (&rdc.buf[rdc.off], INDEX_PAGE_FOOTER, len); rdc.off += len; initial_allocation = rdc.buf_len; /* remember for next time */ response = MHD_create_response_from_buffer_with_free_callback (rdc.off, rdc.buf, &free); mark_as_html (response); #ifdef FORCE_CLOSE (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif update_cached_response (response); } /** * Context we keep for an upload. */ struct UploadContext { /** * Handle where we write the uploaded file to. */ int fd; /** * Name of the file on disk (used to remove on errors). */ char *filename; /** * Language for the upload. */ char *language; /** * Category for the upload. */ char *category; /** * Post processor we're using to process the upload. */ struct MHD_PostProcessor *pp; /** * Handle to connection that we're processing the upload for. */ struct MHD_Connection *connection; /** * Response to generate, NULL to use directory. */ struct MHD_Response *response; }; /** * Append the 'size' bytes from 'data' to '*ret', adding * 0-termination. If '*ret' is NULL, allocate an empty string first. * * @param ret string to update, NULL or 0-terminated * @param data data to append * @param size number of bytes in 'data' * @return #MHD_NO on allocation failure, #MHD_YES on success */ static enum MHD_Result do_append (char **ret, const char *data, size_t size) { char *buf; size_t old_len; if (NULL == *ret) old_len = 0; else old_len = strlen (*ret); if (NULL == (buf = malloc (old_len + size + 1))) return MHD_NO; if (NULL != *ret) { memcpy (buf, *ret, old_len); free (*ret); } memcpy (&buf[old_len], data, size); buf[old_len + size] = '\0'; *ret = buf; return MHD_YES; } /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result process_upload_data (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct UploadContext *uc = cls; size_t i; int res; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 == strcmp (key, "category")) return do_append (&uc->category, data, size); if (0 == strcmp (key, "language")) return do_append (&uc->language, data, size); if (0 != strcmp (key, "upload")) { fprintf (stderr, "Ignoring unexpected form value `%s'\n", key); return MHD_YES; /* ignore */ } if (NULL == filename) { fprintf (stderr, "No filename, aborting upload.\n"); return MHD_NO; /* no filename, error */ } if ( (NULL == uc->category) || (NULL == uc->language) ) { fprintf (stderr, "Missing form data for upload `%s'\n", filename); uc->response = request_refused_response; return MHD_NO; } if (-1 == uc->fd) { char fn[PATH_MAX]; if ( (NULL != strstr (filename, "..")) || (NULL != strchr (filename, '/')) || (NULL != strchr (filename, '\\')) ) { uc->response = request_refused_response; return MHD_NO; } /* create directories -- if they don't exist already */ #ifdef WINDOWS (void) mkdir (uc->language); #else (void) mkdir (uc->language, S_IRWXU); #endif snprintf (fn, sizeof (fn), "%s/%s", uc->language, uc->category); #ifdef WINDOWS (void) mkdir (fn); #else (void) mkdir (fn, S_IRWXU); #endif /* open file */ res = snprintf (fn, sizeof (fn), "%s/%s/%s", uc->language, uc->category, filename); if ((0 >= res) || (sizeof (fn) <= (size_t) res)) { uc->response = request_refused_response; return MHD_NO; } for (i = 0; i < (size_t) res; i++) if (! isprint ((unsigned char) fn[i])) fn[i] = '_'; uc->fd = open (fn, O_CREAT | O_EXCL #ifdef O_LARGEFILE | O_LARGEFILE #endif | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == uc->fd) { fprintf (stderr, "Error opening file `%s' for upload: %s\n", fn, strerror (errno)); uc->response = request_refused_response; return MHD_NO; } uc->filename = strdup (fn); } if ( (0 != size) && #if ! defined(_WIN32) || defined(__CYGWIN__) (size != (size_t) write (uc->fd, data, size)) #else /* Native W32 */ (size != (size_t) write (uc->fd, data, (unsigned int) size)) #endif /* Native W32 */ ) { /* write failed; likely: disk full */ fprintf (stderr, "Error writing to file `%s': %s\n", uc->filename, strerror (errno)); uc->response = internal_error_response; (void) close (uc->fd); uc->fd = -1; if (NULL != uc->filename) { unlink (uc->filename); free (uc->filename); uc->filename = NULL; } return MHD_NO; } return MHD_YES; } /** * Function called whenever a request was completed. * Used to clean up 'struct UploadContext' objects. * * @param cls client-defined closure, NULL * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback, points to NULL if this was * not an upload * @param toe reason for request termination */ static void response_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct UploadContext *uc = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == uc) return; /* this request wasn't an upload request */ if (NULL != uc->pp) { MHD_destroy_post_processor (uc->pp); uc->pp = NULL; } if (-1 != uc->fd) { (void) close (uc->fd); if (NULL != uc->filename) { fprintf (stderr, "Upload of file `%s' failed (incomplete or aborted), removing file.\n", uc->filename); (void) unlink (uc->filename); } } if (NULL != uc->filename) free (uc->filename); free (uc); } /** * Return the current directory listing. * * @param connection connection to return the directory for * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result return_directory_response (struct MHD_Connection *connection) { enum MHD_Result ret; (void) pthread_mutex_lock (&mutex); if (NULL == cached_directory_response) ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, internal_error_response); else ret = MHD_queue_response (connection, MHD_HTTP_OK, cached_directory_response); (void) pthread_mutex_unlock (&mutex); return ret; } /** * Main callback from MHD, used to generate the page. * * @param cls NULL * @param connection connection handle * @param url requested URL * @param method GET, PUT, POST, etc. * @param version HTTP version * @param upload_data data from upload (PUT/POST) * @param upload_data_size number of bytes in @a upload_data * @param req_cls our context * @return #MHD_YES on success, #MHD_NO to drop connection */ static enum MHD_Result generate_page (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (url, "/")) { /* should be file download */ #ifdef MHD_HAVE_LIBMAGIC char file_data[MAGIC_HEADER_SIZE]; ssize_t got; #endif /* MHD_HAVE_LIBMAGIC */ const char *mime; if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) ) return MHD_NO; /* unexpected method (we're not polite...) */ fd = -1; if ( (NULL == strstr (&url[1], "..")) && ('/' != url[1]) ) { fd = open (&url[1], O_RDONLY); if ( (-1 != fd) && ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) ) { (void) close (fd); fd = -1; } } if (-1 == fd) return MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, file_not_found_response); #ifdef MHD_HAVE_LIBMAGIC /* read beginning of the file to determine mime type */ got = read (fd, file_data, sizeof (file_data)); (void) lseek (fd, 0, SEEK_SET); if (0 < got) mime = magic_buffer (magic, file_data, (size_t) got); else #endif /* MHD_HAVE_LIBMAGIC */ mime = NULL; { /* Set mime-type by file-extension in some cases */ const char *ldot = strrchr (&url[1], '.'); if (NULL != ldot) { if (0 == strcasecmp (ldot, ".html")) mime = "text/html"; if (0 == strcasecmp (ldot, ".css")) mime = "text/css"; if (0 == strcasecmp (ldot, ".css3")) mime = "text/css"; if (0 == strcasecmp (ldot, ".js")) mime = "application/javascript"; } } if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size, fd))) { /* internal error (i.e. out of memory) */ (void) close (fd); return MHD_NO; } /* add mime type if we had one */ if (NULL != mime) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* upload! */ struct UploadContext *uc = *req_cls; if (NULL == uc) { if (NULL == (uc = malloc (sizeof (struct UploadContext)))) return MHD_NO; /* out of memory, close connection */ memset (uc, 0, sizeof (struct UploadContext)); uc->fd = -1; uc->connection = connection; uc->pp = MHD_create_post_processor (connection, 64 * 1024 /* buffer size */, &process_upload_data, uc); if (NULL == uc->pp) { /* out of memory, close connection */ free (uc); return MHD_NO; } *req_cls = uc; return MHD_YES; } if (0 != *upload_data_size) { if (NULL == uc->response) (void) MHD_post_process (uc->pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* end of upload, finish it! */ MHD_destroy_post_processor (uc->pp); uc->pp = NULL; if (-1 != uc->fd) { close (uc->fd); uc->fd = -1; } if (NULL != uc->response) { return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, uc->response); } else { update_directory (); return return_directory_response (connection); } } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { return return_directory_response (connection); } /* unexpected request, refuse */ return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, request_refused_response); } #ifndef MINGW /** * Function called if we get a SIGPIPE. Does nothing. * * @param sig will be SIGPIPE (ignored) */ static void catcher (int sig) { (void) sig; /* Unused. Silent compiler warning. */ /* do nothing */ } /** * setup handlers to ignore SIGPIPE. */ static void ignore_sigpipe (void) { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } #endif /** * Entry point to demo. Note: this HTTP server will make all * files in the current directory and its subdirectories available * to anyone. Press ENTER to stop the server once it has started. * * @param argc number of arguments in argv * @param argv first and only argument should be the port number * @return 0 on success */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } #ifndef MINGW ignore_sigpipe (); #endif #ifdef MHD_HAVE_LIBMAGIC magic = magic_open (MAGIC_MIME_TYPE); (void) magic_load (magic, NULL); #endif /* MHD_HAVE_LIBMAGIC */ (void) pthread_mutex_init (&mutex, NULL); file_not_found_response = MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE), (const void *) FILE_NOT_FOUND_PAGE); mark_as_html (file_not_found_response); request_refused_response = MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE), (const void *) REQUEST_REFUSED_PAGE); mark_as_html (request_refused_response); internal_error_response = MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE), (const void *) INTERNAL_ERROR_PAGE); mark_as_html (internal_error_response); update_directory (); d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &generate_page, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024), #ifdef PRODUCTION MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64), #endif MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */) , MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL, MHD_OPTION_END); if (NULL == d) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (file_not_found_response); MHD_destroy_response (request_refused_response); MHD_destroy_response (internal_error_response); update_cached_response (NULL); (void) pthread_mutex_destroy (&mutex); #ifdef MHD_HAVE_LIBMAGIC magic_close (magic); #endif /* MHD_HAVE_LIBMAGIC */ return 0; } /* end of demo.c */ libmicrohttpd-1.0.2/src/examples/fileserver_example_external_select.c0000644000175000017500000001343114760713574023212 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example_external_select.c * @brief minimal example for how to use libmicrohttpd to server files * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #define PAGE \ "File not foundFile not found" static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void free_callback (void *cls) { FILE *file = cls; fclose (file); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; time_t end; time_t t; struct timeval tv; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 3) { printf ("%s PORT SECONDS-TO-RUN\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; end = time (NULL) + atoi (argv[2]); while ((t = time (NULL)) < end) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = end - t; #else /* Native W32 */ tv.tv_sec = (long) (end - t); #endif /* Native W32 */ tv.tv_usec = 0; max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { if (((uint64_t) tv.tv_sec) < mhd_timeout / 1000LL) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; } } if (-1 == select ((int) max + 1, &rs, &ws, &es, &tv)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/http_chunked_compression.c0000644000175000017500000001422614760713574021174 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019 Christian Grothoff (and other contributing authors) Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file http_chunked_compression.c * @brief example for how to compress a chunked HTTP response * @author Silvio Clecio (silvioprog) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #ifndef ZLIB_CONST /* Correct API with const pointer for input data is required */ #define ZLIB_CONST 1 #endif /* ! ZLIB_CONST */ #include #include #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #include #include #ifndef SSIZE_MAX #ifdef __SSIZE_MAX__ #define SSIZE_MAX __SSIZE_MAX__ #elif defined(PTRDIFF_MAX) #define SSIZE_MAX PTRDIFF_MAX #elif defined(INTPTR_MAX) #define SSIZE_MAX INTPTR_MAX #else #define SSIZE_MAX ((ssize_t) (((size_t) -1) >> 1)) #endif #endif /* ! SSIZE_MAX */ #define CHUNK 16384 struct Holder { FILE *file; z_stream stream; void *buf; }; static enum MHD_Result compress_buf (z_stream *strm, const void *src, size_t src_size, size_t *offset, void **dest, size_t *dest_size, void *tmp) { unsigned int have; enum MHD_Result ret; int flush; void *tmp_dest; *dest = NULL; *dest_size = 0; do { if (src_size > CHUNK) { strm->avail_in = CHUNK; src_size -= CHUNK; flush = Z_NO_FLUSH; } else { strm->avail_in = (uInt) src_size; flush = Z_SYNC_FLUSH; } *offset += strm->avail_in; strm->next_in = (const Bytef *) src; do { strm->avail_out = CHUNK; strm->next_out = tmp; ret = (Z_OK == deflate (strm, flush)) ? MHD_YES : MHD_NO; have = CHUNK - strm->avail_out; *dest_size += have; tmp_dest = realloc (*dest, *dest_size); if (NULL == tmp_dest) { free (*dest); *dest = NULL; return MHD_NO; } *dest = tmp_dest; memcpy (((uint8_t *) (*dest)) + ((*dest_size) - have), tmp, have); } while (0 == strm->avail_out); } while (flush != Z_SYNC_FLUSH); return ret; } static ssize_t read_cb (void *cls, uint64_t pos, char *mem, size_t size) { struct Holder *holder = cls; void *src; void *buf; ssize_t ret; size_t offset; size_t r_size; if (pos > SSIZE_MAX) return MHD_CONTENT_READER_END_WITH_ERROR; offset = (size_t) pos; src = malloc (size); if (NULL == src) return MHD_CONTENT_READER_END_WITH_ERROR; r_size = fread (src, 1, size, holder->file); if (0 == r_size) { ret = (0 != ferror (holder->file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; goto done; } if (MHD_YES != compress_buf (&holder->stream, src, r_size, &offset, &buf, &size, holder->buf)) ret = MHD_CONTENT_READER_END_WITH_ERROR; else { memcpy (mem, buf, size); ret = (ssize_t) size; } free (buf); /* Buf may be set even on error return. */ done: free (src); return ret; } static void free_cb (void *cls) { struct Holder *holder = cls; fclose (holder->file); deflateEnd (&holder->stream); free (holder->buf); free (holder); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *con, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_size, void **req_cls) { struct Holder *holder; struct MHD_Response *res; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_size; if (NULL == *req_cls) { *req_cls = (void *) 1; return MHD_YES; } *req_cls = NULL; holder = calloc (1, sizeof (struct Holder)); if (! holder) return MHD_NO; holder->file = fopen (__FILE__, "rb"); if (NULL == holder->file) goto file_error; if (Z_OK != deflateInit (&holder->stream, Z_BEST_COMPRESSION)) goto stream_error; holder->buf = malloc (CHUNK); if (NULL == holder->buf) goto buf_error; res = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &read_cb, holder, &free_cb); if (NULL == res) goto error; ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_ENCODING, "deflate"); if (MHD_YES != ret) goto res_error; ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_TYPE, "text/x-c"); if (MHD_YES != ret) goto res_error; ret = MHD_queue_response (con, MHD_HTTP_OK, res); res_error: MHD_destroy_response (res); return ret; error: free (holder->buf); buf_error: deflateEnd (&holder->stream); stream_error: fclose (holder->file); file_error: free (holder); return MHD_NO; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ((argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port)) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; if (0 == port) MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT, &port); fprintf (stdout, "HTTP server running at http://localhost:%u\n\nPress ENTER to stop the server ...\n", port); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/refuse_post_example.c0000644000175000017500000001013614760713574020140 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file refuse_post_example.c * @brief example for how to refuse a POST request properly * @author Christian Grothoff and Sebastian Gerhardt * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include struct handler_param { const char *response_page; }; static const char *askpage = "\n\ Upload a file, please!
    \n\
    \n\ \n\
    \n\ "; #define BUSYPAGE \ "Webserver busy" \ "We are too busy to process POSTs right now." static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if ((0 != strcmp (method, "GET")) && (0 != strcmp (method, "POST"))) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { *req_cls = &aptr; /* always to busy for POST requests */ if (0 == strcmp (method, "POST")) { response = MHD_create_response_from_buffer_static (strlen (BUSYPAGE), (const void *) BUSYPAGE); ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response); MHD_destroy_response (response); return ret; } } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), (const void *) param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = askpage; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* end of refuse_post_example.c */ libmicrohttpd-1.0.2/src/examples/benchmark_https.c0000644000175000017500000002303114760713574017241 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file benchmark_https.c * @brief minimal code to benchmark MHD GET performance with HTTPS * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define SMALL (1024 * 128) /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT static unsigned int small_deltas[SMALL]; static struct MHD_Response *response; /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback * @param toe reason for request termination * @see MHD_OPTION_NOTIFY_COMPLETED */ static void completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct timeval *tv = *req_cls; struct timeval tve; uint64_t delta; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == tv) return; gettimeofday (&tve, NULL); delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec; if (delta < SMALL) small_deltas[delta]++; else fprintf (stdout, "D: %" PRIu64 " 1\n", delta); free (tv); } static void * uri_logger_cb (void *cls, const char *uri) { struct timeval *tv = malloc (sizeof (struct timeval)); (void) cls; /* Unused. Silent compiler warning. */ (void) uri; /* Unused. Silent compiler warning. */ if (NULL != tv) gettimeofday (tv, NULL); return tv; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ return MHD_queue_response (connection, MHD_HTTP_OK, response); } /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int i; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS #ifdef EPOLL_SUPPORT | MHD_USE_EPOLL | MHD_USE_TURBO #endif , (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL, MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (response); for (i = 0; i < SMALL; i++) if (0 != small_deltas[i]) fprintf (stdout, "D: %u %u\n", i, small_deltas[i]); return 0; } libmicrohttpd-1.0.2/src/examples/minimal_example_empty.c0000644000175000017500000000635314760713574020454 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_NO_CONTENT, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/demo_https.c0000644000175000017500000010031115035214301016204 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file demo_https.c * @brief complex demonstration site: create directory index, offer * upload via form and HTTP POST, download with mime type detection * and error reporting (403, etc.) --- and all of this with * high-performance settings (large buffers, thread pool). * If you want to benchmark MHD, this code should be used to * run tests against. Note that the number of threads may need * to be adjusted depending on the number of available cores. * Logic is identical to demo.c, just adds HTTPS support. * This demonstration uses key/cert stored in static string. Optionally, * use gnutls_load_file() to load them from file. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #ifdef MHD_HAVE_LIBMAGIC #include #endif /* MHD_HAVE_LIBMAGIC */ #include #include #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef PATH_MAX /* Some platforms (namely: GNU Hurd) do no define PATH_MAX. As it is only example for MHD, just use reasonable value for PATH_MAX. */ #define PATH_MAX 16384 #endif /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT #ifdef MHD_HAVE_LIBMAGIC /** * How many bytes of a file do we give to libmagic to determine the mime type? * 16k might be a bit excessive, but ought not hurt performance much anyway, * and should definitively be on the safe side. */ #define MAGIC_HEADER_SIZE (16 * 1024) #endif /* MHD_HAVE_LIBMAGIC */ /** * Page returned for file-not-found. */ #define FILE_NOT_FOUND_PAGE \ "File not foundFile not found" /** * Page returned for internal errors. */ #define INTERNAL_ERROR_PAGE \ "Internal errorInternal error" /** * Page returned for refused requests. */ #define REQUEST_REFUSED_PAGE \ "Request refusedRequest refused (file exists?)" /** * Head of index page. */ #define INDEX_PAGE_HEADER \ "\nWelcome\n\n" \ "

    Upload

    \n" \ "
    \n" \ "
    Content type:
    " \ "Book" \ "Image" \ "Music" \ "Software" \ "Videos\n" \ "Other
    " \ "
    Language:
    " \ "none" \ "English" \ "German" \ "French" \ "Spanish
    \n" \ "
    File:
    " \ "
    " \ "\n" \ "
    \n" \ "

    Download

    \n" \ "
      \n" /** * Footer of index page. */ #define INDEX_PAGE_FOOTER "
    \n\n" /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const char *const categories[] = { "books", "images", "music", "software", "videos", "other", NULL, }; /** * Specification of a supported language. */ struct Language { /** * Directory name for the language. */ const char *dirname; /** * Long name for humans. */ const char *longname; }; /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const struct Language languages[] = { { "no-lang", "No language specified" }, { "en", "English" }, { "de", "German" }, { "fr", "French" }, { "es", "Spanish" }, { NULL, NULL }, }; /** * Response returned if the requested file does not exist (or is not accessible). */ static struct MHD_Response *file_not_found_response; /** * Response returned for internal errors. */ static struct MHD_Response *internal_error_response; /** * Response returned for '/' (GET) to list the contents of the directory and allow upload. */ static struct MHD_Response *cached_directory_response; /** * Response returned for refused uploads. */ static struct MHD_Response *request_refused_response; /** * Mutex used when we update the cached directory response object. */ static pthread_mutex_t mutex; #ifdef MHD_HAVE_LIBMAGIC /** * Global handle to MAGIC data. */ static magic_t magic; #endif /* MHD_HAVE_LIBMAGIC */ /** * Mark the given response as HTML for the browser. * * @param response response to mark */ static void mark_as_html (struct MHD_Response *response) { (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); } /** * Replace the existing 'cached_directory_response' with the * given response. * * @param response new directory response */ static void update_cached_response (struct MHD_Response *response) { (void) pthread_mutex_lock (&mutex); if (NULL != cached_directory_response) MHD_destroy_response (cached_directory_response); cached_directory_response = response; (void) pthread_mutex_unlock (&mutex); } /** * Context keeping the data for the response we're building. */ struct ResponseDataContext { /** * Response data string. */ char *buf; /** * Number of bytes allocated for 'buf'. */ size_t buf_len; /** * Current position where we append to 'buf'. Must be smaller or equal to 'buf_len'. */ size_t off; }; /** * Create a listing of the files in 'dirname' in HTML. * * @param rdc where to store the list of files * @param dirname name of the directory to list * @return MHD_YES on success, MHD_NO on error */ static enum MHD_Result list_directory (struct ResponseDataContext *rdc, const char *dirname) { char fullname[PATH_MAX]; struct stat sbuf; DIR *dir; struct dirent *de; if (NULL == (dir = opendir (dirname))) return MHD_NO; while (NULL != (de = readdir (dir))) { int res; if ('.' == de->d_name[0]) continue; if (sizeof (fullname) <= (size_t) snprintf (fullname, sizeof (fullname), "%s/%s", dirname, de->d_name)) continue; /* ugh, file too long? how can this be!? */ if (0 != stat (fullname, &sbuf)) continue; /* ugh, failed to 'stat' */ if (! S_ISREG (sbuf.st_mode)) continue; /* not a regular file, skip */ if (rdc->off + 1024 > rdc->buf_len) { void *r; if ( (2 * rdc->buf_len + 1024) < rdc->buf_len) break; /* more than SIZE_T _index_ size? Too big for us */ rdc->buf_len = 2 * rdc->buf_len + 1024; if (NULL == (r = realloc (rdc->buf, rdc->buf_len))) break; /* out of memory */ rdc->buf = r; } res = snprintf (&rdc->buf[rdc->off], rdc->buf_len - rdc->off, "
  • %s
  • \n", fullname, de->d_name); if (0 >= res) continue; /* snprintf() error */ if (rdc->buf_len - rdc->off <= (size_t) res) continue; /* buffer too small?? */ rdc->off += (size_t) res; } (void) closedir (dir); return MHD_YES; } /** * Re-scan our local directory and re-build the index. */ static void update_directory (void) { static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */ struct MHD_Response *response; struct ResponseDataContext rdc; unsigned int language_idx; unsigned int category_idx; const struct Language *language; const char *category; char dir_name[128]; struct stat sbuf; int res; size_t len; rdc.buf_len = initial_allocation; if (NULL == (rdc.buf = malloc (rdc.buf_len))) { update_cached_response (NULL); return; } len = strlen (INDEX_PAGE_HEADER); if (rdc.buf_len <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (rdc.buf, INDEX_PAGE_HEADER, len); rdc.off = len; for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++) { language = &languages[language_idx]; if (0 != stat (language->dirname, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", language->longname); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; for (category_idx = 0; NULL != categories[category_idx]; category_idx++) { category = categories[category_idx]; res = snprintf (dir_name, sizeof (dir_name), "%s/%s", language->dirname, category); if ((0 >= res) || (sizeof (dir_name) <= (size_t) res)) continue; /* cannot print dir name */ if (0 != stat (dir_name, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", category); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; if (MHD_NO == list_directory (&rdc, dir_name)) { free (rdc.buf); update_cached_response (NULL); return; } } } /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the footer without need for a final reallocation check. */ len = strlen (INDEX_PAGE_FOOTER); if (rdc.buf_len - rdc.off <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (&rdc.buf[rdc.off], INDEX_PAGE_FOOTER, len); rdc.off += len; initial_allocation = rdc.buf_len; /* remember for next time */ response = MHD_create_response_from_buffer_with_free_callback (rdc.off, rdc.buf, &free); mark_as_html (response); #ifdef FORCE_CLOSE (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif update_cached_response (response); } /** * Context we keep for an upload. */ struct UploadContext { /** * Handle where we write the uploaded file to. */ int fd; /** * Name of the file on disk (used to remove on errors). */ char *filename; /** * Language for the upload. */ char *language; /** * Category for the upload. */ char *category; /** * Post processor we're using to process the upload. */ struct MHD_PostProcessor *pp; /** * Handle to connection that we're processing the upload for. */ struct MHD_Connection *connection; /** * Response to generate, NULL to use directory. */ struct MHD_Response *response; }; /** * Append the 'size' bytes from 'data' to '*ret', adding * 0-termination. If '*ret' is NULL, allocate an empty string first. * * @param ret string to update, NULL or 0-terminated * @param data data to append * @param size number of bytes in 'data' * @return #MHD_NO on allocation failure, #MHD_YES on success */ static enum MHD_Result do_append (char **ret, const char *data, size_t size) { char *buf; size_t old_len; if (NULL == *ret) old_len = 0; else old_len = strlen (*ret); if (NULL == (buf = malloc (old_len + size + 1))) return MHD_NO; if (NULL != *ret) { memcpy (buf, *ret, old_len); free (*ret); } memcpy (&buf[old_len], data, size); buf[old_len + size] = '\0'; *ret = buf; return MHD_YES; } /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result process_upload_data (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct UploadContext *uc = cls; size_t i; int res; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 == strcmp (key, "category")) return do_append (&uc->category, data, size); if (0 == strcmp (key, "language")) return do_append (&uc->language, data, size); if (0 != strcmp (key, "upload")) { fprintf (stderr, "Ignoring unexpected form value `%s'\n", key); return MHD_YES; /* ignore */ } if (NULL == filename) { fprintf (stderr, "No filename, aborting upload.\n"); return MHD_NO; /* no filename, error */ } if ( (NULL == uc->category) || (NULL == uc->language) ) { fprintf (stderr, "Missing form data for upload `%s'\n", filename); uc->response = request_refused_response; return MHD_NO; } if (-1 == uc->fd) { char fn[PATH_MAX]; if ( (NULL != strstr (filename, "..")) || (NULL != strchr (filename, '/')) || (NULL != strchr (filename, '\\')) ) { uc->response = request_refused_response; return MHD_NO; } /* create directories -- if they don't exist already */ #ifdef WINDOWS (void) mkdir (uc->language); #else (void) mkdir (uc->language, S_IRWXU); #endif snprintf (fn, sizeof (fn), "%s/%s", uc->language, uc->category); #ifdef WINDOWS (void) mkdir (fn); #else (void) mkdir (fn, S_IRWXU); #endif /* open file */ res = snprintf (fn, sizeof (fn), "%s/%s/%s", uc->language, uc->category, filename); if ((0 >= res) || (sizeof (fn) <= (size_t) res)) { uc->response = request_refused_response; return MHD_NO; } for (i = 0; i < (size_t) res; i++) if (! isprint ((unsigned char) fn[i])) fn[i] = '_'; uc->fd = open (fn, O_CREAT | O_EXCL #ifdef O_LARGEFILE | O_LARGEFILE #endif | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == uc->fd) { fprintf (stderr, "Error opening file `%s' for upload: %s\n", fn, strerror (errno)); uc->response = request_refused_response; return MHD_NO; } uc->filename = strdup (fn); } if ( (0 != size) && #if ! defined(_WIN32) || defined(__CYGWIN__) (size != (size_t) write (uc->fd, data, size)) #else /* Native W32 */ (size != (size_t) write (uc->fd, data, (unsigned int) size)) #endif /* Native W32 */ ) { /* write failed; likely: disk full */ fprintf (stderr, "Error writing to file `%s': %s\n", uc->filename, strerror (errno)); uc->response = internal_error_response; (void) close (uc->fd); uc->fd = -1; if (NULL != uc->filename) { unlink (uc->filename); free (uc->filename); uc->filename = NULL; } return MHD_NO; } return MHD_YES; } /** * Function called whenever a request was completed. * Used to clean up 'struct UploadContext' objects. * * @param cls client-defined closure, NULL * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback, points to NULL if this was * not an upload * @param toe reason for request termination */ static void response_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct UploadContext *uc = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == uc) return; /* this request wasn't an upload request */ if (NULL != uc->pp) { MHD_destroy_post_processor (uc->pp); uc->pp = NULL; } if (-1 != uc->fd) { (void) close (uc->fd); if (NULL != uc->filename) { fprintf (stderr, "Upload of file `%s' failed (incomplete or aborted), removing file.\n", uc->filename); (void) unlink (uc->filename); } } if (NULL != uc->filename) free (uc->filename); free (uc); } /** * Return the current directory listing. * * @param connection connection to return the directory for * @return MHD_YES on success, MHD_NO on error */ static enum MHD_Result return_directory_response (struct MHD_Connection *connection) { enum MHD_Result ret; (void) pthread_mutex_lock (&mutex); if (NULL == cached_directory_response) ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, internal_error_response); else ret = MHD_queue_response (connection, MHD_HTTP_OK, cached_directory_response); (void) pthread_mutex_unlock (&mutex); return ret; } /** * Main callback from MHD, used to generate the page. * * @param cls NULL * @param connection connection handle * @param url requested URL * @param method GET, PUT, POST, etc. * @param version HTTP version * @param upload_data data from upload (PUT/POST) * @param upload_data_size number of bytes in "upload_data" * @param req_cls our context * @return #MHD_YES on success, #MHD_NO to drop connection */ static enum MHD_Result generate_page (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (url, "/")) { /* should be file download */ #ifdef MHD_HAVE_LIBMAGIC char file_data[MAGIC_HEADER_SIZE]; ssize_t got; #endif /* MHD_HAVE_LIBMAGIC */ const char *mime; if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method (we're not polite...) */ fd = -1; if ( (NULL == strstr (&url[1], "..")) && ('/' != url[1]) ) { fd = open (&url[1], O_RDONLY); if ( (-1 != fd) && ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) ) { (void) close (fd); fd = -1; } } if (-1 == fd) return MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, file_not_found_response); #ifdef MHD_HAVE_LIBMAGIC /* read beginning of the file to determine mime type */ got = read (fd, file_data, sizeof (file_data)); (void) lseek (fd, 0, SEEK_SET); if (0 < got) mime = magic_buffer (magic, file_data, (size_t) got); else #endif /* MHD_HAVE_LIBMAGIC */ mime = NULL; if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size, fd))) { /* internal error (i.e. out of memory) */ (void) close (fd); return MHD_NO; } /* add mime type if we had one */ if (NULL != mime) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* upload! */ struct UploadContext *uc = *req_cls; if (NULL == uc) { if (NULL == (uc = malloc (sizeof (struct UploadContext)))) return MHD_NO; /* out of memory, close connection */ memset (uc, 0, sizeof (struct UploadContext)); uc->fd = -1; uc->connection = connection; uc->pp = MHD_create_post_processor (connection, 64 * 1024 /* buffer size */, &process_upload_data, uc); if (NULL == uc->pp) { /* out of memory, close connection */ free (uc); return MHD_NO; } *req_cls = uc; return MHD_YES; } if (0 != *upload_data_size) { if (NULL == uc->response) (void) MHD_post_process (uc->pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* end of upload, finish it! */ MHD_destroy_post_processor (uc->pp); uc->pp = NULL; if (-1 != uc->fd) { close (uc->fd); uc->fd = -1; } if (NULL != uc->response) { return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, uc->response); } else { update_directory (); return return_directory_response (connection); } } if (0 == strcmp (method, MHD_HTTP_METHOD_GET)) { return return_directory_response (connection); } /* unexpected request, refuse */ return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, request_refused_response); } #ifndef MINGW /** * Function called if we get a SIGPIPE. Does nothing. * * @param sig will be SIGPIPE (ignored) */ static void catcher (int sig) { (void) sig; /* Unused. Silent compiler warning. */ /* do nothing */ } /** * setup handlers to ignore SIGPIPE. */ static void ignore_sigpipe (void) { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } #endif /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; /** * Entry point to demo. Note: this HTTP server will make all * files in the current directory and its subdirectories available * to anyone. Press ENTER to stop the server once it has started. * * @param argc number of arguments in argv * @param argv first and only argument should be the port number * @return 0 on success */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } #ifndef MINGW ignore_sigpipe (); #endif #ifdef MHD_HAVE_LIBMAGIC magic = magic_open (MAGIC_MIME_TYPE); (void) magic_load (magic, NULL); #endif /* MHD_HAVE_LIBMAGIC */ (void) pthread_mutex_init (&mutex, NULL); file_not_found_response = MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE), (const void *) FILE_NOT_FOUND_PAGE); mark_as_html (file_not_found_response); request_refused_response = MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE), (const void *) REQUEST_REFUSED_PAGE); mark_as_html (request_refused_response); internal_error_response = MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE), (const void *) INTERNAL_ERROR_PAGE); mark_as_html (internal_error_response); update_directory (); d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, (uint16_t) port, NULL, NULL, &generate_page, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024), #ifdef PRODUCTION MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64), #endif MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */) , MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (NULL == d) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (file_not_found_response); MHD_destroy_response (request_refused_response); MHD_destroy_response (internal_error_response); update_cached_response (NULL); (void) pthread_mutex_destroy (&mutex); #ifdef MHD_HAVE_LIBMAGIC magic_close (magic); #endif /* MHD_HAVE_LIBMAGIC */ return 0; } /* end of demo_https.c */ libmicrohttpd-1.0.2/src/examples/Makefile.in0000644000175000017500000022022215035216310015745 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage noinst_PROGRAMS = benchmark$(EXEEXT) benchmark_https$(EXEEXT) \ chunked_example$(EXEEXT) minimal_example$(EXEEXT) \ minimal_example_empty$(EXEEXT) dual_stack_example$(EXEEXT) \ minimal_example_comet$(EXEEXT) querystring_example$(EXEEXT) \ timeout$(EXEEXT) fileserver_example$(EXEEXT) \ fileserver_example_dirs$(EXEEXT) \ fileserver_example_external_select$(EXEEXT) \ refuse_post_example$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_2) \ $(am__EXEEXT_3) $(am__EXEEXT_4) $(am__EXEEXT_5) \ $(am__EXEEXT_6) $(am__EXEEXT_7) $(am__EXEEXT_8) \ $(am__EXEEXT_9) $(am__EXEEXT_10) $(am__EXEEXT_11) @HAVE_EXPERIMENTAL_TRUE@am__append_2 = \ @HAVE_EXPERIMENTAL_TRUE@ websocket_chatserver_example @MHD_HAVE_EPOLL_TRUE@am__append_3 = \ @MHD_HAVE_EPOLL_TRUE@ suspend_resume_epoll @HAVE_JANSSON_TRUE@am__append_4 = \ @HAVE_JANSSON_TRUE@ json_echo @ENABLE_HTTPS_TRUE@am__append_5 = \ @ENABLE_HTTPS_TRUE@ https_fileserver_example \ @ENABLE_HTTPS_TRUE@ minimal_example_empty_tls @HAVE_POSTPROCESSOR_TRUE@am__append_6 = \ @HAVE_POSTPROCESSOR_TRUE@ post_example @HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_7 = demo @ENABLE_HTTPS_TRUE@@HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_8 = demo_https @ENABLE_DAUTH_TRUE@am__append_9 = \ @ENABLE_DAUTH_TRUE@ digest_auth_example \ @ENABLE_DAUTH_TRUE@ digest_auth_example_adv @ENABLE_BAUTH_TRUE@am__append_10 = \ @ENABLE_BAUTH_TRUE@ authorization_example @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_11 = \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@ upgrade_example \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@ websocket_threaded_example @HAVE_ZLIB_TRUE@am__append_12 = \ @HAVE_ZLIB_TRUE@ http_compression \ @HAVE_ZLIB_TRUE@ http_chunked_compression @HAVE_W32_TRUE@am__append_13 = -DWINDOWS @MHD_HAVE_LIBMAGIC_TRUE@am__append_14 = -lmagic @MHD_HAVE_LIBMAGIC_TRUE@am__append_15 = -lmagic @HAVE_ZLIB_TRUE@am__append_16 = -lz @HAVE_ZLIB_TRUE@am__append_17 = -lz subdir = src/examples ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @HAVE_EXPERIMENTAL_TRUE@am__EXEEXT_1 = \ @HAVE_EXPERIMENTAL_TRUE@ websocket_chatserver_example$(EXEEXT) @MHD_HAVE_EPOLL_TRUE@am__EXEEXT_2 = suspend_resume_epoll$(EXEEXT) @HAVE_JANSSON_TRUE@am__EXEEXT_3 = json_echo$(EXEEXT) @ENABLE_HTTPS_TRUE@am__EXEEXT_4 = https_fileserver_example$(EXEEXT) \ @ENABLE_HTTPS_TRUE@ minimal_example_empty_tls$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_5 = post_example$(EXEEXT) @HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_6 = demo$(EXEEXT) @ENABLE_HTTPS_TRUE@@HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_7 = demo_https$(EXEEXT) @ENABLE_DAUTH_TRUE@am__EXEEXT_8 = digest_auth_example$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ digest_auth_example_adv$(EXEEXT) @ENABLE_BAUTH_TRUE@am__EXEEXT_9 = authorization_example$(EXEEXT) @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_10 = upgrade_example$(EXEEXT) \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@ websocket_threaded_example$(EXEEXT) @HAVE_ZLIB_TRUE@am__EXEEXT_11 = http_compression$(EXEEXT) \ @HAVE_ZLIB_TRUE@ http_chunked_compression$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) am_authorization_example_OBJECTS = authorization_example.$(OBJEXT) authorization_example_OBJECTS = $(am_authorization_example_OBJECTS) authorization_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_benchmark_OBJECTS = benchmark-benchmark.$(OBJEXT) benchmark_OBJECTS = $(am_benchmark_OBJECTS) benchmark_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_benchmark_https_OBJECTS = \ benchmark_https-benchmark_https.$(OBJEXT) benchmark_https_OBJECTS = $(am_benchmark_https_OBJECTS) benchmark_https_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_chunked_example_OBJECTS = chunked_example.$(OBJEXT) chunked_example_OBJECTS = $(am_chunked_example_OBJECTS) chunked_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_demo_OBJECTS = demo-demo.$(OBJEXT) demo_OBJECTS = $(am_demo_OBJECTS) am__DEPENDENCIES_1 = demo_DEPENDENCIES = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) demo_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_demo_https_OBJECTS = demo_https-demo_https.$(OBJEXT) demo_https_OBJECTS = $(am_demo_https_OBJECTS) demo_https_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) demo_https_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_https_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_digest_auth_example_OBJECTS = digest_auth_example.$(OBJEXT) digest_auth_example_OBJECTS = $(am_digest_auth_example_OBJECTS) digest_auth_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_digest_auth_example_adv_OBJECTS = \ digest_auth_example_adv.$(OBJEXT) digest_auth_example_adv_OBJECTS = \ $(am_digest_auth_example_adv_OBJECTS) digest_auth_example_adv_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_dual_stack_example_OBJECTS = dual_stack_example.$(OBJEXT) dual_stack_example_OBJECTS = $(am_dual_stack_example_OBJECTS) dual_stack_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_OBJECTS = fileserver_example.$(OBJEXT) fileserver_example_OBJECTS = $(am_fileserver_example_OBJECTS) fileserver_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_dirs_OBJECTS = \ fileserver_example_dirs.$(OBJEXT) fileserver_example_dirs_OBJECTS = \ $(am_fileserver_example_dirs_OBJECTS) fileserver_example_dirs_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_external_select_OBJECTS = \ fileserver_example_external_select.$(OBJEXT) fileserver_example_external_select_OBJECTS = \ $(am_fileserver_example_external_select_OBJECTS) fileserver_example_external_select_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_http_chunked_compression_OBJECTS = \ http_chunked_compression.$(OBJEXT) http_chunked_compression_OBJECTS = \ $(am_http_chunked_compression_OBJECTS) http_chunked_compression_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) am_http_compression_OBJECTS = http_compression.$(OBJEXT) http_compression_OBJECTS = $(am_http_compression_OBJECTS) http_compression_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) am_https_fileserver_example_OBJECTS = \ https_fileserver_example-https_fileserver_example.$(OBJEXT) https_fileserver_example_OBJECTS = \ $(am_https_fileserver_example_OBJECTS) https_fileserver_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_json_echo_OBJECTS = json_echo.$(OBJEXT) json_echo_OBJECTS = $(am_json_echo_OBJECTS) json_echo_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_OBJECTS = minimal_example.$(OBJEXT) minimal_example_OBJECTS = $(am_minimal_example_OBJECTS) minimal_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_comet_OBJECTS = minimal_example_comet.$(OBJEXT) minimal_example_comet_OBJECTS = $(am_minimal_example_comet_OBJECTS) minimal_example_comet_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_empty_OBJECTS = minimal_example_empty.$(OBJEXT) minimal_example_empty_OBJECTS = $(am_minimal_example_empty_OBJECTS) minimal_example_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_empty_tls_OBJECTS = \ minimal_example_empty_tls.$(OBJEXT) minimal_example_empty_tls_OBJECTS = \ $(am_minimal_example_empty_tls_OBJECTS) minimal_example_empty_tls_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_post_example_OBJECTS = post_example.$(OBJEXT) post_example_OBJECTS = $(am_post_example_OBJECTS) post_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_querystring_example_OBJECTS = querystring_example.$(OBJEXT) querystring_example_OBJECTS = $(am_querystring_example_OBJECTS) querystring_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_refuse_post_example_OBJECTS = refuse_post_example.$(OBJEXT) refuse_post_example_OBJECTS = $(am_refuse_post_example_OBJECTS) refuse_post_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_suspend_resume_epoll_OBJECTS = \ suspend_resume_epoll-suspend_resume_epoll.$(OBJEXT) suspend_resume_epoll_OBJECTS = $(am_suspend_resume_epoll_OBJECTS) suspend_resume_epoll_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_timeout_OBJECTS = timeout.$(OBJEXT) timeout_OBJECTS = $(am_timeout_OBJECTS) timeout_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_upgrade_example_OBJECTS = \ upgrade_example-upgrade_example.$(OBJEXT) upgrade_example_OBJECTS = $(am_upgrade_example_OBJECTS) upgrade_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) upgrade_example_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(upgrade_example_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ am_websocket_chatserver_example_OBJECTS = \ websocket_chatserver_example.$(OBJEXT) websocket_chatserver_example_OBJECTS = \ $(am_websocket_chatserver_example_OBJECTS) websocket_chatserver_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_websocket_threaded_example_OBJECTS = websocket_threaded_example-websocket_threaded_example.$(OBJEXT) websocket_threaded_example_OBJECTS = \ $(am_websocket_threaded_example_OBJECTS) websocket_threaded_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) websocket_threaded_example_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(websocket_threaded_example_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/authorization_example.Po \ ./$(DEPDIR)/benchmark-benchmark.Po \ ./$(DEPDIR)/benchmark_https-benchmark_https.Po \ ./$(DEPDIR)/chunked_example.Po ./$(DEPDIR)/demo-demo.Po \ ./$(DEPDIR)/demo_https-demo_https.Po \ ./$(DEPDIR)/digest_auth_example.Po \ ./$(DEPDIR)/digest_auth_example_adv.Po \ ./$(DEPDIR)/dual_stack_example.Po \ ./$(DEPDIR)/fileserver_example.Po \ ./$(DEPDIR)/fileserver_example_dirs.Po \ ./$(DEPDIR)/fileserver_example_external_select.Po \ ./$(DEPDIR)/http_chunked_compression.Po \ ./$(DEPDIR)/http_compression.Po \ ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po \ ./$(DEPDIR)/json_echo.Po ./$(DEPDIR)/minimal_example.Po \ ./$(DEPDIR)/minimal_example_comet.Po \ ./$(DEPDIR)/minimal_example_empty.Po \ ./$(DEPDIR)/minimal_example_empty_tls.Po \ ./$(DEPDIR)/post_example.Po ./$(DEPDIR)/querystring_example.Po \ ./$(DEPDIR)/refuse_post_example.Po \ ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po \ ./$(DEPDIR)/timeout.Po \ ./$(DEPDIR)/upgrade_example-upgrade_example.Po \ ./$(DEPDIR)/websocket_chatserver_example.Po \ ./$(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \ $(benchmark_https_SOURCES) $(chunked_example_SOURCES) \ $(demo_SOURCES) $(demo_https_SOURCES) \ $(digest_auth_example_SOURCES) \ $(digest_auth_example_adv_SOURCES) \ $(dual_stack_example_SOURCES) $(fileserver_example_SOURCES) \ $(fileserver_example_dirs_SOURCES) \ $(fileserver_example_external_select_SOURCES) \ $(http_chunked_compression_SOURCES) \ $(http_compression_SOURCES) \ $(https_fileserver_example_SOURCES) $(json_echo_SOURCES) \ $(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \ $(minimal_example_empty_SOURCES) \ $(minimal_example_empty_tls_SOURCES) $(post_example_SOURCES) \ $(querystring_example_SOURCES) $(refuse_post_example_SOURCES) \ $(suspend_resume_epoll_SOURCES) $(timeout_SOURCES) \ $(upgrade_example_SOURCES) \ $(websocket_chatserver_example_SOURCES) \ $(websocket_threaded_example_SOURCES) DIST_SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \ $(benchmark_https_SOURCES) $(chunked_example_SOURCES) \ $(demo_SOURCES) $(demo_https_SOURCES) \ $(digest_auth_example_SOURCES) \ $(digest_auth_example_adv_SOURCES) \ $(dual_stack_example_SOURCES) $(fileserver_example_SOURCES) \ $(fileserver_example_dirs_SOURCES) \ $(fileserver_example_external_select_SOURCES) \ $(http_chunked_compression_SOURCES) \ $(http_compression_SOURCES) \ $(https_fileserver_example_SOURCES) $(json_echo_SOURCES) \ $(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \ $(minimal_example_empty_SOURCES) \ $(minimal_example_empty_tls_SOURCES) $(post_example_SOURCES) \ $(querystring_example_SOURCES) $(refuse_post_example_SOURCES) \ $(suspend_resume_epoll_SOURCES) $(timeout_SOURCES) \ $(upgrade_example_SOURCES) \ $(websocket_chatserver_example_SOURCES) \ $(websocket_threaded_example_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) \ $(am__append_13) AM_LDFLAGS = $(LDFLAGS_ac) MHD_CPU_COUNT_DEF = -DMHD_CPU_COUNT=$(CPU_COUNT) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) EXTRA_DIST = msgs_i18n.c noinst_EXTRA_DIST = msgs_i18n.c minimal_example_SOURCES = \ minimal_example.c minimal_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_SOURCES = \ minimal_example_empty.c minimal_example_empty_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_tls_SOURCES = \ minimal_example_empty_tls.c minimal_example_empty_tls_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la upgrade_example_SOURCES = \ upgrade_example.c upgrade_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) upgrade_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) websocket_threaded_example_SOURCES = \ websocket_threaded_example.c websocket_threaded_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) websocket_threaded_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) timeout_SOURCES = \ timeout.c timeout_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la chunked_example_SOURCES = \ chunked_example.c chunked_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la json_echo_SOURCES = \ json_echo.c json_echo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ -ljansson websocket_chatserver_example_SOURCES = \ websocket_chatserver_example.c websocket_chatserver_example_LDADD = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la demo_SOURCES = \ demo.c demo_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_LDADD = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) $(am__append_14) demo_https_SOURCES = \ demo_https.c demo_https_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_https_LDADD = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) $(am__append_15) benchmark_SOURCES = \ benchmark.c benchmark_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la suspend_resume_epoll_SOURCES = \ suspend_resume_epoll.c suspend_resume_epoll_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) suspend_resume_epoll_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la benchmark_https_SOURCES = \ benchmark_https.c benchmark_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la dual_stack_example_SOURCES = \ dual_stack_example.c dual_stack_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la post_example_SOURCES = \ post_example.c post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_comet_SOURCES = \ minimal_example_comet.c minimal_example_comet_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la authorization_example_SOURCES = \ authorization_example.c authorization_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_SOURCES = \ digest_auth_example.c digest_auth_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_adv_SOURCES = \ digest_auth_example_adv.c digest_auth_example_adv_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la refuse_post_example_SOURCES = \ refuse_post_example.c refuse_post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la querystring_example_SOURCES = \ querystring_example.c querystring_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_SOURCES = \ fileserver_example.c fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_dirs_SOURCES = \ fileserver_example_dirs.c fileserver_example_dirs_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_external_select_SOURCES = \ fileserver_example_external_select.c fileserver_example_external_select_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la https_fileserver_example_SOURCES = \ https_fileserver_example.c https_fileserver_example_CPPFLAGS = \ $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS) https_fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_compression_SOURCES = \ http_compression.c http_chunked_compression_SOURCES = \ http_chunked_compression.c http_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__append_16) http_chunked_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__append_17) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/examples/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/examples/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list authorization_example$(EXEEXT): $(authorization_example_OBJECTS) $(authorization_example_DEPENDENCIES) $(EXTRA_authorization_example_DEPENDENCIES) @rm -f authorization_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(authorization_example_OBJECTS) $(authorization_example_LDADD) $(LIBS) benchmark$(EXEEXT): $(benchmark_OBJECTS) $(benchmark_DEPENDENCIES) $(EXTRA_benchmark_DEPENDENCIES) @rm -f benchmark$(EXEEXT) $(AM_V_CCLD)$(LINK) $(benchmark_OBJECTS) $(benchmark_LDADD) $(LIBS) benchmark_https$(EXEEXT): $(benchmark_https_OBJECTS) $(benchmark_https_DEPENDENCIES) $(EXTRA_benchmark_https_DEPENDENCIES) @rm -f benchmark_https$(EXEEXT) $(AM_V_CCLD)$(LINK) $(benchmark_https_OBJECTS) $(benchmark_https_LDADD) $(LIBS) chunked_example$(EXEEXT): $(chunked_example_OBJECTS) $(chunked_example_DEPENDENCIES) $(EXTRA_chunked_example_DEPENDENCIES) @rm -f chunked_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(chunked_example_OBJECTS) $(chunked_example_LDADD) $(LIBS) demo$(EXEEXT): $(demo_OBJECTS) $(demo_DEPENDENCIES) $(EXTRA_demo_DEPENDENCIES) @rm -f demo$(EXEEXT) $(AM_V_CCLD)$(demo_LINK) $(demo_OBJECTS) $(demo_LDADD) $(LIBS) demo_https$(EXEEXT): $(demo_https_OBJECTS) $(demo_https_DEPENDENCIES) $(EXTRA_demo_https_DEPENDENCIES) @rm -f demo_https$(EXEEXT) $(AM_V_CCLD)$(demo_https_LINK) $(demo_https_OBJECTS) $(demo_https_LDADD) $(LIBS) digest_auth_example$(EXEEXT): $(digest_auth_example_OBJECTS) $(digest_auth_example_DEPENDENCIES) $(EXTRA_digest_auth_example_DEPENDENCIES) @rm -f digest_auth_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(digest_auth_example_OBJECTS) $(digest_auth_example_LDADD) $(LIBS) digest_auth_example_adv$(EXEEXT): $(digest_auth_example_adv_OBJECTS) $(digest_auth_example_adv_DEPENDENCIES) $(EXTRA_digest_auth_example_adv_DEPENDENCIES) @rm -f digest_auth_example_adv$(EXEEXT) $(AM_V_CCLD)$(LINK) $(digest_auth_example_adv_OBJECTS) $(digest_auth_example_adv_LDADD) $(LIBS) dual_stack_example$(EXEEXT): $(dual_stack_example_OBJECTS) $(dual_stack_example_DEPENDENCIES) $(EXTRA_dual_stack_example_DEPENDENCIES) @rm -f dual_stack_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(dual_stack_example_OBJECTS) $(dual_stack_example_LDADD) $(LIBS) fileserver_example$(EXEEXT): $(fileserver_example_OBJECTS) $(fileserver_example_DEPENDENCIES) $(EXTRA_fileserver_example_DEPENDENCIES) @rm -f fileserver_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_OBJECTS) $(fileserver_example_LDADD) $(LIBS) fileserver_example_dirs$(EXEEXT): $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_DEPENDENCIES) $(EXTRA_fileserver_example_dirs_DEPENDENCIES) @rm -f fileserver_example_dirs$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_LDADD) $(LIBS) fileserver_example_external_select$(EXEEXT): $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_DEPENDENCIES) $(EXTRA_fileserver_example_external_select_DEPENDENCIES) @rm -f fileserver_example_external_select$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_LDADD) $(LIBS) http_chunked_compression$(EXEEXT): $(http_chunked_compression_OBJECTS) $(http_chunked_compression_DEPENDENCIES) $(EXTRA_http_chunked_compression_DEPENDENCIES) @rm -f http_chunked_compression$(EXEEXT) $(AM_V_CCLD)$(LINK) $(http_chunked_compression_OBJECTS) $(http_chunked_compression_LDADD) $(LIBS) http_compression$(EXEEXT): $(http_compression_OBJECTS) $(http_compression_DEPENDENCIES) $(EXTRA_http_compression_DEPENDENCIES) @rm -f http_compression$(EXEEXT) $(AM_V_CCLD)$(LINK) $(http_compression_OBJECTS) $(http_compression_LDADD) $(LIBS) https_fileserver_example$(EXEEXT): $(https_fileserver_example_OBJECTS) $(https_fileserver_example_DEPENDENCIES) $(EXTRA_https_fileserver_example_DEPENDENCIES) @rm -f https_fileserver_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(https_fileserver_example_OBJECTS) $(https_fileserver_example_LDADD) $(LIBS) json_echo$(EXEEXT): $(json_echo_OBJECTS) $(json_echo_DEPENDENCIES) $(EXTRA_json_echo_DEPENDENCIES) @rm -f json_echo$(EXEEXT) $(AM_V_CCLD)$(LINK) $(json_echo_OBJECTS) $(json_echo_LDADD) $(LIBS) minimal_example$(EXEEXT): $(minimal_example_OBJECTS) $(minimal_example_DEPENDENCIES) $(EXTRA_minimal_example_DEPENDENCIES) @rm -f minimal_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_OBJECTS) $(minimal_example_LDADD) $(LIBS) minimal_example_comet$(EXEEXT): $(minimal_example_comet_OBJECTS) $(minimal_example_comet_DEPENDENCIES) $(EXTRA_minimal_example_comet_DEPENDENCIES) @rm -f minimal_example_comet$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_comet_OBJECTS) $(minimal_example_comet_LDADD) $(LIBS) minimal_example_empty$(EXEEXT): $(minimal_example_empty_OBJECTS) $(minimal_example_empty_DEPENDENCIES) $(EXTRA_minimal_example_empty_DEPENDENCIES) @rm -f minimal_example_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_empty_OBJECTS) $(minimal_example_empty_LDADD) $(LIBS) minimal_example_empty_tls$(EXEEXT): $(minimal_example_empty_tls_OBJECTS) $(minimal_example_empty_tls_DEPENDENCIES) $(EXTRA_minimal_example_empty_tls_DEPENDENCIES) @rm -f minimal_example_empty_tls$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_empty_tls_OBJECTS) $(minimal_example_empty_tls_LDADD) $(LIBS) post_example$(EXEEXT): $(post_example_OBJECTS) $(post_example_DEPENDENCIES) $(EXTRA_post_example_DEPENDENCIES) @rm -f post_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(post_example_OBJECTS) $(post_example_LDADD) $(LIBS) querystring_example$(EXEEXT): $(querystring_example_OBJECTS) $(querystring_example_DEPENDENCIES) $(EXTRA_querystring_example_DEPENDENCIES) @rm -f querystring_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(querystring_example_OBJECTS) $(querystring_example_LDADD) $(LIBS) refuse_post_example$(EXEEXT): $(refuse_post_example_OBJECTS) $(refuse_post_example_DEPENDENCIES) $(EXTRA_refuse_post_example_DEPENDENCIES) @rm -f refuse_post_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(refuse_post_example_OBJECTS) $(refuse_post_example_LDADD) $(LIBS) suspend_resume_epoll$(EXEEXT): $(suspend_resume_epoll_OBJECTS) $(suspend_resume_epoll_DEPENDENCIES) $(EXTRA_suspend_resume_epoll_DEPENDENCIES) @rm -f suspend_resume_epoll$(EXEEXT) $(AM_V_CCLD)$(LINK) $(suspend_resume_epoll_OBJECTS) $(suspend_resume_epoll_LDADD) $(LIBS) timeout$(EXEEXT): $(timeout_OBJECTS) $(timeout_DEPENDENCIES) $(EXTRA_timeout_DEPENDENCIES) @rm -f timeout$(EXEEXT) $(AM_V_CCLD)$(LINK) $(timeout_OBJECTS) $(timeout_LDADD) $(LIBS) upgrade_example$(EXEEXT): $(upgrade_example_OBJECTS) $(upgrade_example_DEPENDENCIES) $(EXTRA_upgrade_example_DEPENDENCIES) @rm -f upgrade_example$(EXEEXT) $(AM_V_CCLD)$(upgrade_example_LINK) $(upgrade_example_OBJECTS) $(upgrade_example_LDADD) $(LIBS) websocket_chatserver_example$(EXEEXT): $(websocket_chatserver_example_OBJECTS) $(websocket_chatserver_example_DEPENDENCIES) $(EXTRA_websocket_chatserver_example_DEPENDENCIES) @rm -f websocket_chatserver_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(websocket_chatserver_example_OBJECTS) $(websocket_chatserver_example_LDADD) $(LIBS) websocket_threaded_example$(EXEEXT): $(websocket_threaded_example_OBJECTS) $(websocket_threaded_example_DEPENDENCIES) $(EXTRA_websocket_threaded_example_DEPENDENCIES) @rm -f websocket_threaded_example$(EXEEXT) $(AM_V_CCLD)$(websocket_threaded_example_LINK) $(websocket_threaded_example_OBJECTS) $(websocket_threaded_example_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/authorization_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark-benchmark.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark_https-benchmark_https.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chunked_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo-demo.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_https-demo_https.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/digest_auth_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/digest_auth_example_adv.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dual_stack_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_dirs.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_external_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/http_chunked_compression.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/http_compression.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/json_echo.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_comet.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_empty.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_empty_tls.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/post_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/querystring_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/refuse_post_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/timeout.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/upgrade_example-upgrade_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/websocket_chatserver_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< benchmark-benchmark.o: benchmark.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.o -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c benchmark-benchmark.obj: benchmark.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.obj -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi` benchmark_https-benchmark_https.o: benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.o -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c benchmark_https-benchmark_https.obj: benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.obj -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi` demo-demo.o: demo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.o -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo.c' object='demo-demo.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c demo-demo.obj: demo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.obj -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo.c' object='demo-demo.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi` demo_https-demo_https.o: demo_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.o -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c demo_https-demo_https.obj: demo_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.obj -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi` https_fileserver_example-https_fileserver_example.o: https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.o -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c https_fileserver_example-https_fileserver_example.obj: https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.obj -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi` suspend_resume_epoll-suspend_resume_epoll.o: suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT suspend_resume_epoll-suspend_resume_epoll.o -MD -MP -MF $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo -c -o suspend_resume_epoll-suspend_resume_epoll.o `test -f 'suspend_resume_epoll.c' || echo '$(srcdir)/'`suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='suspend_resume_epoll.c' object='suspend_resume_epoll-suspend_resume_epoll.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o suspend_resume_epoll-suspend_resume_epoll.o `test -f 'suspend_resume_epoll.c' || echo '$(srcdir)/'`suspend_resume_epoll.c suspend_resume_epoll-suspend_resume_epoll.obj: suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT suspend_resume_epoll-suspend_resume_epoll.obj -MD -MP -MF $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo -c -o suspend_resume_epoll-suspend_resume_epoll.obj `if test -f 'suspend_resume_epoll.c'; then $(CYGPATH_W) 'suspend_resume_epoll.c'; else $(CYGPATH_W) '$(srcdir)/suspend_resume_epoll.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='suspend_resume_epoll.c' object='suspend_resume_epoll-suspend_resume_epoll.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o suspend_resume_epoll-suspend_resume_epoll.obj `if test -f 'suspend_resume_epoll.c'; then $(CYGPATH_W) 'suspend_resume_epoll.c'; else $(CYGPATH_W) '$(srcdir)/suspend_resume_epoll.c'; fi` upgrade_example-upgrade_example.o: upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -MT upgrade_example-upgrade_example.o -MD -MP -MF $(DEPDIR)/upgrade_example-upgrade_example.Tpo -c -o upgrade_example-upgrade_example.o `test -f 'upgrade_example.c' || echo '$(srcdir)/'`upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/upgrade_example-upgrade_example.Tpo $(DEPDIR)/upgrade_example-upgrade_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='upgrade_example.c' object='upgrade_example-upgrade_example.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -c -o upgrade_example-upgrade_example.o `test -f 'upgrade_example.c' || echo '$(srcdir)/'`upgrade_example.c upgrade_example-upgrade_example.obj: upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -MT upgrade_example-upgrade_example.obj -MD -MP -MF $(DEPDIR)/upgrade_example-upgrade_example.Tpo -c -o upgrade_example-upgrade_example.obj `if test -f 'upgrade_example.c'; then $(CYGPATH_W) 'upgrade_example.c'; else $(CYGPATH_W) '$(srcdir)/upgrade_example.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/upgrade_example-upgrade_example.Tpo $(DEPDIR)/upgrade_example-upgrade_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='upgrade_example.c' object='upgrade_example-upgrade_example.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -c -o upgrade_example-upgrade_example.obj `if test -f 'upgrade_example.c'; then $(CYGPATH_W) 'upgrade_example.c'; else $(CYGPATH_W) '$(srcdir)/upgrade_example.c'; fi` websocket_threaded_example-websocket_threaded_example.o: websocket_threaded_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(websocket_threaded_example_CFLAGS) $(CFLAGS) -MT websocket_threaded_example-websocket_threaded_example.o -MD -MP -MF $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Tpo -c -o websocket_threaded_example-websocket_threaded_example.o `test -f 'websocket_threaded_example.c' || echo '$(srcdir)/'`websocket_threaded_example.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Tpo $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='websocket_threaded_example.c' object='websocket_threaded_example-websocket_threaded_example.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(websocket_threaded_example_CFLAGS) $(CFLAGS) -c -o websocket_threaded_example-websocket_threaded_example.o `test -f 'websocket_threaded_example.c' || echo '$(srcdir)/'`websocket_threaded_example.c websocket_threaded_example-websocket_threaded_example.obj: websocket_threaded_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(websocket_threaded_example_CFLAGS) $(CFLAGS) -MT websocket_threaded_example-websocket_threaded_example.obj -MD -MP -MF $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Tpo -c -o websocket_threaded_example-websocket_threaded_example.obj `if test -f 'websocket_threaded_example.c'; then $(CYGPATH_W) 'websocket_threaded_example.c'; else $(CYGPATH_W) '$(srcdir)/websocket_threaded_example.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Tpo $(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='websocket_threaded_example.c' object='websocket_threaded_example-websocket_threaded_example.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(websocket_threaded_example_CFLAGS) $(CFLAGS) -c -o websocket_threaded_example-websocket_threaded_example.obj `if test -f 'websocket_threaded_example.c'; then $(CYGPATH_W) 'websocket_threaded_example.c'; else $(CYGPATH_W) '$(srcdir)/websocket_threaded_example.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(PROGRAMS) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/authorization_example.Po -rm -f ./$(DEPDIR)/benchmark-benchmark.Po -rm -f ./$(DEPDIR)/benchmark_https-benchmark_https.Po -rm -f ./$(DEPDIR)/chunked_example.Po -rm -f ./$(DEPDIR)/demo-demo.Po -rm -f ./$(DEPDIR)/demo_https-demo_https.Po -rm -f ./$(DEPDIR)/digest_auth_example.Po -rm -f ./$(DEPDIR)/digest_auth_example_adv.Po -rm -f ./$(DEPDIR)/dual_stack_example.Po -rm -f ./$(DEPDIR)/fileserver_example.Po -rm -f ./$(DEPDIR)/fileserver_example_dirs.Po -rm -f ./$(DEPDIR)/fileserver_example_external_select.Po -rm -f ./$(DEPDIR)/http_chunked_compression.Po -rm -f ./$(DEPDIR)/http_compression.Po -rm -f ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po -rm -f ./$(DEPDIR)/json_echo.Po -rm -f ./$(DEPDIR)/minimal_example.Po -rm -f ./$(DEPDIR)/minimal_example_comet.Po -rm -f ./$(DEPDIR)/minimal_example_empty.Po -rm -f ./$(DEPDIR)/minimal_example_empty_tls.Po -rm -f ./$(DEPDIR)/post_example.Po -rm -f ./$(DEPDIR)/querystring_example.Po -rm -f ./$(DEPDIR)/refuse_post_example.Po -rm -f ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/timeout.Po -rm -f ./$(DEPDIR)/upgrade_example-upgrade_example.Po -rm -f ./$(DEPDIR)/websocket_chatserver_example.Po -rm -f ./$(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/authorization_example.Po -rm -f ./$(DEPDIR)/benchmark-benchmark.Po -rm -f ./$(DEPDIR)/benchmark_https-benchmark_https.Po -rm -f ./$(DEPDIR)/chunked_example.Po -rm -f ./$(DEPDIR)/demo-demo.Po -rm -f ./$(DEPDIR)/demo_https-demo_https.Po -rm -f ./$(DEPDIR)/digest_auth_example.Po -rm -f ./$(DEPDIR)/digest_auth_example_adv.Po -rm -f ./$(DEPDIR)/dual_stack_example.Po -rm -f ./$(DEPDIR)/fileserver_example.Po -rm -f ./$(DEPDIR)/fileserver_example_dirs.Po -rm -f ./$(DEPDIR)/fileserver_example_external_select.Po -rm -f ./$(DEPDIR)/http_chunked_compression.Po -rm -f ./$(DEPDIR)/http_compression.Po -rm -f ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po -rm -f ./$(DEPDIR)/json_echo.Po -rm -f ./$(DEPDIR)/minimal_example.Po -rm -f ./$(DEPDIR)/minimal_example_comet.Po -rm -f ./$(DEPDIR)/minimal_example_empty.Po -rm -f ./$(DEPDIR)/minimal_example_empty_tls.Po -rm -f ./$(DEPDIR)/post_example.Po -rm -f ./$(DEPDIR)/querystring_example.Po -rm -f ./$(DEPDIR)/refuse_post_example.Po -rm -f ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/timeout.Po -rm -f ./$(DEPDIR)/upgrade_example-upgrade_example.Po -rm -f ./$(DEPDIR)/websocket_chatserver_example.Po -rm -f ./$(DEPDIR)/websocket_threaded_example-websocket_threaded_example.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-am clean clean-generic clean-libtool \ clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/examples/minimal_example.c0000644000175000017500000000712414760713574017233 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demo" \ "libmicrohttpd demo" struct handler_param { const char *response_page; }; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = PAGE; d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/dual_stack_example.c0000644000175000017500000000640714760713574017722 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2012 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file dual_stack_example.c * @brief how to use MHD with both IPv4 and IPv6 support (dual-stack) * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" struct handler_param { const char *response_page; }; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = PAGE; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_DUAL_STACK, (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/timeout.c0000644000175000017500000000636414760713574015565 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2017 Christian Grothoff, Silvio Clecio (silvioprog), Evgeny Grin (Karlson2k) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file timeout.c * @brief example for how to use libmicrohttpd request timeout * @author Christian Grothoff, Silvio Clecio (silvioprog), Karlson2k (Evgeny Grin) */ #include #include #include #define PORT 8080 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello timeout!"; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_from_buffer_static (strlen (page), (const void *) page); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html")) { fprintf (stderr, "Failed to set content type header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, /* 3 seconds */ MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 3, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.2/src/examples/minimal_example_empty_tls.c0000644000175000017500000001655114760713574021337 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example_empty_tls.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_NO_CONTENT, response); MHD_destroy_response (response); return ret; } /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) 1, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/json_echo.c0000644000175000017500000002407315035214304016022 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2025 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file json_echo.c * @brief example for processing POST requests with JSON uploads, echos the JSON back to the client * @author Christian Grothoff */ #include #include #include #include #include #include #include /** * Bad request page. */ #define BAD_REQUEST_ERROR \ "Illegal requestGo away." /** * Invalid JSON page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * State we keep for each request. */ struct Request { /** * Number of bytes received. */ size_t off; /** * Size of @a buf. */ size_t len; /** * Buffer for POST data. */ void *buf; }; /** * Handler used to generate a 404 reply. * * @param connection connection to use */ static enum MHD_Result not_found_page (struct MHD_Connection *connection) { struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), (const void *) NOT_FOUND_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html")) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * Handler used to generate a 400 reply. * * @param connection connection to use */ static enum MHD_Result invalid_request (struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_static ( strlen (BAD_REQUEST_ERROR), (const void *) BAD_REQUEST_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html")) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * Main MHD callback for handling requests. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle identifying the incoming connection * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct Request *request = *req_cls; struct MHD_Response *response; enum MHD_Result ret; unsigned int i; (void) cls; /* Unused. Silence compiler warning. */ (void) version; /* Unused. Silence compiler warning. */ if (NULL == request) { const char *clen; char dummy; unsigned int len; request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 != strcmp (method, MHD_HTTP_METHOD_POST)) { return not_found_page (connection); } clen = MHD_lookup_connection_value ( connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH); if (NULL == clen) return invalid_request (connection); if (1 != sscanf (clen, "%u%c", &len, &dummy)) return invalid_request (connection); request->len = len; request->buf = malloc (request->len); if (NULL == request->buf) return MHD_NO; return MHD_YES; } if (0 != *upload_data_size) { if (request->len < *upload_data_size + request->off) { fprintf (stderr, "Content-length header wrong, aborting\n"); return MHD_NO; } memcpy (request->buf, upload_data, *upload_data_size); request->off += *upload_data_size; *upload_data_size = 0; return MHD_YES; } { json_t *j; json_error_t err; char *s; j = json_loadb (request->buf, request->len, 0, &err); if (NULL == j) return invalid_request (connection); s = json_dumps (j, JSON_INDENT (2)); json_decref (j); response = MHD_create_response_from_buffer (strlen (s), s, MHD_RESPMEM_MUST_FREE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silence compiler warning. */ (void) connection; /* Unused. Silence compiler warning. */ (void) toe; /* Unused. Silence compiler warning. */ if (NULL == request) return; if (NULL != request->buf) free (request->buf); free (request); } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/https_fileserver_example.c0000644000175000017500000002243014760713574021172 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file https_fileserver_example.c * @brief a simple HTTPS file server using TLS. * * Usage : * * 'http_fileserver_example HTTP-PORT SECONDS-TO-RUN' * * The certificate & key are required by the server to operate, omitting the * path arguments will cause the server to use the hard coded example certificate & key. * * 'certtool' may be used to generate these if required. * * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #define BUF_SIZE 1024 #define MAX_URL_LEN 255 #define EMPTY_PAGE \ "File not foundFile not found" /* test server key */ static const char key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void file_free_callback (void *cls) { FILE *file = cls; fclose (file); } /* HTTP access handler call back */ static enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { response = MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE), (const void *) EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &file_free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *TLS_daemon; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > UINT16_MAX) ) { fprintf (stderr, "Port must be a number between 1 and 65535\n"); return 1; } TLS_daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, (uint16_t) port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_CONNECTION_TIMEOUT, 256, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == TLS_daemon) { fprintf (stderr, "Error: failed to start TLS_daemon.\n"); return 1; } printf ("MHD daemon listening on port %u\n", (unsigned int) port); (void) getc (stdin); MHD_stop_daemon (TLS_daemon); return 0; } libmicrohttpd-1.0.2/src/examples/fileserver_example_dirs.c0000644000175000017500000001474014760713574020776 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example_dirs.c * @brief example for how to use libmicrohttpd to serve files (with directory support) * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #ifdef HAVE_UNISTD_H #include #endif #include static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void file_free_callback (void *cls) { FILE *file = cls; fclose (file); } static void dir_free_callback (void *cls) { DIR *dir = cls; if (dir != NULL) closedir (dir); } static ssize_t dir_reader (void *cls, uint64_t pos, char *buf, size_t max) { DIR *dir = cls; struct dirent *e; int res; if (max < 512) return 0; (void) pos; /* 'pos' is ignored as function return next one single entry per call. */ do { e = readdir (dir); if (e == NULL) return MHD_CONTENT_READER_END_OF_STREAM; } while (e->d_name[0] == '.'); res = snprintf (buf, max, "%s
    ", e->d_name, e->d_name); if (0 >= res) return MHD_CONTENT_READER_END_WITH_ERROR; if (max < (size_t) res) return MHD_CONTENT_READER_END_WITH_ERROR; return (ssize_t) res; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; DIR *dir; struct stat buf; char emsg[1024]; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { dir = opendir ("."); if (NULL == dir) { /* most likely cause: more concurrent requests than available file descriptors / 2 */ snprintf (emsg, sizeof (emsg), "Failed to open directory `.': %s\n", strerror (errno)); response = MHD_create_response_from_buffer (strlen (emsg), emsg, MHD_RESPMEM_MUST_COPY); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &dir_reader, dir, &dir_free_callback); if (NULL == response) { closedir (dir); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &file_free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/websocket_threaded_example.c0000644000175000017500000006343714760713574021444 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2020 Christian Grothoff, Silvio Clecio (and other contributing authors) Copyright (C) 2020-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file websocket_threaded_example.c * @brief example for how to provide a tiny threaded websocket server * @author Silvio Clecio (silvioprog) * @author Karlson2k (Evgeny Grin) */ /* TODO: allow to send large messages. */ #include "platform.h" #include #include #include #define CHAT_PAGE \ "\n" \ "\n" \ "WebSocket chat\n" \ "\n" \ "\n" \ "\n" \ "\n" \ "

    \n" \ "\n" \ "\n" \ "" #define BAD_REQUEST_PAGE \ "\n" \ "\n" \ "WebSocket chat\n" \ "\n" \ "\n" \ "Bad Request\n" \ "\n" \ "\n" #define UPGRADE_REQUIRED_PAGE \ "\n" \ "\n" \ "WebSocket chat\n" \ "\n" \ "\n" \ "Upgrade required\n" \ "\n" \ "\n" #define WS_SEC_WEBSOCKET_VERSION "13" #define WS_UPGRADE_VALUE "websocket" #define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" #define WS_GUID_LEN 36 #define WS_KEY_LEN 24 #define WS_KEY_GUID_LEN ((WS_KEY_LEN) + (WS_GUID_LEN)) #define WS_FIN 128 #define WS_OPCODE_TEXT_FRAME 1 #define WS_OPCODE_CON_CLOSE_FRAME 8 #define MAX_CLIENTS 10 static MHD_socket CLIENT_SOCKS[MAX_CLIENTS]; static pthread_mutex_t MUTEX = PTHREAD_MUTEX_INITIALIZER; struct WsData { struct MHD_UpgradeResponseHandle *urh; MHD_socket sock; }; /********** begin SHA-1 **********/ #define SHA1HashSize 20 #define SHA1CircularShift(bits, word) \ (((word) << (bits)) | ((word) >> (32 - (bits)))) enum SHA1_RESULT { SHA1_RESULT_SUCCESS = 0, SHA1_RESULT_NULL = 1, SHA1_RESULT_STATE_ERROR = 2 }; struct SHA1Context { uint32_t intermediate_hash[SHA1HashSize / 4]; uint32_t length_low; uint32_t length_high; int_least16_t message_block_index; unsigned char message_block[64]; int computed; int corrupted; }; static void SHA1ProcessMessageBlock (struct SHA1Context *context) { const uint32_t K[] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; int i; uint32_t temp; uint32_t W[80]; uint32_t A, B, C, D, E; for (i = 0; i < 16; i++) { W[i] = ((uint32_t) context->message_block[i * 4]) << 24; W[i] |= ((uint32_t) context->message_block[i * 4 + 1]) << 16; W[i] |= ((uint32_t) context->message_block[i * 4 + 2]) << 8; W[i] |= context->message_block[i * 4 + 3]; } for (i = 16; i < 80; i++) { W[i] = SHA1CircularShift (1, W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); } A = context->intermediate_hash[0]; B = context->intermediate_hash[1]; C = context->intermediate_hash[2]; D = context->intermediate_hash[3]; E = context->intermediate_hash[4]; for (i = 0; i < 20; i++) { temp = SHA1CircularShift (5, A) + ((B & C) | ((~B) & D)) + E + W[i] + K[0]; E = D; D = C; C = SHA1CircularShift (30, B); B = A; A = temp; } for (i = 20; i < 40; i++) { temp = SHA1CircularShift (5, A) + (B ^ C ^ D) + E + W[i] + K[1]; E = D; D = C; C = SHA1CircularShift (30, B); B = A; A = temp; } for (i = 40; i < 60; i++) { temp = SHA1CircularShift (5, A) + ((B & C) | (B & D) | (C & D)) + E + W[i] + K[2]; E = D; D = C; C = SHA1CircularShift (30, B); B = A; A = temp; } for (i = 60; i < 80; i++) { temp = SHA1CircularShift (5, A) + (B ^ C ^ D) + E + W[i] + K[3]; E = D; D = C; C = SHA1CircularShift (30, B); B = A; A = temp; } context->intermediate_hash[0] += A; context->intermediate_hash[1] += B; context->intermediate_hash[2] += C; context->intermediate_hash[3] += D; context->intermediate_hash[4] += E; context->message_block_index = 0; } static void SHA1PadMessage (struct SHA1Context *context) { if (context->message_block_index > 55) { context->message_block[context->message_block_index++] = 0x80; while (context->message_block_index < 64) { context->message_block[context->message_block_index++] = 0; } SHA1ProcessMessageBlock (context); while (context->message_block_index < 56) { context->message_block[context->message_block_index++] = 0; } } else { context->message_block[context->message_block_index++] = 0x80; while (context->message_block_index < 56) { context->message_block[context->message_block_index++] = 0; } } context->message_block[56] = (unsigned char) (context->length_high >> 24); context->message_block[57] = (unsigned char) (context->length_high >> 16); context->message_block[58] = (unsigned char) (context->length_high >> 8); context->message_block[59] = (unsigned char) (context->length_high); context->message_block[60] = (unsigned char) (context->length_low >> 24); context->message_block[61] = (unsigned char) (context->length_low >> 16); context->message_block[62] = (unsigned char) (context->length_low >> 8); context->message_block[63] = (unsigned char) (context->length_low); SHA1ProcessMessageBlock (context); } static enum SHA1_RESULT SHA1Reset (struct SHA1Context *context) { if (! context) { return SHA1_RESULT_NULL; } context->length_low = 0; context->length_high = 0; context->message_block_index = 0; context->intermediate_hash[0] = 0x67452301; context->intermediate_hash[1] = 0xEFCDAB89; context->intermediate_hash[2] = 0x98BADCFE; context->intermediate_hash[3] = 0x10325476; context->intermediate_hash[4] = 0xC3D2E1F0; context->computed = 0; context->corrupted = 0; return SHA1_RESULT_SUCCESS; } static enum SHA1_RESULT SHA1Result (struct SHA1Context *context, unsigned char Message_Digest[SHA1HashSize]) { int i; if (! context || ! Message_Digest) { return SHA1_RESULT_NULL; } if (context->corrupted) { return SHA1_RESULT_STATE_ERROR; } if (! context->computed) { SHA1PadMessage (context); for (i = 0; i < 64; ++i) { context->message_block[i] = 0; } context->length_low = 0; context->length_high = 0; context->computed = 1; } for (i = 0; i < SHA1HashSize; ++i) { Message_Digest[i] = (unsigned char) (context->intermediate_hash[i >> 2] >> 8 * (3 - (i & 0x03))); } return SHA1_RESULT_SUCCESS; } static enum SHA1_RESULT SHA1Input (struct SHA1Context *context, const unsigned char *message_array, unsigned length) { if (! length) { return SHA1_RESULT_SUCCESS; } if (! context || ! message_array) { return SHA1_RESULT_NULL; } if (context->computed) { context->corrupted = 1; return SHA1_RESULT_STATE_ERROR; } if (context->corrupted) { return SHA1_RESULT_STATE_ERROR; } while (length-- && ! context->corrupted) { context->message_block[context->message_block_index++] = (*message_array & 0xFF); context->length_low += 8; if (context->length_low == 0) { context->length_high++; if (context->length_high == 0) { context->corrupted = 1; } } if (context->message_block_index == 64) { SHA1ProcessMessageBlock (context); } message_array++; } return SHA1_RESULT_SUCCESS; } /********** end SHA-1 **********/ /********** begin Base64 **********/ static ssize_t BASE64Encode (const void *in, size_t len, char **output) { #define FILLCHAR '=' const char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; const char *data = in; char *opt; ssize_t ret; size_t i; char c; ret = 0; opt = malloc (2 + (len * 4 / 3) + 8); if (NULL == opt) { return -1; } for (i = 0; i < len; ++i) { c = (data[i] >> 2) & 0x3F; opt[ret++] = cvt[(int) c]; c = (data[i] << 4) & 0x3F; if (++i < len) { c = (char) (c | ((data[i] >> 4) & 0x0F)); } opt[ret++] = cvt[(int) c]; if (i < len) { c = (char) (c | ((data[i] << 2) & 0x3F)); if (++i < len) { c = (char) (c | ((data[i] >> 6) & 0x03)); } opt[ret++] = cvt[(int) c]; } else { ++i; opt[ret++] = FILLCHAR; } if (i < len) { c = data[i] & 0x3F; opt[ret++] = cvt[(int) c]; } else { opt[ret++] = FILLCHAR; } } *output = opt; return ret; } /********** end Base64 **********/ static enum MHD_Result is_websocket_request (struct MHD_Connection *con, const char *upg_header, const char *con_header) { (void) con; /* Unused. Silent compiler warning. */ return ((upg_header != NULL) && (con_header != NULL) && (0 == strcmp (upg_header, WS_UPGRADE_VALUE)) && (NULL != strstr (con_header, "Upgrade"))) ? MHD_YES : MHD_NO; } static enum MHD_Result send_chat_page (struct MHD_Connection *con) { struct MHD_Response *res; enum MHD_Result ret; res = MHD_create_response_from_buffer_static (strlen (CHAT_PAGE), (const void *) CHAT_PAGE); ret = MHD_queue_response (con, MHD_HTTP_OK, res); MHD_destroy_response (res); return ret; } static enum MHD_Result send_bad_request (struct MHD_Connection *con) { struct MHD_Response *res; enum MHD_Result ret; res = MHD_create_response_from_buffer_static (strlen (BAD_REQUEST_PAGE), (const void *) BAD_REQUEST_PAGE); ret = MHD_queue_response (con, MHD_HTTP_BAD_REQUEST, res); MHD_destroy_response (res); return ret; } static enum MHD_Result send_upgrade_required (struct MHD_Connection *con) { struct MHD_Response *res; enum MHD_Result ret; res = MHD_create_response_from_buffer_static (strlen (UPGRADE_REQUIRED_PAGE), (const void *) UPGRADE_REQUIRED_PAGE); if (MHD_YES != MHD_add_response_header (res, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION, WS_SEC_WEBSOCKET_VERSION)) { MHD_destroy_response (res); return MHD_NO; } ret = MHD_queue_response (con, MHD_HTTP_UPGRADE_REQUIRED, res); MHD_destroy_response (res); return ret; } static enum MHD_Result ws_get_accept_value (const char *key, char **val) { struct SHA1Context ctx; unsigned char hash[SHA1HashSize]; char *str; ssize_t len; if ( (NULL == key) || (WS_KEY_LEN != strlen (key))) { return MHD_NO; } str = malloc (WS_KEY_LEN + WS_GUID_LEN + 1); if (NULL == str) { return MHD_NO; } strncpy (str, key, (WS_KEY_LEN + 1)); strncpy (str + WS_KEY_LEN, WS_GUID, WS_GUID_LEN + 1); SHA1Reset (&ctx); SHA1Input (&ctx, (const unsigned char *) str, WS_KEY_GUID_LEN); if (SHA1_RESULT_SUCCESS != SHA1Result (&ctx, hash)) { free (str); return MHD_NO; } free (str); len = BASE64Encode (hash, SHA1HashSize, val); if (-1 == len) { return MHD_NO; } (*val)[len] = '\0'; return MHD_YES; } static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) abort (); #endif /* MHD_WINSOCK_SOCKETS */ } static size_t send_all (MHD_socket sock, const unsigned char *buf, size_t len) { ssize_t ret; size_t off; for (off = 0; off < len; off += (size_t) ret) { #if ! defined(_WIN32) || defined(__CYGWIN__) ret = send (sock, (const void *) &buf[off], len - off, 0); #else /* Native W32 */ ret = send (sock, (const void *) &buf[off], (int) (len - off), 0); #endif /* Native W32 */ if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) { break; } } return off; } static ssize_t ws_send_frame (MHD_socket sock, const char *msg, size_t length) { unsigned char *response; unsigned char frame[10]; unsigned char idx_first_rdata; size_t idx_response; size_t output; MHD_socket isock; size_t i; frame[0] = (WS_FIN | WS_OPCODE_TEXT_FRAME); if (length <= 125) { frame[1] = length & 0x7F; idx_first_rdata = 2; } #if SIZEOF_SIZE_T > 4 else if (0xFFFF < length) { frame[1] = 127; frame[2] = (unsigned char) ((length >> 56) & 0xFF); frame[3] = (unsigned char) ((length >> 48) & 0xFF); frame[4] = (unsigned char) ((length >> 40) & 0xFF); frame[5] = (unsigned char) ((length >> 32) & 0xFF); frame[6] = (unsigned char) ((length >> 24) & 0xFF); frame[7] = (unsigned char) ((length >> 16) & 0xFF); frame[8] = (unsigned char) ((length >> 8) & 0xFF); frame[9] = (unsigned char) (length & 0xFF); idx_first_rdata = 10; } #endif /* SIZEOF_SIZE_T > 4 */ else { frame[1] = 126; frame[2] = (length >> 8) & 0xFF; frame[3] = length & 0xFF; idx_first_rdata = 4; } idx_response = 0; response = malloc (idx_first_rdata + length + 1); if (NULL == response) { return -1; } for (i = 0; i < idx_first_rdata; i++) { response[i] = frame[i]; idx_response++; } for (i = 0; i < length; i++) { response[idx_response] = (unsigned char) msg[i]; idx_response++; } response[idx_response] = '\0'; output = 0; if (0 != pthread_mutex_lock (&MUTEX)) abort (); for (i = 0; i < MAX_CLIENTS; i++) { isock = CLIENT_SOCKS[i]; if ((isock != MHD_INVALID_SOCKET) && (isock != sock)) { output += send_all (isock, response, idx_response); } } if (0 != pthread_mutex_unlock (&MUTEX)) abort (); free (response); return (ssize_t) output; } static unsigned char * ws_receive_frame (unsigned char *frame, ssize_t *length, int *type) { unsigned char masks[4]; unsigned char mask; unsigned char *msg; unsigned char flength; unsigned char idx_first_mask; unsigned char idx_first_data; size_t data_length; int i; int j; msg = NULL; if (frame[0] == (WS_FIN | WS_OPCODE_TEXT_FRAME)) { *type = WS_OPCODE_TEXT_FRAME; idx_first_mask = 2; mask = frame[1]; flength = mask & 0x7F; if (flength == 126) { idx_first_mask = 4; } else if (flength == 127) { idx_first_mask = 10; } idx_first_data = (unsigned char) (idx_first_mask + 4); data_length = (size_t) *length - idx_first_data; masks[0] = frame[idx_first_mask + 0]; masks[1] = frame[idx_first_mask + 1]; masks[2] = frame[idx_first_mask + 2]; masks[3] = frame[idx_first_mask + 3]; msg = malloc (data_length + 1); if (NULL != msg) { for (i = idx_first_data, j = 0; i < *length; i++, j++) { msg[j] = frame[i] ^ masks[j % 4]; } *length = (ssize_t) data_length; msg[j] = '\0'; } } else if (frame[0] == (WS_FIN | WS_OPCODE_CON_CLOSE_FRAME)) { *type = WS_OPCODE_CON_CLOSE_FRAME; } else { *type = frame[0] & 0x0F; } return msg; } static void * run_usock (void *cls) { struct WsData *ws = cls; struct MHD_UpgradeResponseHandle *urh = ws->urh; unsigned char buf[2048]; unsigned char *msg; char *text; ssize_t got; int type; int i; make_blocking (ws->sock); while (1) { got = recv (ws->sock, (void *) buf, sizeof (buf), 0); if (0 >= got) { break; } msg = ws_receive_frame (buf, &got, &type); if (NULL == msg) { break; } if (type == WS_OPCODE_TEXT_FRAME) { ssize_t sent; int buf_size; buf_size = snprintf (NULL, 0, "User#%d: %s", (int) ws->sock, msg); if (0 < buf_size) { text = malloc ((size_t) buf_size + 1); if (NULL != text) { if (snprintf (text, (size_t) buf_size + 1, "User#%d: %s", (int) ws->sock, msg) == buf_size) sent = ws_send_frame (ws->sock, text, (size_t) buf_size); else sent = -1; free (text); } else sent = -1; } else sent = -1; free (msg); if (-1 == sent) { break; } } else { if (type == WS_OPCODE_CON_CLOSE_FRAME) { free (msg); break; } } } if (0 != pthread_mutex_lock (&MUTEX)) abort (); for (i = 0; i < MAX_CLIENTS; i++) { if (CLIENT_SOCKS[i] == ws->sock) { CLIENT_SOCKS[i] = MHD_INVALID_SOCKET; break; } } if (0 != pthread_mutex_unlock (&MUTEX)) abort (); free (ws); MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return NULL; } static void uh_cb (void *cls, struct MHD_Connection *con, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { struct WsData *ws; pthread_t pt; int sock_overflow; int i; (void) cls; /* Unused. Silent compiler warning. */ (void) con; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ (void) extra_in; /* Unused. Silent compiler warning. */ (void) extra_in_size; /* Unused. Silent compiler warning. */ ws = malloc (sizeof (struct WsData)); if (NULL == ws) abort (); memset (ws, 0, sizeof (struct WsData)); ws->sock = sock; ws->urh = urh; sock_overflow = MHD_YES; if (0 != pthread_mutex_lock (&MUTEX)) abort (); for (i = 0; i < MAX_CLIENTS; i++) { if (MHD_INVALID_SOCKET == CLIENT_SOCKS[i]) { CLIENT_SOCKS[i] = ws->sock; sock_overflow = MHD_NO; break; } } if (0 != pthread_mutex_unlock (&MUTEX)) abort (); if (sock_overflow) { free (ws); MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return; } if (0 != pthread_create (&pt, NULL, &run_usock, ws)) abort (); /* Note that by detaching like this we make it impossible to ensure a clean shutdown, as the we stop the daemon even if a worker thread is still running. Alas, this is a simple example... */ pthread_detach (pt); } static enum MHD_Result ahc_cb (void *cls, struct MHD_Connection *con, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *res; const char *upg_header; const char *con_header; const char *ws_version_header; const char *ws_key_header; char *ws_ac_value; enum MHD_Result ret; size_t key_size; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { *req_cls = (void *) 1; return MHD_YES; } *req_cls = NULL; upg_header = MHD_lookup_connection_value (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE); con_header = MHD_lookup_connection_value (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (MHD_NO == is_websocket_request (con, upg_header, con_header)) { return send_chat_page (con); } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) || (0 != strcmp (version, MHD_HTTP_VERSION_1_1))) { return send_bad_request (con); } ws_version_header = MHD_lookup_connection_value (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION); if ((NULL == ws_version_header) || (0 != strcmp (ws_version_header, WS_SEC_WEBSOCKET_VERSION))) { return send_upgrade_required (con); } ret = MHD_lookup_connection_value_n (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY, strlen ( MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY), &ws_key_header, &key_size); if ((MHD_NO == ret) || (key_size != WS_KEY_LEN)) { return send_bad_request (con); } ret = ws_get_accept_value (ws_key_header, &ws_ac_value); if (MHD_NO == ret) { return ret; } res = MHD_create_response_for_upgrade (&uh_cb, NULL); if (MHD_YES != MHD_add_response_header (res, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT, ws_ac_value)) { free (ws_ac_value); MHD_destroy_response (res); return MHD_NO; } free (ws_ac_value); if (MHD_YES != MHD_add_response_header (res, MHD_HTTP_HEADER_UPGRADE, WS_UPGRADE_VALUE)) { MHD_destroy_response (res); return MHD_NO; } ret = MHD_queue_response (con, MHD_HTTP_SWITCHING_PROTOCOLS, res); MHD_destroy_response (res); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; size_t i; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO_INTERNAL_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_cb, NULL, MHD_OPTION_END); if (NULL == d) return 1; for (i = 0; i < sizeof(CLIENT_SOCKS) / sizeof(CLIENT_SOCKS[0]); ++i) CLIENT_SOCKS[i] = MHD_INVALID_SOCKET; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/msgs_i18n.c0000644000175000017500000000603414760713574015701 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017 Christian Grothoff, Silvio Clecio (silvioprog) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file msgs_i18n.c * @brief example for how to use translate libmicrohttpd messages * @author Christian Grothoff * @author Silvio Clecio (silvioprog) */ /* * supposing you are in Brazil: * * # generate the PO file * $ msginit --input=po/libmicrohttpd.pot --locale=pt_BR --output=libmicrohttpd.po * # open the generated .po in any program like Poedit and translate the MHD messages; once done, let's go to the test: * mkdir -p src/examples/locale/pt_BR/LC_MESSAGES * mv libmicrohttpd.mo libmicrohttpd.po src/examples/locale/pt_BR/LC_MESSAGES * cd src/examples/ * gcc -o msgs_i18n msgs_i18n.c -lmicrohttpd * export LANGUAGE=pt_BR * ./msgs_i18n * # it may print: Opção inválida 4196490! (Você terminou a lista com MHD_OPTION_END?) */ #include #include #include #include static int ahc_echo (void *cls, struct MHD_Connection *cnc, const char *url, const char *mt, const char *ver, const char *upd, size_t *upsz, void **req_cls) { return MHD_NO; } static void error_handler (void *cls, const char *fm, va_list ap) { /* Here we do the translation using GNU gettext. As the error message is from libmicrohttpd, we specify "libmicrohttpd" as the translation domain here. */ vprintf (dgettext ("libmicrohttpd", fm), ap); } int main (int argc, char **argv) { setlocale (LC_ALL, ""); /* The example uses PO files in the directory "libmicrohttpd/src/examples/locale". This needs to be adapted to match where the MHD PO files are installed. */ bindtextdomain ("libmicrohttpd", "locale"); MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_FEATURE_MESSAGES | MHD_USE_ERROR_LOG, 8080, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_EXTERNAL_LOGGER, &error_handler, NULL, 99999 /* invalid option, to raise the error "Invalid option ..." which we are going to translate */); return 1; /* This program won't "succeed"... */ } libmicrohttpd-1.0.2/src/examples/Makefile.am0000644000175000017500000001470315035214304015742 00000000000000# This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) MHD_CPU_COUNT_DEF = -DMHD_CPU_COUNT=$(CPU_COUNT) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # example programs noinst_PROGRAMS = \ benchmark \ benchmark_https \ chunked_example \ minimal_example \ minimal_example_empty \ dual_stack_example \ minimal_example_comet \ querystring_example \ timeout \ fileserver_example \ fileserver_example_dirs \ fileserver_example_external_select \ refuse_post_example if HAVE_EXPERIMENTAL noinst_PROGRAMS += \ websocket_chatserver_example endif if MHD_HAVE_EPOLL noinst_PROGRAMS += \ suspend_resume_epoll endif if HAVE_JANSSON noinst_PROGRAMS += \ json_echo endif EXTRA_DIST = msgs_i18n.c noinst_EXTRA_DIST = msgs_i18n.c if ENABLE_HTTPS noinst_PROGRAMS += \ https_fileserver_example \ minimal_example_empty_tls endif if HAVE_POSTPROCESSOR noinst_PROGRAMS += \ post_example if HAVE_POSIX_THREADS noinst_PROGRAMS += demo if ENABLE_HTTPS noinst_PROGRAMS += demo_https endif endif endif if ENABLE_DAUTH noinst_PROGRAMS += \ digest_auth_example \ digest_auth_example_adv endif if ENABLE_BAUTH noinst_PROGRAMS += \ authorization_example endif if HAVE_POSIX_THREADS if ENABLE_UPGRADE noinst_PROGRAMS += \ upgrade_example \ websocket_threaded_example endif endif if HAVE_ZLIB noinst_PROGRAMS += \ http_compression \ http_chunked_compression endif if HAVE_W32 AM_CFLAGS += -DWINDOWS endif minimal_example_SOURCES = \ minimal_example.c minimal_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_SOURCES = \ minimal_example_empty.c minimal_example_empty_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_tls_SOURCES = \ minimal_example_empty_tls.c minimal_example_empty_tls_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la upgrade_example_SOURCES = \ upgrade_example.c upgrade_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) upgrade_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) websocket_threaded_example_SOURCES = \ websocket_threaded_example.c websocket_threaded_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) websocket_threaded_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) timeout_SOURCES = \ timeout.c timeout_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la chunked_example_SOURCES = \ chunked_example.c chunked_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la json_echo_SOURCES = \ json_echo.c json_echo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ -ljansson websocket_chatserver_example_SOURCES = \ websocket_chatserver_example.c websocket_chatserver_example_LDADD = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la demo_SOURCES = \ demo.c demo_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) if MHD_HAVE_LIBMAGIC demo_LDADD += -lmagic endif demo_https_SOURCES = \ demo_https.c demo_https_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) if MHD_HAVE_LIBMAGIC demo_https_LDADD += -lmagic endif benchmark_SOURCES = \ benchmark.c benchmark_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la suspend_resume_epoll_SOURCES = \ suspend_resume_epoll.c suspend_resume_epoll_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) suspend_resume_epoll_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la benchmark_https_SOURCES = \ benchmark_https.c benchmark_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la dual_stack_example_SOURCES = \ dual_stack_example.c dual_stack_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la post_example_SOURCES = \ post_example.c post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_comet_SOURCES = \ minimal_example_comet.c minimal_example_comet_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la authorization_example_SOURCES = \ authorization_example.c authorization_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_SOURCES = \ digest_auth_example.c digest_auth_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_adv_SOURCES = \ digest_auth_example_adv.c digest_auth_example_adv_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la refuse_post_example_SOURCES = \ refuse_post_example.c refuse_post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la querystring_example_SOURCES = \ querystring_example.c querystring_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_SOURCES = \ fileserver_example.c fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_dirs_SOURCES = \ fileserver_example_dirs.c fileserver_example_dirs_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_external_select_SOURCES = \ fileserver_example_external_select.c fileserver_example_external_select_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la https_fileserver_example_SOURCES = \ https_fileserver_example.c https_fileserver_example_CPPFLAGS = \ $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS) https_fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_compression_SOURCES = \ http_compression.c http_chunked_compression_SOURCES = \ http_chunked_compression.c http_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_chunked_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la if HAVE_ZLIB http_compression_LDADD += -lz http_chunked_compression_LDADD += -lz endif libmicrohttpd-1.0.2/src/examples/http_compression.c0000644000175000017500000001222114760713574017464 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019 Christian Grothoff (and other contributing authors) Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file http_compression.c * @brief minimal example for how to compress HTTP response * @author Silvio Clecio (silvioprog) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #define PAGE \ "HTTP compressionHello, " \ "hello, hello. This is a 'hello world' message for the world, " \ "repeat, for the world." static enum MHD_Result can_compress (struct MHD_Connection *con) { const char *ae; const char *de; ae = MHD_lookup_connection_value (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_ENCODING); if (NULL == ae) return MHD_NO; if (0 == strcmp (ae, "*")) return MHD_YES; de = strstr (ae, "deflate"); if (NULL == de) return MHD_NO; if (((de == ae) || (de[-1] == ',') || (de[-1] == ' ')) && ((de[strlen ("deflate")] == '\0') || (de[strlen ("deflate")] == ',') || (de[strlen ("deflate")] == ';'))) return MHD_YES; return MHD_NO; } static enum MHD_Result body_compress (void **buf, size_t *buf_size) { Bytef *cbuf; uLongf cbuf_size; int ret; cbuf_size = compressBound ((uLong) * buf_size); cbuf = malloc (cbuf_size); if (NULL == cbuf) return MHD_NO; ret = compress (cbuf, &cbuf_size, (const Bytef *) *buf, (uLong) * buf_size); if ((Z_OK != ret) || (cbuf_size >= *buf_size)) { /* compression failed */ free (cbuf); return MHD_NO; } free (*buf); *buf = (void *) cbuf; *buf_size = (size_t) cbuf_size; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; enum MHD_Result comp; size_t body_len; char *body_str; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (! *req_cls) { *req_cls = (void *) 1; return MHD_YES; } *req_cls = NULL; body_str = strdup (PAGE); if (NULL == body_str) { return MHD_NO; } body_len = strlen (body_str); /* try to compress the body */ comp = MHD_NO; if (MHD_YES == can_compress (connection)) comp = body_compress ((void **) &body_str, &body_len); response = MHD_create_response_from_buffer_with_free_callback (body_len, body_str, &free); if (NULL == response) { free (body_str); return MHD_NO; } if (MHD_YES == comp) { /* Need to indicate to client that body is compressed */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "deflate")) { MHD_destroy_response (response); return MHD_NO; } } ret = MHD_queue_response (connection, 200, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/post_example.c0000644000175000017500000005436414760713574016602 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2011 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file post_example.c * @brief example for processing POST requests using libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include #include #include #include #include #include /** * Invalid method page. */ #define METHOD_ERROR \ "Illegal requestGo away." /** * Invalid URL page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * Front page. (/) */ #define MAIN_PAGE \ "Welcome
    What is your name?
    " /** * Second page. (/2) */ #define SECOND_PAGE \ "Tell me moreprevious
    %s, what is your job?
    " /** * Second page (/S) */ #define SUBMIT_PAGE \ "Ready to submit?
    previous
    " /** * Last page. */ #define LAST_PAGE \ "Thank youThank you." /** * Name of our cookie. */ #define COOKIE_NAME "session" /** * State we keep for each user/session/browser. */ struct Session { /** * We keep all sessions in a linked list. */ struct Session *next; /** * Unique ID for this session. */ char sid[33]; /** * Reference counter giving the number of connections * currently using this session. */ unsigned int rc; /** * Time when this session was last active. */ time_t start; /** * String submitted via form. */ char value_1[64]; /** * Another value submitted via form. */ char value_2[64]; }; /** * Data kept per request. */ struct Request { /** * Associated session. */ struct Session *session; /** * Post processor handling form data (IF this is * a POST request). */ struct MHD_PostProcessor *pp; /** * URL to serve in response to this POST (if this request * was a 'POST') */ const char *post_url; }; /** * Linked list of all active sessions. Yes, O(n) but a * hash table would be overkill for a simple example... */ static struct Session *sessions; /** * Return the session handle for this connection, or * create one if this is a new user. */ static struct Session * get_session (struct MHD_Connection *connection) { struct Session *ret; const char *cookie; cookie = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, COOKIE_NAME); if (cookie != NULL) { /* find existing session */ ret = sessions; while (NULL != ret) { if (0 == strcmp (cookie, ret->sid)) break; ret = ret->next; } if (NULL != ret) { ret->rc++; return ret; } } /* create fresh session */ ret = calloc (1, sizeof (struct Session)); if (NULL == ret) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return NULL; } /* not a super-secure way to generate a random session ID, but should do for a simple example... */ snprintf (ret->sid, sizeof (ret->sid), "%X%X%X%X", (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand ()); ret->rc++; ret->start = time (NULL); ret->next = sessions; sessions = ret; return ret; } /** * Type of handler that generates a reply. * * @param cls content for the page (handler-specific) * @param mime mime type to use * @param session session information * @param connection connection to process * @param #MHD_YES on success, #MHD_NO on failure */ typedef enum MHD_Result (*PageHandler)(const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection); /** * Entry we generate for each page served. */ struct Page { /** * Acceptable URL for this page. */ const char *url; /** * Mime type to set for the page. */ const char *mime; /** * Handler to call to generate response. */ PageHandler handler; /** * Extra argument to handler. */ const void *handler_cls; }; /** * Add header to response to set a session cookie. * * @param session session to use * @param response response to modify */ static void add_session_cookie (struct Session *session, struct MHD_Response *response) { char cstr[256]; snprintf (cstr, sizeof (cstr), "%s=%s", COOKIE_NAME, session->sid); if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE, cstr)) { fprintf (stderr, "Failed to set session cookie header!\n"); } } /** * Handler that returns a simple static HTTP page that * is passed in via 'cls'. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result serve_simple_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; const char *form = cls; struct MHD_Response *response; /* return static form */ response = MHD_create_response_from_buffer_static (strlen (form), (const void *) form); if (NULL == response) return MHD_NO; add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' value to the given HTML code. * * @param cls unused * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; size_t slen; char *reply; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ slen = strlen (MAIN_PAGE) + strlen (session->value_1); reply = malloc (slen + 1); if (NULL == reply) return MHD_NO; snprintf (reply, slen + 1, MAIN_PAGE, session->value_1); /* return static form */ response = MHD_create_response_from_buffer_with_free_callback (slen, (void *) reply, &free); if (NULL == response) { free (reply); return MHD_NO; } add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' and 'v2' values to the given HTML code. * * @param cls unused * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_v2_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; size_t slen; (void) cls; /* Unused. Silent compiler warning. */ slen = strlen (SECOND_PAGE) + strlen (session->value_1) + strlen (session->value_2); reply = malloc (slen + 1); if (NULL == reply) return MHD_NO; snprintf (reply, slen + 1, SECOND_PAGE, session->value_1, session->value_2); /* return static form */ response = MHD_create_response_from_buffer_with_free_callback (slen, (void *) reply, &free); if (NULL == response) { free (reply); return MHD_NO; } add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler used to generate a 404 reply. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result not_found_page (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) session; /* Unused. Silent compiler warning. */ /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), (const void *) NOT_FOUND_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * List of all pages served by this HTTP server. */ static struct Page pages[] = { { "/", "text/html", &fill_v1_form, NULL }, { "/2", "text/html", &fill_v1_v2_form, NULL }, { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE }, { "/F", "text/html", &serve_simple_form, LAST_PAGE }, { NULL, NULL, ¬_found_page, NULL } /* 404 */ }; /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return MHD_YES to continue iterating, * MHD_NO to abort the iteration */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; struct Session *session = request->session; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ if (0 == strcmp ("DONE", key)) { fprintf (stdout, "Session `%s' submitted `%s', `%s'\n", session->sid, session->value_1, session->value_2); return MHD_YES; } if (0 == strcmp ("v1", key)) { if (off >= sizeof(session->value_1) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_1)) size = (size_t) (sizeof (session->value_1) - off - 1); /* crop extra data */ memcpy (&session->value_1[off], data, size); session->value_1[size + off] = '\0'; return MHD_YES; } if (0 == strcmp ("v2", key)) { if (off >= sizeof(session->value_2) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_2)) size = (size_t) (sizeof (session->value_2) - off - 1); /* crop extra data */ memcpy (&session->value_2[off], data, size); session->value_2[size + off] = '\0'; return MHD_YES; } fprintf (stderr, "Unsupported form value `%s'\n", key); return MHD_YES; } /** * Main MHD callback for handling requests. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle identifying the incoming connection * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; struct Request *request; struct Session *session; enum MHD_Result ret; unsigned int i; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ request = *req_cls; if (NULL == request) { request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { request->pp = MHD_create_post_processor (connection, 1024, &post_iterator, request); if (NULL == request->pp) { fprintf (stderr, "Failed to setup post processor for `%s'\n", url); return MHD_NO; /* internal error */ } } return MHD_YES; } if (NULL == request->session) { request->session = get_session (connection); if (NULL == request->session) { fprintf (stderr, "Failed to setup session for `%s'\n", url); return MHD_NO; /* internal error */ } } session = request->session; session->start = time (NULL); if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* evaluate POST data */ if (MHD_YES != MHD_post_process (request->pp, upload_data, *upload_data_size)) return MHD_NO; if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } /* done with POST data, serve response */ MHD_destroy_post_processor (request->pp); request->pp = NULL; method = MHD_HTTP_METHOD_GET; /* fake 'GET' */ if (NULL != request->post_url) url = request->post_url; } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { /* find out which page to serve */ i = 0; while ( (pages[i].url != NULL) && (0 != strcmp (pages[i].url, url)) ) i++; ret = pages[i].handler (pages[i].handler_cls, pages[i].mime, session, connection); if (ret != MHD_YES) fprintf (stderr, "Failed to create page for `%s'\n", url); return ret; } /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (METHOD_ERROR), (const void *) METHOD_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_NOT_ACCEPTABLE, response); MHD_destroy_response (response); return ret; } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == request) return; if (NULL != request->session) request->session->rc--; if (NULL != request->pp) MHD_destroy_post_processor (request->pp); free (request); } /** * Clean up handles of sessions that have been idle for * too long. */ static void expire_sessions (void) { struct Session *pos; struct Session *prev; struct Session *next; time_t now; now = time (NULL); prev = NULL; pos = sessions; while (NULL != pos) { next = pos->next; if (now - pos->start > 60 * 60) { /* expire sessions after 1h */ if (NULL == prev) sessions = pos->next; else prev->next = next; free (pos); } else prev = pos; pos = next; } } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { expire_sessions (); max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.2/src/examples/digest_auth_example_adv.c0000644000175000017500000010075114760713574020737 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digest_auth_example_adv.c * @brief Advanced example for digest auth with libmicrohttpd * @author Karlson2k (Evgeny Grin) */ #include #include #include #include #include #if ! defined(_WIN32) || defined(__CYGWIN__) # include # include # include #else /* Native W32 */ # include #endif /* Native W32 */ #define SEC_AREA1_URL "/secret_page/" #define SEC_AREA2_URL "/super_secret_page/" #define MAIN_PAGE \ "Welcome to the site" \ "

    Restricted Page

    " \ "

    Very Restricted Page

    " #define OPAQUE_DATA "ServerOpaqueData" #define REALM "authenticated_users@thishost" /** * Force select "MD5" algorithm instead of MHD default (currently the same) if non-zero. */ static int force_md5 = 0; /** * Force select "SHA-256" algorithm instead of MHD default (MD5) if non-zero. */ static int force_sha256 = 0; /** * Force select "SHA-512/256" algorithm instead of MHD default (MD5) if non-zero. */ static int force_sha512_256 = 0; /** * Disable fallback to (less secure) RFC2069 if non-zero. */ static int allow_rfc2069 = 0; /** * The daemon's port */ static uint16_t daemon_port = 0; /* *** "Database" of users and "database" functions *** */ /** * User record. * This kind of data (or something similar) should be stored in some database * or file. */ struct UserEntry { /** * The username. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *username; #if 0 /* Disabled code */ /* The cleartext password is not stored in the database. The more secure "userdigest" is used instead. */ /** * The password. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *password; #endif /* Disabled code */ /** * The realm for this entry. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *realm; /** * The MD5 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_md5[MHD_MD5_DIGEST_SIZE]; /** * The MD5 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_md5[MHD_MD5_DIGEST_SIZE]; /** * The SHA-256 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_sha256[MHD_SHA256_DIGEST_SIZE]; /** * The SHA-256 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_sha256[MHD_SHA256_DIGEST_SIZE]; /** * The SHA-512/256 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_sha512_256[MHD_SHA512_256_DIGEST_SIZE]; /** * The SHA-512/256 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_sha512_256[MHD_SHA512_256_DIGEST_SIZE]; /** * User has access to "area 1" if non-zero */ int allow_area_1; /** * User has access to "area 2" if non-zero */ int allow_area_2; }; /** * The array of user entries. * In real application it should be loaded from external sources * at the application startup. */ static struct UserEntry user_ids[2]; /** * The number of entries used in @a user_ids. */ static size_t user_ids_used = 0; /** * Add new user to the users database/array. * * This kind of function must be used only when the new user is introduced. * It must not be used at the every start of the application. The database * of users should be stored somewhere and reloaded when application is * started. * * @param username the username of the new user * @param password the password of the new user * @param realm the realm (the protection space) for which the new user * is added * @param allow_area_1 if non-zero than user has access to the "area 1" * @param allow_area_2 if non-zero than user has access to the "area 2" * @return non-zero on success, * zero on failure (like no more space in the database). */ static int add_new_user_entry (const char *const username, const char *const password, const char *const realm, int allow_area_1, int allow_area_2) { struct UserEntry *entry; enum MHD_Result res; if ((sizeof(user_ids) / sizeof(user_ids[0])) <= user_ids_used) return 0; /* No more space to add new entry */ entry = user_ids + user_ids_used; entry->username = username; entry->realm = realm; res = MHD_YES; if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_MD5, username, realm, entry->userhash_md5, sizeof(entry->userhash_md5)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_MD5, username, realm, password, entry->userdigest_md5, sizeof(entry->userdigest_md5)); if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_SHA256, username, realm, entry->userhash_sha256, sizeof(entry->userhash_sha256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_SHA256, username, realm, password, entry->userdigest_sha256, sizeof(entry->userdigest_sha256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_SHA512_256, username, realm, entry->userhash_sha512_256, sizeof(entry->userhash_sha512_256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_SHA512_256, username, realm, password, entry->userdigest_sha512_256, sizeof(entry->userdigest_sha512_256)); if (MHD_NO == res) return 0; /* Failure exit point */ entry->allow_area_1 = allow_area_1; entry->allow_area_2 = allow_area_2; user_ids_used++; return ! 0; } /** * Find the user entry for specified username * @param username the username to find * @return NULL if no entry for specified username is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_username (const char *const username) { size_t i; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == strcmp (username, entry->username)) return entry; } return NULL; } /** * Find the user entry for specified userhash * @param algo3 the algorithm used for userhash calculation * @param userhash the userhash identifier to find * @param userhash_size the size @a userhash in bytes * @return NULL if no entry for specified userhash is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_userhash (enum MHD_DigestAuthAlgo3 algo3, const void *userhash, size_t userhash_size) { size_t i; if (MHD_digest_get_hash_size (algo3) != userhash_size) return NULL; /* Wrong length of the userhash */ switch (algo3) { case MHD_DIGEST_AUTH_ALGO3_MD5: case MHD_DIGEST_AUTH_ALGO3_MD5_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_md5) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_md5, sizeof(entry->userhash_md5))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_SHA256: case MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_sha256) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_sha256, sizeof(entry->userhash_sha256))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_SHA512_256: case MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_sha512_256) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_sha512_256, sizeof(entry->userhash_sha512_256))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_INVALID: /* Mute compiler warning. Impossible value in this context. */ default: break; } return NULL; } /** * Find the user entry for the user specified by provided username info * @param user_info the pointer to the structure username info returned by MHD * @return NULL if no entry for specified username info is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_userinfo (const struct MHD_DigestAuthUsernameInfo *username_info) { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD <= username_info->uname_type) return find_entry_by_username (username_info->username); if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == username_info->uname_type) return find_entry_by_userhash (username_info->algo3, username_info->userhash_bin, username_info->userhash_hex_len / 2); return NULL; /* Should be unreachable as all cases are covered before */ } /* *** End of "database" of users and "database" functions *** */ /* *** Requests handling *** */ /** * Send "Requested HTTP method is not supported" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_page_not_found (struct MHD_Connection *c) { static const char page_content[] = "Page Not Found" \ "The requested page not found."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_NOT_FOUND, resp); MHD_destroy_response (resp); return ret; } /** * Get enum MHD_DigestAuthMultiAlgo3 value to be used for authentication. * @return the algorithm number/value */ static enum MHD_DigestAuthMultiAlgo3 get_m_algo (void) { if (force_md5) return MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (force_sha256) return MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else if (force_sha512_256) return MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256; /* No forced algorithm selection, let MHD to use default */ return MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; } /** * Get enum MHD_DigestAuthMultiQOP value to be used for authentication. * @return the "Quality Of Protection" number/value */ static enum MHD_DigestAuthMultiQOP get_m_QOP (void) { if (allow_rfc2069) return MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT; return MHD_DIGEST_AUTH_MULT_QOP_AUTH; } /** * Send "Authentication required" page * @param c the connection structure * @param stale if non-zero then "nonce stale" is indicated in the reply * @param wrong_cred if non-zero then client is informed the previously * it used wrong credentials * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_auth_required (struct MHD_Connection *c, int stale, int wrong_cred) { static const char auth_required_content[] = "Authentication required" \ "The requested page needs authentication."; static const size_t auth_required_content_len = (sizeof(auth_required_content) / sizeof(char)) - 1; static const char wrong_creds_content[] = "Wrong credentials" \ "The provided credentials are incorrect."; static const size_t wrong_creds_content_len = (sizeof(wrong_creds_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; if (wrong_cred) stale = 0; /* Force client to ask user for username and password */ if (! wrong_cred) resp = MHD_create_response_from_buffer_static (auth_required_content_len, auth_required_content); else resp = MHD_create_response_from_buffer_static (wrong_creds_content_len, wrong_creds_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_auth_required_response3 ( c, REALM, OPAQUE_DATA, /* The "opaque data", not really useful */ SEC_AREA1_URL " " SEC_AREA2_URL, /* Space-separated list of URLs' initial parts */ resp, stale, get_m_QOP (), get_m_algo (), ! 0, /* Userhash support enabled */ ! 0 /* UTF-8 is preferred */); MHD_destroy_response (resp); return ret; } /** * Send "Forbidden" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_forbidden (struct MHD_Connection *c) { static const char page_content[] = "Forbidden" \ "You do not have access to this page."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_FORBIDDEN, resp); MHD_destroy_response (resp); return ret; } /** * Send "Area 1" pages * @param c the connection structure * @param url the requested URL * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_area1_pages (struct MHD_Connection *c, const char *url) { if (0 == strcmp (url, SEC_AREA1_URL "")) { static const char page_content[] = "Restricted secret page" \ "Welcome to the restricted area"; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /* If needed: add handlers for other URLs in this area */ #if 0 /* Disabled code */ if (0 == strcmp (url, SEC_AREA1_URL "some_path/some_page")) { /* Add page creation/processing code */ } #endif /* Disabled code */ /* The requested URL is unknown */ return reply_with_page_not_found (c); } /** * Send "Area 2" pages * @param c the connection structure * @param url the requested URL * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_area2_pages (struct MHD_Connection *c, const char *url) { if (0 == strcmp (url, SEC_AREA2_URL "")) { static const char page_content[] = "Very restricted secret page" \ "Welcome to the super restricted area"; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /* If needed: add handlers for other URLs in this area */ #if 0 /* Disabled code */ if (0 == strcmp (url, SEC_AREA2_URL "other_path/other_page")) { /* Add page creation/processing code */ } #endif /* Disabled code */ /* The requested URL is unknown */ return reply_with_page_not_found (c); } /** * Handle client's request for secured areas * @param c the connection structure * @param url the URL requested by the client * @param sec_area_num the number of secured area * @return MHD_YES if request was handled (either with "denied" or with * "allowed" result), * MHD_NO if it was an error handling the request. */ static enum MHD_Result handle_sec_areas_req (struct MHD_Connection *c, const char *url, unsigned int sec_area_num) { struct MHD_DigestAuthUsernameInfo *username_info; struct UserEntry *user_entry; void *userdigest; size_t userdigest_size; enum MHD_DigestAuthResult auth_res; username_info = MHD_digest_auth_get_username3 (c); if (NULL == username_info) return reply_with_auth_required (c, 0, 0); user_entry = find_entry_by_userinfo (username_info); if (NULL == user_entry) return reply_with_auth_required (c, 0, 1); switch (username_info->algo3) { case MHD_DIGEST_AUTH_ALGO3_MD5: userdigest = user_entry->userdigest_md5; userdigest_size = sizeof(user_entry->userdigest_md5); break; case MHD_DIGEST_AUTH_ALGO3_SHA256: userdigest = user_entry->userdigest_sha256; userdigest_size = sizeof(user_entry->userdigest_sha256); break; case MHD_DIGEST_AUTH_ALGO3_SHA512_256: userdigest = user_entry->userdigest_sha512_256; userdigest_size = sizeof(user_entry->userdigest_sha512_256); break; case MHD_DIGEST_AUTH_ALGO3_MD5_SESSION: case MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION: case MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION: /* Not supported currently and not used by MHD. The client incorrectly used algorithm not advertised by the server. */ return reply_with_auth_required (c, 0, 1); case MHD_DIGEST_AUTH_ALGO3_INVALID: /* Mute compiler warning */ default: return MHD_NO; /* Should be unreachable */ } auth_res = MHD_digest_auth_check_digest3 ( c, REALM, /* Make sure to use the proper realm, not the realm provided by the client and returned by "user_entry" */ user_entry->username, userdigest, userdigest_size, 0, /* Use daemon's default value for nonce_timeout*/ 0, /* Use daemon's default value for max_nc */ get_m_QOP (), (enum MHD_DigestAuthMultiAlgo3) username_info->algo3 /* Direct cast from "single algorithm" to "multi-algorithm" is allowed */ ); if (MHD_DAUTH_OK != auth_res) { int need_just_refresh_nonce; /* Actually MHD_DAUTH_NONCE_OTHER_COND should not be returned as MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE is not used for the daemon. To keep the code universal the MHD_DAUTH_NONCE_OTHER_COND is still checked here. */ need_just_refresh_nonce = (MHD_DAUTH_NONCE_STALE == auth_res) || (MHD_DAUTH_NONCE_OTHER_COND == auth_res); return reply_with_auth_required (c, need_just_refresh_nonce, ! need_just_refresh_nonce); } /* The user successfully authenticated */ /* Check whether access to the request area is allowed for the user */ if (1 == sec_area_num) { if (user_entry->allow_area_1) return reply_with_area1_pages (c, url); else return reply_with_forbidden (c); } else if (2 == sec_area_num) { if (user_entry->allow_area_2) return reply_with_area2_pages (c, url); else return reply_with_forbidden (c); } return MHD_NO; /* Should be unreachable */ } /** * Send the main page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_main_page (struct MHD_Connection *c) { static const char page_content[] = MAIN_PAGE; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /** * Send "Requested HTTP method is not supported" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_method_not_supported (struct MHD_Connection *c) { static const char page_content[] = "Requested HTTP Method Is Not Supported" \ "The requested HTTP method is not supported."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_NOT_IMPLEMENTED, resp); MHD_destroy_response (resp); return ret; } static enum MHD_Result ahc_main (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int already_called_marker; size_t url_len; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return reply_with_method_not_supported (connection); if (0 != *upload_data_size) return MHD_NO; /* No upload expected for GET or HEAD */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 == strcmp (url, "/")) return reply_with_main_page (connection); url_len = strlen (url); if ((strlen (SEC_AREA1_URL) <= url_len) && (0 == memcmp (url, SEC_AREA1_URL, strlen (SEC_AREA1_URL)))) return handle_sec_areas_req (connection, url, 1); /* The requested URL is within SEC_AREA1_URL */ if ((strlen (SEC_AREA2_URL) <= url_len) && (0 == memcmp (url, SEC_AREA2_URL, strlen (SEC_AREA2_URL)))) return handle_sec_areas_req (connection, url, 2); /* The requested URL is within SEC_AREA2_URL */ return reply_with_page_not_found (connection); } /* *** End of requests handling *** */ /** * Add new users to the users "database". * * In real application this kind of function must NOT be called at * the application startup. Instead similar function should be * called only when new user is introduced. The users "database" * should be stored somewhere and reloaded at the application * startup. * * @return non-zero on success, * zero in case of error. */ static int add_new_users (void) { if (! add_new_user_entry ("joepublic", "password", REALM, ! 0, 0)) return 0; if (! add_new_user_entry ("superadmin", "pA$$w0Rd", REALM, ! 0, ! 0)) return 0; return ! 0; } /** * Check and apply application parameters * @param argc the argc of the @a main function * @param argv the argv of the @a main function * @return non-zero on success, * zero in case of any error (like wrong parameters). */ static int check_params (int argc, char *const *const argv) { size_t i; unsigned int port_value; if (2 > argc) return 0; for (i = 1; i < (unsigned int) argc; ++i) { if (0 == strcmp (argv[i], "--md5")) { /* Force use MD5 */ force_md5 = ! 0; force_sha256 = 0; force_sha512_256 = 0; } else if (0 == strcmp (argv[i], "--sha256")) { /* Force use SHA-256 instead of default MD5 */ force_md5 = 0; force_sha256 = ! 0; force_sha512_256 = 0; } else if (0 == strcmp (argv[i], "--sha512-256")) { /* Force use SHA-512/256 instead of default MD5 */ force_md5 = 0; force_sha256 = 0; force_sha512_256 = ! 0; } else if (0 == strcmp (argv[i], "--allow-rfc2069")) allow_rfc2069 = ! 0; /* Allow fallback to RFC2069. Not recommended! */ else if ((1 == sscanf (argv[i], "%u", &port_value)) && (0 < port_value) && (65535 >= port_value)) daemon_port = (uint16_t) port_value; else { fprintf (stderr, "Unrecognized parameter: %s\n", argv[i]); return 0; } } if (force_sha512_256) printf ( "Note: when testing with curl/libcurl do not be surprised with failures as " "libcurl incorrectly implements SHA-512/256 algorithm.\n"); return ! 0; } /** * The cryptographically secure random data */ static uint8_t rand_data[8]; /** * Initialise the random data * @return non-zero if succeed, * zero if failed */ static int init_rand_data (void) { #if ! defined(_WIN32) || defined(__CYGWIN__) int fd; ssize_t len; size_t off; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open '%s': %s\n", "/dev/urandom", strerror (errno)); return 0; } for (off = 0; off < sizeof(rand_data); off += (size_t) len) { len = read (fd, rand_data, 8); if (0 > len) { fprintf (stderr, "Failed to read '%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 0; } } (void) close (fd); #else /* Native W32 */ HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (FALSE == b) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", (unsigned long) GetLastError ()); return 0; } b = CryptGenRandom (cc, sizeof(rand_data), (BYTE *) rand_data); if (FALSE == b) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (FALSE == b) return 0; #endif /* Native W32 */ return ! 0; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; if (! check_params (argc, argv)) { fprintf (stderr, "Usage: %s [--md5|--sha256|--sha512-256] " "[--allow-rfc2069] PORT\n", argv[0]); return 1; } if (! add_new_users ()) { fprintf (stderr, "Failed to add new users to the users database.\n"); return 2; } if (! init_rand_data ()) { fprintf (stderr, "Failed to initialise random data.\n"); return 2; } d = MHD_start_daemon ( MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_ERROR_LOG, daemon_port, NULL, NULL, &ahc_main, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rand_data), rand_data, MHD_OPTION_NONCE_NC_SIZE, 500, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 180, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "Failed to start the server on port %lu.\n", (unsigned long) daemon_port); return 1; } printf ("Running server on port %lu.\nPress ENTER to stop.\n", (unsigned long) daemon_port); (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* End of digest_auth_example_adv.c */ libmicrohttpd-1.0.2/src/microhttpd_ws/0000755000175000017500000000000015035216652015041 500000000000000libmicrohttpd-1.0.2/src/microhttpd_ws/mhd_websocket.c0000644000175000017500000023773014760713574017770 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021 David Gausmann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd_ws/mhd_websocket.c * @brief Support for the websocket protocol * @author David Gausmann */ #include "platform.h" #include "microhttpd.h" #include "microhttpd_ws.h" #include "sha1.h" struct MHD_WebSocketStream { /* The function pointer to malloc for payload (can be used to use different memory management) */ MHD_WebSocketMallocCallback malloc; /* The function pointer to realloc for payload (can be used to use different memory management) */ MHD_WebSocketReallocCallback realloc; /* The function pointer to free for payload (can be used to use different memory management) */ MHD_WebSocketFreeCallback free; /* A closure for the random number generator (only used for client mode; usually not required) */ void *cls_rng; /* The random number generator (only used for client mode; usually not required) */ MHD_WebSocketRandomNumberGenerator rng; /* The flags specified upon initialization. It may alter the behavior of decoding/encoding */ int flags; /* The current step for the decoder. 0 means start of a frame. */ char decode_step; /* Specifies whether the stream is valid (1) or not (0), if a close frame has been received this is (-1) to indicate that no data frames are allowed anymore */ char validity; /* The current step of the UTF-8 encoding check in the data payload */ char data_utf8_step; /* The current step of the UTF-8 encoding check in the control payload */ char control_utf8_step; /* if != 0 means that we expect a CONTINUATION frame */ char data_type; /* The start of the current frame (may differ from data_payload for CONTINUATION frames) */ char *data_payload_start; /* The buffer for the data frame */ char *data_payload; /* The buffer for the control frame */ char *control_payload; /* Configuration for the maximum allowed buffer size for payload data */ size_t max_payload_size; /* The current frame header size */ size_t frame_header_size; /* The current data payload size (can be greater than payload_size for fragmented frames) */ size_t data_payload_size; /* The size of the payload of the current frame (control or data) */ size_t payload_size; /* The processing offset to the start of the payload of the current frame (control or data) */ size_t payload_index; /* The frame header of the current frame (control or data) */ char frame_header[32]; /* The mask key of the current frame (control or data); this is 0 if no masking used */ char mask_key[4]; }; #define MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT MHD_WEBSOCKET_FLAG_CLIENT #define MHD_WEBSOCKET_FLAG_MASK_FRAGMENTATION \ MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS #define MHD_WEBSOCKET_FLAG_MASK_GENERATE_CLOSE_FRAMES \ MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR #define MHD_WEBSOCKET_FLAG_MASK_ALL \ (MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT \ | MHD_WEBSOCKET_FLAG_MASK_FRAGMENTATION \ | MHD_WEBSOCKET_FLAG_MASK_GENERATE_CLOSE_FRAMES) enum MHD_WebSocket_Opcode { MHD_WebSocket_Opcode_Continuation = 0x0, MHD_WebSocket_Opcode_Text = 0x1, MHD_WebSocket_Opcode_Binary = 0x2, MHD_WebSocket_Opcode_Close = 0x8, MHD_WebSocket_Opcode_Ping = 0x9, MHD_WebSocket_Opcode_Pong = 0xA }; enum MHD_WebSocket_DecodeStep { MHD_WebSocket_DecodeStep_Start = 0, MHD_WebSocket_DecodeStep_Length1ofX = 1, MHD_WebSocket_DecodeStep_Length1of2 = 2, MHD_WebSocket_DecodeStep_Length2of2 = 3, MHD_WebSocket_DecodeStep_Length1of8 = 4, MHD_WebSocket_DecodeStep_Length2of8 = 5, MHD_WebSocket_DecodeStep_Length3of8 = 6, MHD_WebSocket_DecodeStep_Length4of8 = 7, MHD_WebSocket_DecodeStep_Length5of8 = 8, MHD_WebSocket_DecodeStep_Length6of8 = 9, MHD_WebSocket_DecodeStep_Length7of8 = 10, MHD_WebSocket_DecodeStep_Length8of8 = 11, MHD_WebSocket_DecodeStep_Mask1Of4 = 12, MHD_WebSocket_DecodeStep_Mask2Of4 = 13, MHD_WebSocket_DecodeStep_Mask3Of4 = 14, MHD_WebSocket_DecodeStep_Mask4Of4 = 15, MHD_WebSocket_DecodeStep_HeaderCompleted = 16, MHD_WebSocket_DecodeStep_PayloadOfDataFrame = 17, MHD_WebSocket_DecodeStep_PayloadOfControlFrame = 18, MHD_WebSocket_DecodeStep_BrokenStream = 99 }; enum MHD_WebSocket_UTF8Result { MHD_WebSocket_UTF8Result_Invalid = 0, MHD_WebSocket_UTF8Result_Valid = 1, MHD_WebSocket_UTF8Result_Incomplete = 2 }; static void MHD_websocket_copy_payload (char *dst, const char *src, size_t len, uint32_t mask, unsigned long mask_offset); static int MHD_websocket_check_utf8 (const char *buf, size_t buf_len, int *utf8_step, size_t *buf_offset); static enum MHD_WEBSOCKET_STATUS MHD_websocket_decode_header_complete (struct MHD_WebSocketStream *ws, char **payload, size_t *payload_len); static enum MHD_WEBSOCKET_STATUS MHD_websocket_decode_payload_complete (struct MHD_WebSocketStream *ws, char **payload, size_t *payload_len); static char MHD_websocket_encode_is_masked (struct MHD_WebSocketStream *ws); static char MHD_websocket_encode_overhead_size (struct MHD_WebSocketStream *ws, size_t payload_len); static enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_data (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, int fragmentation, char **frame, size_t *frame_len, char opcode); static enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_ping_pong (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len, char opcode); static uint32_t MHD_websocket_generate_mask (struct MHD_WebSocketStream *ws); static uint16_t MHD_htons (uint16_t value); static uint64_t MHD_htonll (uint64_t value); /** * Checks whether the HTTP version is 1.1 or above. */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_http_version (const char *http_version) { /* validate parameters */ if (NULL == http_version) { /* Like with the other check routines, */ /* NULL is threated as "value not given" and not as parameter error */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /* Check whether the version has a valid format */ /* RFC 1945 3.1: The format must be "HTTP/x.x" where x is */ /* any digit and must appear at least once */ if (('H' != http_version[0]) || ('T' != http_version[1]) || ('T' != http_version[2]) || ('P' != http_version[3]) || ('/' != http_version[4])) { return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /* Find the major and minor part of the version */ /* RFC 1945 3.1: Both numbers must be threated as separate integers. */ /* Leading zeros must be ignored and both integers may have multiple digits */ const char *major = NULL; const char *dot = NULL; size_t i = 5; for (;;) { char c = http_version[i]; if (('0' <= c) && ('9' >= c)) { if ((NULL == major) || ((http_version + i == major + 1) && ('0' == *major)) ) { major = http_version + i; } ++i; } else if ('.' == http_version[i]) { dot = http_version + i; ++i; break; } else { return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } } const char *minor = NULL; const char *end = NULL; for (;;) { char c = http_version[i]; if (('0' <= c) && ('9' >= c)) { if ((NULL == minor) || ((http_version + i == minor + 1) && ('0' == *minor)) ) { minor = http_version + i; } ++i; } else if (0 == c) { end = http_version + i; break; } else { return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } } if ((NULL == major) || (NULL == dot) || (NULL == minor) || (NULL == end)) { return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } if ((2 <= dot - major) || ('2' <= *major) || (('1' == *major) && ((2 <= end - minor) || ('1' <= *minor))) ) { return MHD_WEBSOCKET_STATUS_OK; } return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /** * Checks whether the "Connection" request header has the 'Upgrade' token. */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_connection_header (const char *connection_header) { /* validate parameters */ if (NULL == connection_header) { /* To be compatible with the return value */ /* of MHD_lookup_connection_value, */ /* NULL is threated as "value not given" and not as parameter error */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /* Check whether the Connection includes an Upgrade token */ /* RFC 7230 6.1: Multiple tokens may appear. */ /* RFC 7230 3.2.6: Tokens are comma separated */ const char *token_start = NULL; const char *token_end = NULL; for (size_t i = 0; ; ++i) { char c = connection_header[i]; /* RFC 7230 3.2.6: The list of allowed characters is a token is: */ /* "!" / "#" / "$" / "%" / "&" / "'" / "*" / */ /* "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" */ /* DIGIT / ALPHA */ if (('!' == c) || ('#' == c) || ('$' == c) || ('%' == c) || ('&' == c) || ('\'' == c) || ('*' == c) || ('+' == c) || ('-' == c) || ('.' == c) || ('^' == c) || ('_' == c) || ('`' == c) || ('|' == c) || ('~' == c) || (('0' <= c) && ('9' >= c)) || (('A' <= c) && ('Z' >= c)) || (('a' <= c) && ('z' >= c)) ) { /* This is a valid token character */ if (NULL == token_start) { token_start = connection_header + i; } token_end = connection_header + i + 1; } else if ((' ' == c) || ('\t' == c)) { /* White-spaces around tokens will be ignored */ } else if ((',' == c) || (0 == c)) { /* Check the token (case-insensitive) */ if (NULL != token_start) { if (7 == (token_end - token_start) ) { if ( (('U' == token_start[0]) || ('u' == token_start[0])) && (('P' == token_start[1]) || ('p' == token_start[1])) && (('G' == token_start[2]) || ('g' == token_start[2])) && (('R' == token_start[3]) || ('r' == token_start[3])) && (('A' == token_start[4]) || ('a' == token_start[4])) && (('D' == token_start[5]) || ('d' == token_start[5])) && (('E' == token_start[6]) || ('e' == token_start[6])) ) { /* The token equals to "Upgrade" */ return MHD_WEBSOCKET_STATUS_OK; } } } if (0 == c) { break; } token_start = NULL; token_end = NULL; } else { /* RFC 7230 3.2.6: Other characters are not allowed */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } } return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /** * Checks whether the "Upgrade" request header has the "websocket" keyword. */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_upgrade_header (const char *upgrade_header) { /* validate parameters */ if (NULL == upgrade_header) { /* To be compatible with the return value */ /* of MHD_lookup_connection_value, */ /* NULL is threated as "value not given" and not as parameter error */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /* Check whether the Connection includes an Upgrade token */ /* RFC 7230 6.1: Multiple tokens may appear. */ /* RFC 7230 3.2.6: Tokens are comma separated */ const char *keyword_start = NULL; const char *keyword_end = NULL; for (size_t i = 0; ; ++i) { char c = upgrade_header[i]; /* RFC 7230 3.2.6: The list of allowed characters is a token is: */ /* "!" / "#" / "$" / "%" / "&" / "'" / "*" / */ /* "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" */ /* DIGIT / ALPHA */ /* We also allow "/" here as the sub-delimiter for the protocol version */ if (('!' == c) || ('#' == c) || ('$' == c) || ('%' == c) || ('&' == c) || ('\'' == c) || ('*' == c) || ('+' == c) || ('-' == c) || ('.' == c) || ('^' == c) || ('_' == c) || ('`' == c) || ('|' == c) || ('~' == c) || ('/' == c) || (('0' <= c) && ('9' >= c)) || (('A' <= c) && ('Z' >= c)) || (('a' <= c) && ('z' >= c)) ) { /* This is a valid token character */ if (NULL == keyword_start) { keyword_start = upgrade_header + i; } keyword_end = upgrade_header + i + 1; } else if ((' ' == c) || ('\t' == c)) { /* White-spaces around tokens will be ignored */ } else if ((',' == c) || (0 == c)) { /* Check the token (case-insensitive) */ if (NULL != keyword_start) { if (9 == (keyword_end - keyword_start) ) { if ( (('W' == keyword_start[0]) || ('w' == keyword_start[0])) && (('E' == keyword_start[1]) || ('e' == keyword_start[1])) && (('B' == keyword_start[2]) || ('b' == keyword_start[2])) && (('S' == keyword_start[3]) || ('s' == keyword_start[3])) && (('O' == keyword_start[4]) || ('o' == keyword_start[4])) && (('C' == keyword_start[5]) || ('c' == keyword_start[5])) && (('K' == keyword_start[6]) || ('k' == keyword_start[6])) && (('E' == keyword_start[7]) || ('e' == keyword_start[7])) && (('T' == keyword_start[8]) || ('t' == keyword_start[8])) ) { /* The keyword equals to "websocket" */ return MHD_WEBSOCKET_STATUS_OK; } } } if (0 == c) { break; } keyword_start = NULL; keyword_end = NULL; } else { /* RFC 7230 3.2.6: Other characters are not allowed */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } } return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /** * Checks whether the "Sec-WebSocket-Version" request header * equals to "13" */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_check_version_header (const char *version_header) { /* validate parameters */ if (NULL == version_header) { /* To be compatible with the return value */ /* of MHD_lookup_connection_value, */ /* NULL is threated as "value not given" and not as parameter error */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } if (('1' == version_header[0]) && ('3' == version_header[1]) && (0 == version_header[2])) { /* The version equals to "13" */ return MHD_WEBSOCKET_STATUS_OK; } return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /** * Creates the response for the Sec-WebSocket-Accept header */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_create_accept_header (const char *sec_websocket_key, char *sec_websocket_accept) { /* initialize output variables for errors cases */ if (NULL != sec_websocket_accept) *sec_websocket_accept = 0; /* validate parameters */ if (NULL == sec_websocket_accept) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } if (NULL == sec_websocket_key) { /* NULL is not a parameter error, */ /* because MHD_lookup_connection_value returns NULL */ /* if the header wasn't found */ return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER; } /* build SHA1 hash of the given key and the UUID appended */ char sha1[20]; const char *suffix = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; int length = (int) strlen (sec_websocket_key); struct sha1_ctx ctx; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, (const uint8_t *) sec_websocket_key, length); MHD_SHA1_update (&ctx, (const uint8_t *) suffix, 36); MHD_SHA1_finish (&ctx, (uint8_t *) sha1); /* base64 encode that SHA1 hash */ /* (simple algorithm here; SHA1 has always 20 bytes, */ /* which will always result in a 28 bytes base64 hash) */ const char *base64_encoding_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (int i = 0, j = 0; i < 20;) { uint32_t octet_a = i < 20 ? (unsigned char) sha1[i++] : 0; uint32_t octet_b = i < 20 ? (unsigned char) sha1[i++] : 0; uint32_t octet_c = i < 20 ? (unsigned char) sha1[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; sec_websocket_accept[j++] = base64_encoding_table[(triple >> 3 * 6) & 0x3F]; sec_websocket_accept[j++] = base64_encoding_table[(triple >> 2 * 6) & 0x3F]; sec_websocket_accept[j++] = base64_encoding_table[(triple >> 1 * 6) & 0x3F]; sec_websocket_accept[j++] = base64_encoding_table[(triple >> 0 * 6) & 0x3F]; } sec_websocket_accept[27] = '='; sec_websocket_accept[28] = 0; return MHD_WEBSOCKET_STATUS_OK; } /** * Initializes a new websocket stream */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size) { return MHD_websocket_stream_init2 (ws, flags, max_payload_size, malloc, realloc, free, NULL, NULL); } /** * Initializes a new websocket stream with * additional parameters for allocation functions */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size, MHD_WebSocketMallocCallback callback_malloc, MHD_WebSocketReallocCallback callback_realloc, MHD_WebSocketFreeCallback callback_free, void *cls_rng, MHD_WebSocketRandomNumberGenerator callback_rng) { /* initialize output variables for errors cases */ if (NULL != ws) *ws = NULL; /* validate parameters */ if ((NULL == ws) || (0 != (flags & ~MHD_WEBSOCKET_FLAG_MASK_ALL)) || ((uint64_t) 0x7FFFFFFFFFFFFFFF < max_payload_size) || (NULL == callback_malloc) || (NULL == callback_realloc) || (NULL == callback_free) || ((0 != (flags & MHD_WEBSOCKET_FLAG_CLIENT)) && (NULL == callback_rng))) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* allocate stream */ struct MHD_WebSocketStream *ws_ = (struct MHD_WebSocketStream *) malloc ( sizeof (struct MHD_WebSocketStream)); if (NULL == ws_) return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; /* initialize stream */ memset (ws_, 0, sizeof (struct MHD_WebSocketStream)); ws_->flags = flags; ws_->max_payload_size = max_payload_size; ws_->malloc = callback_malloc; ws_->realloc = callback_realloc; ws_->free = callback_free; ws_->cls_rng = cls_rng; ws_->rng = callback_rng; ws_->validity = MHD_WEBSOCKET_VALIDITY_VALID; /* return stream */ *ws = ws_; return MHD_WEBSOCKET_STATUS_OK; } /** * Frees a previously allocated websocket stream */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_free (struct MHD_WebSocketStream *ws) { /* validate parameters */ if (NULL == ws) return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; /* free allocated payload data */ if (ws->data_payload) ws->free (ws->data_payload); if (ws->control_payload) ws->free (ws->control_payload); /* free the stream */ free (ws); return MHD_WEBSOCKET_STATUS_OK; } /** * Invalidates a websocket stream (no more decoding possible) */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws) { /* validate parameters */ if (NULL == ws) return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; /* invalidate stream */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; return MHD_WEBSOCKET_STATUS_OK; } /** * Returns whether a websocket stream is valid */ _MHD_EXTERN enum MHD_WEBSOCKET_VALIDITY MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws) { /* validate parameters */ if (NULL == ws) return MHD_WEBSOCKET_VALIDITY_INVALID; return ws->validity; } /** * Decodes incoming data to a websocket frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_decode (struct MHD_WebSocketStream *ws, const char *streambuf, size_t streambuf_len, size_t *streambuf_read_len, char **payload, size_t *payload_len) { /* initialize output variables for errors cases */ if (NULL != streambuf_read_len) *streambuf_read_len = 0; if (NULL != payload) *payload = NULL; if (NULL != payload_len) *payload_len = 0; /* validate parameters */ if ((NULL == ws) || ((NULL == streambuf) && (0 != streambuf_len)) || (NULL == streambuf_read_len) || (NULL == payload) || (NULL == payload_len) ) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* validate stream validity */ if (MHD_WEBSOCKET_VALIDITY_INVALID == ws->validity) return MHD_WEBSOCKET_STATUS_STREAM_BROKEN; /* decode loop */ size_t current = 0; while (current < streambuf_len) { switch (ws->decode_step) { /* start of frame */ case MHD_WebSocket_DecodeStep_Start: { /* The first byte contains the opcode, the fin flag and three reserved bits */ if (MHD_WEBSOCKET_VALIDITY_INVALID != ws->validity) { char opcode = streambuf [current]; if (0 != (opcode & 0x70)) { /* RFC 6455 5.2 RSV1-3: If a reserved flag is set */ /* (while it isn't specified by an extension) the communication must fail. */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } switch (opcode & 0x0F) { case MHD_WebSocket_Opcode_Continuation: if (0 == ws->data_type) { /* RFC 6455 5.4: Continuation frame without previous data frame */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if (MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES == ws->validity) { /* RFC 6455 5.5.1: After a close frame has been sent, */ /* no data frames may be sent (so we don't accept data frames */ /* for decoding anymore) */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } break; case MHD_WebSocket_Opcode_Text: case MHD_WebSocket_Opcode_Binary: if (0 != ws->data_type) { /* RFC 6455 5.4: Continuation expected, but new data frame */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if (MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES == ws->validity) { /* RFC 6455 5.5.1: After a close frame has been sent, */ /* no data frames may be sent (so we don't accept data frames */ /* for decoding anymore) */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } break; case MHD_WebSocket_Opcode_Close: case MHD_WebSocket_Opcode_Ping: case MHD_WebSocket_Opcode_Pong: if ((opcode & 0x80) == 0) { /* RFC 6455 5.4: Control frames may not be fragmented */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if (MHD_WebSocket_Opcode_Close == (opcode & 0x0F)) { /* RFC 6455 5.5.1: After a close frame has been sent, */ /* no data frames may be sent (so we don't accept data frames */ /* for decoding anymore) */ ws->validity = MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES; } break; default: /* RFC 6455 5.2 OPCODE: Only six opcodes are specified. */ /* All other are invalid in version 13 of the protocol. */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } } ws->frame_header [ws->frame_header_size++] = streambuf [current++]; ws->decode_step = MHD_WebSocket_DecodeStep_Length1ofX; } break; case MHD_WebSocket_DecodeStep_Length1ofX: { /* The second byte specifies whether the data is masked and the size */ /* (the client MUST mask the payload, the server MUST NOT mask the payload) */ char frame_len = streambuf [current]; char is_masked = (frame_len & 0x80); frame_len &= 0x7f; if (MHD_WEBSOCKET_VALIDITY_INVALID != ws->validity) { if (0 != is_masked) { if (MHD_WEBSOCKET_FLAG_CLIENT == (ws->flags & MHD_WEBSOCKET_FLAG_CLIENT)) { /* RFC 6455 5.1: All frames from the server must be unmasked */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } } else { if (MHD_WEBSOCKET_FLAG_SERVER == (ws->flags & MHD_WEBSOCKET_FLAG_CLIENT)) { /* RFC 6455 5.1: All frames from the client must be masked */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } } if (126 <= frame_len) { if (0 != (ws->frame_header [0] & 0x08)) { /* RFC 6455 5.5: Control frames may not have more payload than 125 bytes */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } } if (1 == frame_len) { if (MHD_WebSocket_Opcode_Close == (ws->frame_header [0] & 0x0F)) { /* RFC 6455 5.5.1: The close frame must have at least */ /* two bytes of payload if payload is used */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } } } ws->frame_header [ws->frame_header_size++] = streambuf [current++]; if (126 == frame_len) { ws->decode_step = MHD_WebSocket_DecodeStep_Length1of2; } else if (127 == frame_len) { ws->decode_step = MHD_WebSocket_DecodeStep_Length1of8; } else { size_t size = (size_t) frame_len; if ((SIZE_MAX < size) || (ws->max_payload_size && (ws->max_payload_size < size)) ) { /* RFC 6455 7.4.1 1009: If the message is too big to process, we may close the connection */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } ws->payload_size = size; if (0 != is_masked) { /* with mask */ ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4; } else { /* without mask */ *((uint32_t *) ws->mask_key) = 0; ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted; } } } break; /* Payload size first byte of 2 bytes */ case MHD_WebSocket_DecodeStep_Length1of2: /* Payload size first 7 bytes of 8 bytes */ case MHD_WebSocket_DecodeStep_Length1of8: case MHD_WebSocket_DecodeStep_Length2of8: case MHD_WebSocket_DecodeStep_Length3of8: case MHD_WebSocket_DecodeStep_Length4of8: case MHD_WebSocket_DecodeStep_Length5of8: case MHD_WebSocket_DecodeStep_Length6of8: case MHD_WebSocket_DecodeStep_Length7of8: /* Mask first 3 bytes of 4 bytes */ case MHD_WebSocket_DecodeStep_Mask1Of4: case MHD_WebSocket_DecodeStep_Mask2Of4: case MHD_WebSocket_DecodeStep_Mask3Of4: ws->frame_header [ws->frame_header_size++] = streambuf [current++]; ++ws->decode_step; break; /* 2 byte length finished */ case MHD_WebSocket_DecodeStep_Length2of2: { ws->frame_header [ws->frame_header_size++] = streambuf [current++]; size_t size = (size_t) MHD_htons ( *((uint16_t *) &ws->frame_header [2])); if (125 >= size) { /* RFC 6455 5.2 Payload length: The minimal number of bytes */ /* must be used for the length */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if ((SIZE_MAX < size) || (ws->max_payload_size && (ws->max_payload_size < size)) ) { /* RFC 6455 7.4.1 1009: If the message is too big to process, */ /* we may close the connection */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } ws->payload_size = size; if (0 != (ws->frame_header [1] & 0x80)) { /* with mask */ ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4; } else { /* without mask */ *((uint32_t *) ws->mask_key) = 0; ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted; } } break; /* 8 byte length finished */ case MHD_WebSocket_DecodeStep_Length8of8: { ws->frame_header [ws->frame_header_size++] = streambuf [current++]; uint64_t size = MHD_htonll (*((uint64_t *) &ws->frame_header [2])); if (0x7fffffffffffffff < size) { /* RFC 6455 5.2 frame-payload-length-63: The length may */ /* not exceed 0x7fffffffffffffff */ ws->decode_step = MHD_WebSocket_DecodeStep_BrokenStream; ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if (65535 >= size) { /* RFC 6455 5.2 Payload length: The minimal number of bytes */ /* must be used for the length */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; } if ((SIZE_MAX < size) || (ws->max_payload_size && (ws->max_payload_size < size)) ) { /* RFC 6455 7.4.1 1009: If the message is too big to process, */ /* we may close the connection */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED, 0, 0, payload, payload_len); } *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } ws->payload_size = (size_t) size; if (0 != (ws->frame_header [1] & 0x80)) { /* with mask */ ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4; } else { /* without mask */ *((uint32_t *) ws->mask_key) = 0; ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted; } } break; /* mask finished */ case MHD_WebSocket_DecodeStep_Mask4Of4: ws->frame_header [ws->frame_header_size++] = streambuf [current++]; *((uint32_t *) ws->mask_key) = *((uint32_t *) &ws->frame_header [ws-> frame_header_size - 4]); ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted; break; /* header finished */ case MHD_WebSocket_DecodeStep_HeaderCompleted: /* return or assign either to data or control */ { int ret = MHD_websocket_decode_header_complete (ws, payload, payload_len); if (MHD_WEBSOCKET_STATUS_OK != ret) { *streambuf_read_len = current; return ret; } } break; /* payload data */ case MHD_WebSocket_DecodeStep_PayloadOfDataFrame: case MHD_WebSocket_DecodeStep_PayloadOfControlFrame: { size_t bytes_needed = ws->payload_size - ws->payload_index; size_t bytes_remaining = streambuf_len - current; size_t bytes_to_take = bytes_needed < bytes_remaining ? bytes_needed : bytes_remaining; if (0 != bytes_to_take) { size_t utf8_start = ws->payload_index; char *decode_payload = ws->decode_step == MHD_WebSocket_DecodeStep_PayloadOfDataFrame ? ws->data_payload_start : ws->control_payload; /* copy the new payload data (with unmasking if necessary */ MHD_websocket_copy_payload (decode_payload + ws->payload_index, &streambuf [current], bytes_to_take, *((uint32_t *) ws->mask_key), (unsigned long) (ws->payload_index & 0x03)); current += bytes_to_take; ws->payload_index += bytes_to_take; if (((MHD_WebSocket_DecodeStep_PayloadOfDataFrame == ws->decode_step) && (MHD_WebSocket_Opcode_Text == ws->data_type)) || ((MHD_WebSocket_DecodeStep_PayloadOfControlFrame == ws->decode_step) && (MHD_WebSocket_Opcode_Close == (ws->frame_header [0] & 0x0f)) && (2 < ws->payload_index)) ) { /* RFC 6455 8.1: We need to check the UTF-8 validity */ int utf8_step; char *decode_payload_utf8; size_t bytes_to_check; size_t utf8_error_offset = 0; if (MHD_WebSocket_DecodeStep_PayloadOfDataFrame == ws->decode_step) { utf8_step = ws->data_utf8_step; decode_payload_utf8 = decode_payload + utf8_start; bytes_to_check = bytes_to_take; } else { utf8_step = ws->control_utf8_step; if ((MHD_WebSocket_Opcode_Close == (ws->frame_header [0] & 0x0f)) && (2 > utf8_start) ) { /* The first two bytes of the close frame are binary content and */ /* must be skipped in the UTF-8 check */ utf8_start = 2; utf8_error_offset = 2; } decode_payload_utf8 = decode_payload + utf8_start; bytes_to_check = bytes_to_take - utf8_start; } size_t utf8_check_offset = 0; int utf8_result = MHD_websocket_check_utf8 (decode_payload_utf8, bytes_to_check, &utf8_step, &utf8_check_offset); if (MHD_WebSocket_UTF8Result_Invalid != utf8_result) { /* memorize current validity check step to continue later */ ws->data_utf8_step = utf8_step; } else { /* RFC 6455 8.1: We must fail on broken UTF-8 sequence */ ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8, 0, 0, payload, payload_len); } *streambuf_read_len = current - bytes_to_take + utf8_check_offset + utf8_error_offset; return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR; } } } } if (ws->payload_size == ws->payload_index) { /* all payload data of the current frame has been received */ int ret = MHD_websocket_decode_payload_complete (ws, payload, payload_len); if (MHD_WEBSOCKET_STATUS_OK != ret) { *streambuf_read_len = current; return ret; } } break; case MHD_WebSocket_DecodeStep_BrokenStream: *streambuf_read_len = current; return MHD_WEBSOCKET_STATUS_STREAM_BROKEN; } } /* Special treatment for zero payload length messages */ if (MHD_WebSocket_DecodeStep_HeaderCompleted == ws->decode_step) { int ret = MHD_websocket_decode_header_complete (ws, payload, payload_len); if (MHD_WEBSOCKET_STATUS_OK != ret) { *streambuf_read_len = current; return ret; } } switch (ws->decode_step) { case MHD_WebSocket_DecodeStep_PayloadOfDataFrame: case MHD_WebSocket_DecodeStep_PayloadOfControlFrame: if (ws->payload_size == ws->payload_index) { /* all payload data of the current frame has been received */ int ret = MHD_websocket_decode_payload_complete (ws, payload, payload_len); if (MHD_WEBSOCKET_STATUS_OK != ret) { *streambuf_read_len = current; return ret; } } break; } *streambuf_read_len = current; /* more data needed */ return MHD_WEBSOCKET_STATUS_OK; } static enum MHD_WEBSOCKET_STATUS MHD_websocket_decode_header_complete (struct MHD_WebSocketStream *ws, char **payload, size_t *payload_len) { /* assign either to data or control */ char opcode = ws->frame_header [0] & 0x0f; switch (opcode) { case MHD_WebSocket_Opcode_Continuation: { /* validate payload size */ size_t new_size_total = ws->payload_size + ws->data_payload_size; if ((0 != ws->max_payload_size) && (ws->max_payload_size < new_size_total) ) { /* RFC 6455 7.4.1 1009: If the message is too big to process, */ /* we may close the connection */ ws->decode_step = MHD_WebSocket_DecodeStep_BrokenStream; ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID; if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR)) { MHD_websocket_encode_close (ws, MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED, 0, 0, payload, payload_len); } return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } /* allocate buffer for continued data frame */ char *new_buf = NULL; if (0 != new_size_total) { new_buf = ws->realloc (ws->data_payload, new_size_total + 1); if (NULL == new_buf) { return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; } new_buf [new_size_total] = 0; ws->data_payload_start = &new_buf[ws->data_payload_size]; } else { ws->data_payload_start = new_buf; } ws->data_payload = new_buf; ws->data_payload_size = new_size_total; } ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfDataFrame; break; case MHD_WebSocket_Opcode_Text: case MHD_WebSocket_Opcode_Binary: /* allocate buffer for data frame */ { size_t new_size_total = ws->payload_size; char *new_buf = NULL; if (0 != new_size_total) { new_buf = ws->malloc (new_size_total + 1); if (NULL == new_buf) { return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; } new_buf [new_size_total] = 0; } ws->data_payload = new_buf; ws->data_payload_start = new_buf; ws->data_payload_size = new_size_total; ws->data_type = opcode; } ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfDataFrame; break; case MHD_WebSocket_Opcode_Close: case MHD_WebSocket_Opcode_Ping: case MHD_WebSocket_Opcode_Pong: /* allocate buffer for control frame */ { size_t new_size_total = ws->payload_size; char *new_buf = NULL; if (0 != new_size_total) { new_buf = ws->malloc (new_size_total + 1); if (NULL == new_buf) { return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; } new_buf[new_size_total] = 0; } ws->control_payload = new_buf; } ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfControlFrame; break; } return MHD_WEBSOCKET_STATUS_OK; } static enum MHD_WEBSOCKET_STATUS MHD_websocket_decode_payload_complete (struct MHD_WebSocketStream *ws, char **payload, size_t *payload_len) { /* all payload data of the current frame has been received */ char is_continue = MHD_WebSocket_Opcode_Continuation == (ws->frame_header [0] & 0x0F); char is_fin = ws->frame_header [0] & 0x80; if (0 != is_fin) { /* the frame is complete */ if (MHD_WebSocket_DecodeStep_PayloadOfDataFrame == ws->decode_step) { /* data frame */ char data_type = ws->data_type; if ((0 != (ws->flags & MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS)) && (0 != is_continue)) { data_type |= 0x40; /* mark as last fragment */ } *payload = ws->data_payload; *payload_len = ws->data_payload_size; ws->data_payload = 0; ws->data_payload_start = 0; ws->data_payload_size = 0; ws->decode_step = MHD_WebSocket_DecodeStep_Start; ws->payload_index = 0; ws->data_type = 0; ws->frame_header_size = 0; return data_type; } else { /* control frame */ *payload = ws->control_payload; *payload_len = ws->payload_size; ws->control_payload = 0; ws->decode_step = MHD_WebSocket_DecodeStep_Start; ws->payload_index = 0; ws->frame_header_size = 0; return (ws->frame_header [0] & 0x0f); } } else if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS)) { /* RFC 6455 5.4: To allow streaming, the user can choose */ /* to return fragments */ if ((MHD_WebSocket_Opcode_Text == ws->data_type) && (MHD_WEBSOCKET_UTF8STEP_NORMAL != ws->data_utf8_step) ) { /* the last UTF-8 sequence is incomplete, so we keep the start of that and only return the part before */ size_t given_utf8 = 0; switch (ws->data_utf8_step) { /* one byte given */ case MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1: case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2: case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2: case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2: case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3: case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3: case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3: given_utf8 = 1; break; /* two bytes given */ case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2: case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3: given_utf8 = 2; break; /* three bytes given */ case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3: given_utf8 = 3; break; } size_t new_len = ws->data_payload_size - given_utf8; if (0 != new_len) { char *next_payload = ws->malloc (given_utf8 + 1); if (NULL == next_payload) { return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; } memcpy (next_payload, ws->data_payload_start + ws->payload_index - given_utf8, given_utf8); next_payload[given_utf8] = 0; ws->data_payload[new_len] = 0; *payload = ws->data_payload; *payload_len = new_len; ws->data_payload = next_payload; ws->data_payload_size = given_utf8; } else { *payload = NULL; *payload_len = 0; } ws->decode_step = MHD_WebSocket_DecodeStep_Start; ws->payload_index = 0; ws->frame_header_size = 0; if (0 != is_continue) return ws->data_type | 0x20; /* mark as middle fragment */ else return ws->data_type | 0x10; /* mark as first fragment */ } else { /* we simply pass the entire data frame */ *payload = ws->data_payload; *payload_len = ws->data_payload_size; ws->data_payload = 0; ws->data_payload_start = 0; ws->data_payload_size = 0; ws->decode_step = MHD_WebSocket_DecodeStep_Start; ws->payload_index = 0; ws->frame_header_size = 0; if (0 != is_continue) return ws->data_type | 0x20; /* mark as middle fragment */ else return ws->data_type | 0x10; /* mark as first fragment */ } } else { /* RFC 6455 5.4: We must await a continuation frame to get */ /* the remainder of this data frame */ ws->decode_step = MHD_WebSocket_DecodeStep_Start; ws->frame_header_size = 0; ws->payload_index = 0; return MHD_WEBSOCKET_STATUS_OK; } } /** * Splits the received close reason */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_split_close_reason (const char *payload, size_t payload_len, unsigned short *reason_code, const char **reason_utf8, size_t *reason_utf8_len) { /* initialize output variables for errors cases */ if (NULL != reason_code) *reason_code = MHD_WEBSOCKET_CLOSEREASON_NO_REASON; if (NULL != reason_utf8) *reason_utf8 = NULL; if (NULL != reason_utf8_len) *reason_utf8_len = 0; /* validate parameters */ if ((NULL == payload) && (0 != payload_len)) return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; if (1 == payload_len) return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR; if (125 < payload_len) return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; /* decode reason code */ if (2 > payload_len) { if (NULL != reason_code) *reason_code = MHD_WEBSOCKET_CLOSEREASON_NO_REASON; } else { if (NULL != reason_code) *reason_code = MHD_htons (*((uint16_t *) payload)); } /* decode reason text */ if (2 >= payload_len) { if (NULL != reason_utf8) *reason_utf8 = NULL; if (NULL != reason_utf8_len) *reason_utf8_len = 0; } else { if (NULL != reason_utf8) *reason_utf8 = payload + 2; if (NULL != reason_utf8_len) *reason_utf8_len = payload_len - 2; } return MHD_WEBSOCKET_STATUS_OK; } /** * Encodes a text into a websocket text frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_text (struct MHD_WebSocketStream *ws, const char *payload_utf8, size_t payload_utf8_len, int fragmentation, char **frame, size_t *frame_len, int *utf8_step) { /* initialize output variables for errors cases */ if (NULL != frame) *frame = NULL; if (NULL != frame_len) *frame_len = 0; if ((NULL != utf8_step) && ((MHD_WEBSOCKET_FRAGMENTATION_FIRST == fragmentation) || (MHD_WEBSOCKET_FRAGMENTATION_NONE == fragmentation) )) { /* the old UTF-8 step will be ignored for new fragments */ *utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL; } /* validate parameters */ if ((NULL == ws) || ((0 != payload_utf8_len) && (NULL == payload_utf8)) || (NULL == frame) || (NULL == frame_len) || (MHD_WEBSOCKET_FRAGMENTATION_NONE > fragmentation) || (MHD_WEBSOCKET_FRAGMENTATION_LAST < fragmentation) || ((MHD_WEBSOCKET_FRAGMENTATION_NONE != fragmentation) && (NULL == utf8_step)) ) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* check max length */ if ((uint64_t) 0x7FFFFFFFFFFFFFFF < (uint64_t) payload_utf8_len) { return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } /* check UTF-8 */ int utf8_result = MHD_websocket_check_utf8 (payload_utf8, payload_utf8_len, utf8_step, NULL); if ((MHD_WebSocket_UTF8Result_Invalid == utf8_result) || ((MHD_WebSocket_UTF8Result_Incomplete == utf8_result) && (MHD_WEBSOCKET_FRAGMENTATION_NONE == fragmentation)) ) { return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR; } /* encode data */ return MHD_websocket_encode_data (ws, payload_utf8, payload_utf8_len, fragmentation, frame, frame_len, MHD_WebSocket_Opcode_Text); } /** * Encodes binary data into a websocket binary frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_binary (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, int fragmentation, char **frame, size_t *frame_len) { /* initialize output variables for errors cases */ if (NULL != frame) *frame = NULL; if (NULL != frame_len) *frame_len = 0; /* validate parameters */ if ((NULL == ws) || ((0 != payload_len) && (NULL == payload)) || (NULL == frame) || (NULL == frame_len) || (MHD_WEBSOCKET_FRAGMENTATION_NONE > fragmentation) || (MHD_WEBSOCKET_FRAGMENTATION_LAST < fragmentation) ) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* check max length */ if ((uint64_t) 0x7FFFFFFFFFFFFFFF < (uint64_t) payload_len) { return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; } return MHD_websocket_encode_data (ws, payload, payload_len, fragmentation, frame, frame_len, MHD_WebSocket_Opcode_Binary); } /** * Internal function for encoding text/binary data into a websocket frame */ static enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_data (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, int fragmentation, char **frame, size_t *frame_len, char opcode) { /* calculate length and masking */ char is_masked = MHD_websocket_encode_is_masked (ws); size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len); size_t total_len = overhead_len + payload_len; uint32_t mask = 0 != is_masked ? MHD_websocket_generate_mask (ws) : 0; /* allocate memory */ char *result = ws->malloc (total_len + 1); if (NULL == result) return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; result [total_len] = 0; *frame = result; *frame_len = total_len; /* add the opcode */ switch (fragmentation) { case MHD_WEBSOCKET_FRAGMENTATION_NONE: *(result++) = 0x80 | opcode; break; case MHD_WEBSOCKET_FRAGMENTATION_FIRST: *(result++) = opcode; break; case MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING: *(result++) = MHD_WebSocket_Opcode_Continuation; break; case MHD_WEBSOCKET_FRAGMENTATION_LAST: *(result++) = 0x80 | MHD_WebSocket_Opcode_Continuation; break; } /* add the length */ if (126 > payload_len) { *(result++) = is_masked | (char) payload_len; } else if (65536 > payload_len) { *(result++) = is_masked | 126; *((uint16_t *) result) = MHD_htons ((uint16_t) payload_len); result += 2; } else { *(result++) = is_masked | 127; *((uint64_t *) result) = MHD_htonll ((uint64_t) payload_len); result += 8; } /* add the mask */ if (0 != is_masked) { *(result++) = ((char *) &mask)[0]; *(result++) = ((char *) &mask)[1]; *(result++) = ((char *) &mask)[2]; *(result++) = ((char *) &mask)[3]; } /* add the payload */ if (0 != payload_len) { MHD_websocket_copy_payload (result, payload, payload_len, mask, 0); } return MHD_WEBSOCKET_STATUS_OK; } /** * Encodes a websocket ping frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_ping (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len) { /* encode the ping frame */ return MHD_websocket_encode_ping_pong (ws, payload, payload_len, frame, frame_len, MHD_WebSocket_Opcode_Ping); } /** * Encodes a websocket pong frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_pong (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len) { /* encode the pong frame */ return MHD_websocket_encode_ping_pong (ws, payload, payload_len, frame, frame_len, MHD_WebSocket_Opcode_Pong); } /** * Internal function for encoding ping/pong frames */ static enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_ping_pong (struct MHD_WebSocketStream *ws, const char *payload, size_t payload_len, char **frame, size_t *frame_len, char opcode) { /* initialize output variables for errors cases */ if (NULL != frame) *frame = NULL; if (NULL != frame_len) *frame_len = 0; /* validate the parameters */ if ((NULL == ws) || ((0 != payload_len) && (NULL == payload)) || (NULL == frame) || (NULL == frame_len) ) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* RFC 6455 5.5: Control frames may only have up to 125 bytes of payload data */ if (125 < payload_len) return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; /* calculate length and masking */ char is_masked = MHD_websocket_encode_is_masked (ws); size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len); size_t total_len = overhead_len + payload_len; uint32_t mask = is_masked != 0 ? MHD_websocket_generate_mask (ws) : 0; /* allocate memory */ char *result = ws->malloc (total_len + 1); if (NULL == result) return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; result [total_len] = 0; *frame = result; *frame_len = total_len; /* add the opcode */ *(result++) = 0x80 | opcode; /* add the length */ *(result++) = is_masked | (char) payload_len; /* add the mask */ if (0 != is_masked) { *(result++) = ((char *) &mask)[0]; *(result++) = ((char *) &mask)[1]; *(result++) = ((char *) &mask)[2]; *(result++) = ((char *) &mask)[3]; } /* add the payload */ if (0 != payload_len) { MHD_websocket_copy_payload (result, payload, payload_len, mask, 0); } return MHD_WEBSOCKET_STATUS_OK; } /** * Encodes a websocket close frame */ _MHD_EXTERN enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_close (struct MHD_WebSocketStream *ws, unsigned short reason_code, const char *reason_utf8, size_t reason_utf8_len, char **frame, size_t *frame_len) { /* initialize output variables for errors cases */ if (NULL != frame) *frame = NULL; if (NULL != frame_len) *frame_len = 0; /* validate the parameters */ if ((NULL == ws) || ((0 != reason_utf8_len) && (NULL == reason_utf8)) || (NULL == frame) || (NULL == frame_len) || ((MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) && (1000 > reason_code)) || ((0 != reason_utf8_len) && (MHD_WEBSOCKET_CLOSEREASON_NO_REASON == reason_code)) ) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } /* RFC 6455 5.5: Control frames may only have up to 125 bytes of payload data, */ /* but in this case only 123 bytes, because 2 bytes are reserved */ /* for the close reason code. */ if (123 < reason_utf8_len) return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED; /* RFC 6455 5.5.1: If close payload data is given, it must be valid UTF-8 */ if (0 != reason_utf8_len) { int utf8_result = MHD_websocket_check_utf8 (reason_utf8, reason_utf8_len, NULL, NULL); if (MHD_WebSocket_UTF8Result_Valid != utf8_result) return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR; } /* calculate length and masking */ char is_masked = MHD_websocket_encode_is_masked (ws); size_t payload_len = (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code ? 2 + reason_utf8_len : 0); size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len); size_t total_len = overhead_len + payload_len; uint32_t mask = is_masked != 0 ? MHD_websocket_generate_mask (ws) : 0; /* allocate memory */ char *result = ws->malloc (total_len + 1); if (NULL == result) return MHD_WEBSOCKET_STATUS_MEMORY_ERROR; result [total_len] = 0; *frame = result; *frame_len = total_len; /* add the opcode */ *(result++) = 0x88; /* add the length */ *(result++) = is_masked | (char) payload_len; /* add the mask */ if (0 != is_masked) { *(result++) = ((char *) &mask)[0]; *(result++) = ((char *) &mask)[1]; *(result++) = ((char *) &mask)[2]; *(result++) = ((char *) &mask)[3]; } /* add the payload */ if (0 != reason_code) { /* close reason code */ uint16_t reason_code_nb = MHD_htons (reason_code); MHD_websocket_copy_payload (result, (const char *) &reason_code_nb, 2, mask, 0); result += 2; /* custom reason payload */ if (0 != reason_utf8_len) { MHD_websocket_copy_payload (result, reason_utf8, reason_utf8_len, mask, 2); } } return MHD_WEBSOCKET_STATUS_OK; } /** * Returns the 0x80 prefix for masked data, 0x00 otherwise */ static char MHD_websocket_encode_is_masked (struct MHD_WebSocketStream *ws) { return (ws->flags & MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT) == MHD_WEBSOCKET_FLAG_CLIENT ? 0x80 : 0x00; } /** * Calculates the size of the overhead in bytes */ static char MHD_websocket_encode_overhead_size (struct MHD_WebSocketStream *ws, size_t payload_len) { return 2 + (MHD_websocket_encode_is_masked (ws) != 0 ? 4 : 0) + (125 < payload_len ? (65535 < payload_len ? 8 : 2) : 0); } /** * Copies the payload to the destination (using mask) */ static void MHD_websocket_copy_payload (char *dst, const char *src, size_t len, uint32_t mask, unsigned long mask_offset) { if (0 != len) { if (0 == mask) { /* when the mask is zero, we can just copy the data */ memcpy (dst, src, len); } else { /* mask is used */ char mask_[4]; *((uint32_t *) mask_) = mask; for (size_t i = 0; i < len; ++i) { dst[i] = src[i] ^ mask_[(i + mask_offset) & 3]; } } } } /** * Checks a UTF-8 sequence */ static int MHD_websocket_check_utf8 (const char *buf, size_t buf_len, int *utf8_step, size_t *buf_offset) { int utf8_step_ = (NULL != utf8_step) ? *utf8_step : MHD_WEBSOCKET_UTF8STEP_NORMAL; for (size_t i = 0; i < buf_len; ++i) { unsigned char character = (unsigned char) buf[i]; switch (utf8_step_) { case MHD_WEBSOCKET_UTF8STEP_NORMAL: if ((0x00 <= character) && (0x7F >= character)) { /* RFC 3629 4: single byte UTF-8 sequence */ /* (nothing to do here) */ } else if ((0xC2 <= character) && (0xDF >= character)) { /* RFC 3629 4: two byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1; } else if (0xE0 == character) { /* RFC 3629 4: three byte UTF-8 sequence, but the second byte must be 0xA0-0xBF */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2; } else if (0xED == character) { /* RFC 3629 4: three byte UTF-8 sequence, but the second byte must be 0x80-0x9F */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2; } else if (((0xE1 <= character) && (0xEC >= character)) || ((0xEE <= character) && (0xEF >= character)) ) { /* RFC 3629 4: three byte UTF-8 sequence, both tail bytes must be 0x80-0xBF */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2; } else if (0xF0 == character) { /* RFC 3629 4: four byte UTF-8 sequence, but the second byte must be 0x90-0xBF */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3; } else if (0xF4 == character) { /* RFC 3629 4: four byte UTF-8 sequence, but the second byte must be 0x80-0x8F */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3; } else if ((0xF1 <= character) && (0xF3 >= character)) { /* RFC 3629 4: four byte UTF-8 sequence, all three tail bytes must be 0x80-0xBF */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2: if ((0xA0 <= character) && (0xBF >= character)) { /* RFC 3629 4: Second byte of three byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2: if ((0x80 <= character) && (0x9F >= character)) { /* RFC 3629 4: Second byte of three byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2: if ((0x80 <= character) && (0xBF >= character)) { /* RFC 3629 4: Second byte of three byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3: if ((0x90 <= character) && (0xBF >= character)) { /* RFC 3629 4: Second byte of four byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3: if ((0x80 <= character) && (0x8F >= character)) { /* RFC 3629 4: Second byte of four byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3: if ((0x80 <= character) && (0xBF >= character)) { /* RFC 3629 4: Second byte of four byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3: if ((0x80 <= character) && (0xBF >= character)) { /* RFC 3629 4: Third byte of four byte UTF-8 sequence */ utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; /* RFC 3629 4: Second byte of two byte UTF-8 sequence */ case MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1: /* RFC 3629 4: Third byte of three byte UTF-8 sequence */ case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2: /* RFC 3629 4: Fourth byte of four byte UTF-8 sequence */ case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3: if ((0x80 <= character) && (0xBF >= character)) { utf8_step_ = MHD_WEBSOCKET_UTF8STEP_NORMAL; } else { /* RFC 3629 4: Invalid UTF-8 byte */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } break; default: /* Invalid last step...? */ if (NULL != buf_offset) *buf_offset = i; return MHD_WebSocket_UTF8Result_Invalid; } } /* return values */ if (NULL != utf8_step) *utf8_step = utf8_step_; if (NULL != buf_offset) *buf_offset = buf_len; if (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step_) { return MHD_WebSocket_UTF8Result_Incomplete; } return MHD_WebSocket_UTF8Result_Valid; } /** * Generates a mask for masking by calling * a random number generator. */ static uint32_t MHD_websocket_generate_mask (struct MHD_WebSocketStream *ws) { unsigned char mask_[4]; if (NULL != ws->rng) { size_t offset = 0; while (offset < 4) { size_t encoded = ws->rng (ws->cls_rng, mask_ + offset, 4 - offset); offset += encoded; } } else { /* this case should never happen */ mask_ [0] = 0; mask_ [1] = 0; mask_ [2] = 0; mask_ [3] = 0; } return *((uint32_t *) mask_); } /** * Calls the malloc function associated with the websocket steam */ _MHD_EXTERN void * MHD_websocket_malloc (struct MHD_WebSocketStream *ws, size_t buf_len) { if (NULL == ws) { return NULL; } return ws->malloc (buf_len); } /** * Calls the realloc function associated with the websocket steam */ _MHD_EXTERN void * MHD_websocket_realloc (struct MHD_WebSocketStream *ws, void *buf, size_t new_buf_len) { if (NULL == ws) { return NULL; } return ws->realloc (buf, new_buf_len); } /** * Calls the free function associated with the websocket steam */ _MHD_EXTERN int MHD_websocket_free (struct MHD_WebSocketStream *ws, void *buf) { if (NULL == ws) { return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR; } ws->free (buf); return MHD_WEBSOCKET_STATUS_OK; } /** * Converts a 16 bit value into network byte order (MSB first) * in dependence of the host system */ static uint16_t MHD_htons (uint16_t value) { uint16_t endian = 0x0001; if (((char *) &endian)[0] == 0x01) { /* least significant byte first */ ((char *) &endian)[0] = ((char *) &value)[1]; ((char *) &endian)[1] = ((char *) &value)[0]; return endian; } else { /* most significant byte first */ return value; } } /** * Converts a 64 bit value into network byte order (MSB first) * in dependence of the host system */ static uint64_t MHD_htonll (uint64_t value) { uint64_t endian = 0x0000000000000001; if (((char *) &endian)[0] == 0x01) { /* least significant byte first */ ((char *) &endian)[0] = ((char *) &value)[7]; ((char *) &endian)[1] = ((char *) &value)[6]; ((char *) &endian)[2] = ((char *) &value)[5]; ((char *) &endian)[3] = ((char *) &value)[4]; ((char *) &endian)[4] = ((char *) &value)[3]; ((char *) &endian)[5] = ((char *) &value)[2]; ((char *) &endian)[6] = ((char *) &value)[1]; ((char *) &endian)[7] = ((char *) &value)[0]; return endian; } else { /* most significant byte first */ return value; } } libmicrohttpd-1.0.2/src/microhttpd_ws/sha1.c0000644000175000017500000003701514760713574016000 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.c * @brief Calculation of SHA-1 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha1.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA-1 calculation. * * @param ctx_ must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_) { struct sha1_ctx *const ctx = ctx_; /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.1 */ /* Just some "magic" numbers defined by standard */ ctx->H[0] = UINT32_C (0x67452301); ctx->H[1] = UINT32_C (0xefcdab89); ctx->H[2] = UINT32_C (0x98badcfe); ctx->H[3] = UINT32_C (0x10325476); ctx->H[4] = UINT32_C (0xc3d2e1f0); /* Initialise number of bytes. */ ctx->count = 0; } /** * Base of SHA-1 transformation. * Gets full 512 bits / 64 bytes block of data and updates hash values; * @param H hash values * @param data data, must be exactly 64 bytes long */ static void sha1_transform (uint32_t H[_SHA1_DIGEST_LENGTH], const uint8_t data[SHA1_BLOCK_SIZE]) { /* Working variables, see FIPS PUB 180-4 paragraph 6.1.3 */ uint32_t a = H[0]; uint32_t b = H[1]; uint32_t c = H[2]; uint32_t d = H[3]; uint32_t e = H[4]; /* Data buffer, used as cyclic buffer. See FIPS PUB 180-4 paragraphs 5.2.1, 6.1.3 */ uint32_t W[16]; /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. See FIPS PUB 180-4 formulae 4.1. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ #define Par(x,y,z) ( (x) ^ (y) ^ (z) ) /* Single step of SHA-1 computation, see FIPS PUB 180-4 paragraph 6.1.3 step 3. * Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA1STEP32 (a, b, c, d, e, func, K00, W[0]); SHA1STEP32 (e, a, b, c, d, func, K00, W[1]); so current 'vC' will be used as 'vD' on the next step, current 'vE' will be used as 'vA' on the next step. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA1STEP32(vA,vB,vC,vD,vE,ft,kt,wt) do { \ (vE) += _MHD_ROTL32 ((vA), 5) + ft ((vB), (vC), (vD)) + (kt) + (wt); \ (vB) = _MHD_ROTL32 ((vB), 30); } while (0) /* Get value of W(t) from input data buffer, See FIPS PUB 180-4 paragraph 6.1.3. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 paragraph 3.1.2. */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_32BIT_BE (((const uint8_t*) (buf)) + (t) * SHA1_BYTES_IN_WORD) #ifndef _MHD_GET_32BIT_BE_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN)) { /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, SHA1_BLOCK_SIZE); /* The W[] buffer itself will be used as the source of the data, * but data will be reloaded in correct bytes order during * the next steps */ data = (uint8_t *) W; } #endif /* _MHD_GET_32BIT_BE_UNALIGNED */ /* SHA-1 values of Kt for t=0..19, see FIPS PUB 180-4 paragraph 4.2.1. */ #define K00 UINT32_C(0x5a827999) /* SHA-1 values of Kt for t=20..39, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K20 UINT32_C(0x6ed9eba1) /* SHA-1 values of Kt for t=40..59, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K40 UINT32_C(0x8f1bbcdc) /* SHA-1 values of Kt for t=60..79, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K60 UINT32_C(0xca62c1d6) /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ /* Note: instead of using K constants as array, all K values are specified individually for each step. */ SHA1STEP32 (a, b, c, d, e, Ch, K00, W[0] = GET_W_FROM_DATA (data, 0)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[1] = GET_W_FROM_DATA (data, 1)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[2] = GET_W_FROM_DATA (data, 2)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[3] = GET_W_FROM_DATA (data, 3)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[4] = GET_W_FROM_DATA (data, 4)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[5] = GET_W_FROM_DATA (data, 5)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[6] = GET_W_FROM_DATA (data, 6)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[7] = GET_W_FROM_DATA (data, 7)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[8] = GET_W_FROM_DATA (data, 8)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[9] = GET_W_FROM_DATA (data, 9)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[10] = GET_W_FROM_DATA (data, 10)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[11] = GET_W_FROM_DATA (data, 11)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[12] = GET_W_FROM_DATA (data, 12)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[13] = GET_W_FROM_DATA (data, 13)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[14] = GET_W_FROM_DATA (data, 14)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[15] = GET_W_FROM_DATA (data, 15)); /* 'W' generation and assignment for 16 <= t <= 79. See FIPS PUB 180-4 paragraph 6.1.3. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as cyclic buffer. */ #define Wgen(w,t) _MHD_ROTL32((w)[(t + 13) & 0xf] ^ (w)[(t + 8) & 0xf] \ ^ (w)[(t + 2) & 0xf] ^ (w)[t & 0xf], 1) /* During last 60 steps, before making any calculations on each step, W element is generated from W elements of cyclic buffer and generated value stored back in cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.1. */ SHA1STEP32 (e, a, b, c, d, Ch, K00, W[16 & 0xf] = Wgen (W, 16)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[17 & 0xf] = Wgen (W, 17)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[18 & 0xf] = Wgen (W, 18)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[19 & 0xf] = Wgen (W, 19)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[20 & 0xf] = Wgen (W, 20)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[21 & 0xf] = Wgen (W, 21)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[22 & 0xf] = Wgen (W, 22)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[23 & 0xf] = Wgen (W, 23)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[24 & 0xf] = Wgen (W, 24)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[25 & 0xf] = Wgen (W, 25)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[26 & 0xf] = Wgen (W, 26)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[27 & 0xf] = Wgen (W, 27)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[28 & 0xf] = Wgen (W, 28)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[29 & 0xf] = Wgen (W, 29)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[30 & 0xf] = Wgen (W, 30)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[31 & 0xf] = Wgen (W, 31)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[32 & 0xf] = Wgen (W, 32)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[33 & 0xf] = Wgen (W, 33)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[34 & 0xf] = Wgen (W, 34)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[35 & 0xf] = Wgen (W, 35)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[36 & 0xf] = Wgen (W, 36)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[37 & 0xf] = Wgen (W, 37)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[38 & 0xf] = Wgen (W, 38)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[39 & 0xf] = Wgen (W, 39)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[40 & 0xf] = Wgen (W, 40)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[41 & 0xf] = Wgen (W, 41)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[42 & 0xf] = Wgen (W, 42)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[43 & 0xf] = Wgen (W, 43)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[44 & 0xf] = Wgen (W, 44)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[45 & 0xf] = Wgen (W, 45)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[46 & 0xf] = Wgen (W, 46)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[47 & 0xf] = Wgen (W, 47)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[48 & 0xf] = Wgen (W, 48)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[49 & 0xf] = Wgen (W, 49)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[50 & 0xf] = Wgen (W, 50)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[51 & 0xf] = Wgen (W, 51)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[52 & 0xf] = Wgen (W, 52)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[53 & 0xf] = Wgen (W, 53)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[54 & 0xf] = Wgen (W, 54)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[55 & 0xf] = Wgen (W, 55)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[56 & 0xf] = Wgen (W, 56)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[57 & 0xf] = Wgen (W, 57)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[58 & 0xf] = Wgen (W, 58)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[59 & 0xf] = Wgen (W, 59)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[60 & 0xf] = Wgen (W, 60)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[61 & 0xf] = Wgen (W, 61)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[62 & 0xf] = Wgen (W, 62)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[63 & 0xf] = Wgen (W, 63)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[64 & 0xf] = Wgen (W, 64)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[65 & 0xf] = Wgen (W, 65)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[66 & 0xf] = Wgen (W, 66)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[67 & 0xf] = Wgen (W, 67)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[68 & 0xf] = Wgen (W, 68)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[69 & 0xf] = Wgen (W, 69)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[70 & 0xf] = Wgen (W, 70)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[71 & 0xf] = Wgen (W, 71)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[72 & 0xf] = Wgen (W, 72)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[73 & 0xf] = Wgen (W, 73)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[74 & 0xf] = Wgen (W, 74)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[75 & 0xf] = Wgen (W, 75)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[76 & 0xf] = Wgen (W, 76)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[77 & 0xf] = Wgen (W, 77)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[78 & 0xf] = Wgen (W, 78)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[79 & 0xf] = Wgen (W, 79)); /* Compute intermediate hash. See FIPS PUB 180-4 paragraph 6.1.3 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; } /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length) { struct sha1_ctx *const ctx = ctx_; unsigned bytes_have; /**< Number of bytes in buffer */ mhd_assert ((data != NULL) || (length == 0)); if (0 == length) return; /* Do nothing */ /* Note: (count & (SHA1_BLOCK_SIZE-1)) equal (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned bytes_left = SHA1_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with the data in the buffer and process the full block. */ memcpy (ctx->buffer + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha1_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA1_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha1_transform (ctx->H, data); data += SHA1_BLOCK_SIZE; length -= SHA1_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (ctx->buffer + bytes_have, data, length); } } /** * Size of "length" padding addition in bytes. * See FIPS PUB 180-4 paragraph 5.1.1. */ #define SHA1_SIZE_OF_LEN_ADD (64 / 8) /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]) { struct sha1_ctx *const ctx = ctx_; uint64_t num_bits; /**< Number of processed bits */ unsigned bytes_have; /**< Number of bytes in buffer */ num_bits = ctx->count << 3; /* Note: (count & (SHA1_BLOCK_SIZE-1)) equals (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); /* Input data must be padded with bit "1" and with length of data in bits. See FIPS PUB 180-4 paragraph 5.1.1. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of first padding bit in byte is always predefined (0x80). */ /* Buffer always have space at least for one byte (as full buffers are processed immediately). */ ctx->buffer[bytes_have++] = 0x80; if (SHA1_BLOCK_SIZE - bytes_have < SHA1_SIZE_OF_LEN_ADD) { /* No space in current block to put total length of message. Pad current block with zeros and process it. */ if (SHA1_BLOCK_SIZE > bytes_have) memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - bytes_have); /* Process full block. */ sha1_transform (ctx->H, ctx->buffer); /* Start new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in the processed message as a big-endian value. */ _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD, num_bits); /* Process the full final block. */ sha1_transform (ctx->H, ctx->buffer); /* Put final hash/digest in BE mode */ #ifndef _MHD_PUT_32BIT_BE_UNALIGNED if (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) { uint32_t alig_dgst[_SHA1_DIGEST_LENGTH]; _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]); _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]); /* Copy result to unaligned destination address */ memcpy (digest, alig_dgst, SHA1_DIGEST_SIZE); } else #else /* _MHD_PUT_32BIT_BE_UNALIGNED */ if (1) #endif /* _MHD_PUT_32BIT_BE_UNALIGNED */ { _MHD_PUT_32BIT_BE (digest + 0 * SHA1_BYTES_IN_WORD, ctx->H[0]); _MHD_PUT_32BIT_BE (digest + 1 * SHA1_BYTES_IN_WORD, ctx->H[1]); _MHD_PUT_32BIT_BE (digest + 2 * SHA1_BYTES_IN_WORD, ctx->H[2]); _MHD_PUT_32BIT_BE (digest + 3 * SHA1_BYTES_IN_WORD, ctx->H[3]); _MHD_PUT_32BIT_BE (digest + 4 * SHA1_BYTES_IN_WORD, ctx->H[4]); } /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct sha1_ctx)); } libmicrohttpd-1.0.2/src/microhttpd_ws/Makefile.in0000644000175000017500000013212015035216310017014 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = test_websocket$(EXEEXT) subdir = src/microhttpd_ws ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = libmicrohttpd_ws_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_libmicrohttpd_ws_la_OBJECTS = libmicrohttpd_ws_la-sha1.lo \ libmicrohttpd_ws_la-mhd_websocket.lo libmicrohttpd_ws_la_OBJECTS = $(am_libmicrohttpd_ws_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libmicrohttpd_ws_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(libmicrohttpd_ws_la_CFLAGS) $(CFLAGS) \ $(libmicrohttpd_ws_la_LDFLAGS) $(LDFLAGS) -o $@ am_test_websocket_OBJECTS = test_websocket.$(OBJEXT) test_websocket_OBJECTS = $(am_test_websocket_OBJECTS) test_websocket_DEPENDENCIES = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = \ ./$(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Plo \ ./$(DEPDIR)/libmicrohttpd_ws_la-sha1.Plo \ ./$(DEPDIR)/test_websocket.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libmicrohttpd_ws_la_SOURCES) $(test_websocket_SOURCES) DIST_SOURCES = $(libmicrohttpd_ws_la_SOURCES) \ $(test_websocket_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(noinst_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS) noinst_DATA = MOSTLYCLEANFILES = SUBDIRS = . lib_LTLIBRARIES = \ libmicrohttpd_ws.la libmicrohttpd_ws_la_SOURCES = \ sha1.c sha1.h \ mhd_websocket.c libmicrohttpd_ws_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_ws_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) libmicrohttpd_ws_la_LDFLAGS = \ $(MHD_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -version-info 0:0:0 libmicrohttpd_ws_la_LIBADD = \ $(MHD_LIBDEPS) TESTS = $(check_PROGRAMS) test_websocket_SOURCES = \ test_websocket.c test_websocket_LDADD = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/microhttpd_ws/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/microhttpd_ws/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libmicrohttpd_ws.la: $(libmicrohttpd_ws_la_OBJECTS) $(libmicrohttpd_ws_la_DEPENDENCIES) $(EXTRA_libmicrohttpd_ws_la_DEPENDENCIES) $(AM_V_CCLD)$(libmicrohttpd_ws_la_LINK) -rpath $(libdir) $(libmicrohttpd_ws_la_OBJECTS) $(libmicrohttpd_ws_la_LIBADD) $(LIBS) test_websocket$(EXEEXT): $(test_websocket_OBJECTS) $(test_websocket_DEPENDENCIES) $(EXTRA_test_websocket_DEPENDENCIES) @rm -f test_websocket$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_websocket_OBJECTS) $(test_websocket_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_ws_la-sha1.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_websocket.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< libmicrohttpd_ws_la-sha1.lo: sha1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_ws_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_ws_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_ws_la-sha1.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_ws_la-sha1.Tpo -c -o libmicrohttpd_ws_la-sha1.lo `test -f 'sha1.c' || echo '$(srcdir)/'`sha1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_ws_la-sha1.Tpo $(DEPDIR)/libmicrohttpd_ws_la-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha1.c' object='libmicrohttpd_ws_la-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_ws_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_ws_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_ws_la-sha1.lo `test -f 'sha1.c' || echo '$(srcdir)/'`sha1.c libmicrohttpd_ws_la-mhd_websocket.lo: mhd_websocket.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_ws_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_ws_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_ws_la-mhd_websocket.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Tpo -c -o libmicrohttpd_ws_la-mhd_websocket.lo `test -f 'mhd_websocket.c' || echo '$(srcdir)/'`mhd_websocket.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Tpo $(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_websocket.c' object='libmicrohttpd_ws_la-mhd_websocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_ws_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_ws_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_ws_la-mhd_websocket.lo `test -f 'mhd_websocket.c' || echo '$(srcdir)/'`mhd_websocket.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_websocket.log: test_websocket$(EXEEXT) @p='test_websocket$(EXEEXT)'; \ b='test_websocket'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile $(LTLIBRARIES) $(DATA) install-checkPROGRAMS: install-libLTLIBRARIES installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES) -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_ws_la-sha1.Plo -rm -f ./$(DEPDIR)/test_websocket.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/libmicrohttpd_ws_la-mhd_websocket.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_ws_la-sha1.Plo -rm -f ./$(DEPDIR)/test_websocket.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/microhttpd_ws/Makefile.am0000644000175000017500000000217115035214301017003 00000000000000# This Makefile.am is in the public domain AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS) $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la noinst_DATA = MOSTLYCLEANFILES = SUBDIRS = . lib_LTLIBRARIES = \ libmicrohttpd_ws.la libmicrohttpd_ws_la_SOURCES = \ sha1.c sha1.h \ mhd_websocket.c libmicrohttpd_ws_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_ws_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) libmicrohttpd_ws_la_LDFLAGS = \ $(MHD_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -version-info 0:0:0 libmicrohttpd_ws_la_LIBADD = \ $(MHD_LIBDEPS) TESTS = $(check_PROGRAMS) check_PROGRAMS = \ test_websocket test_websocket_SOURCES = \ test_websocket.c test_websocket_LDADD = \ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \ $(top_builddir)/src/microhttpd/libmicrohttpd.la libmicrohttpd-1.0.2/src/microhttpd_ws/sha1.h0000644000175000017500000000526714760713577016014 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.h * @brief Calculation of SHA-1 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA1_H #define MHD_SHA1_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * SHA-1 digest is kept internally as 5 32-bit words. */ #define _SHA1_DIGEST_LENGTH 5 /** * Number of bits in single SHA-1 word */ #define SHA1_WORD_SIZE_BITS 32 /** * Number of bytes in single SHA-1 word */ #define SHA1_BYTES_IN_WORD (SHA1_WORD_SIZE_BITS / 8) /** * Size of SHA-1 digest in bytes */ #define SHA1_DIGEST_SIZE (_SHA1_DIGEST_LENGTH * SHA1_BYTES_IN_WORD) /** * Size of SHA-1 digest string in chars including termination NUL */ #define SHA1_DIGEST_STRING_SIZE ((SHA1_DIGEST_SIZE) * 2 + 1) /** * Size of single processing block in bits */ #define SHA1_BLOCK_SIZE_BITS 512 /** * Size of single processing block in bytes */ #define SHA1_BLOCK_SIZE (SHA1_BLOCK_SIZE_BITS / 8) struct sha1_ctx { uint32_t H[_SHA1_DIGEST_LENGTH]; /**< Intermediate hash value / digest at end of calculation */ uint8_t buffer[SHA1_BLOCK_SIZE]; /**< SHA256 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for SHA-1 calculation. * * @param ctx must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_); /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length); /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]); #endif /* MHD_SHA1_H */ libmicrohttpd-1.0.2/src/microhttpd_ws/test_websocket.c0000644000175000017500000137500014760713574020171 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021 David Gausmann libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_websocket.c * @brief Testcase for WebSocket decoding/encoding * @author David Gausmann */ #include "microhttpd.h" #include "microhttpd_ws.h" #include #include #include #include #include #if SIZE_MAX >= 0x100000000 #define ENABLE_64BIT_TESTS 1 #endif int disable_alloc = 0; size_t open_allocs = 0; /** * Custom `malloc()` function used for memory tests */ static void * test_malloc (size_t buf_len) { if (0 != disable_alloc) return NULL; void *result = malloc (buf_len); if (NULL != result) ++open_allocs; return result; } /** * Custom `realloc()` function used for memory tests */ static void * test_realloc (void *buf, size_t buf_len) { if (0 != disable_alloc) return NULL; void *result = realloc (buf, buf_len); if ((NULL != result) && (NULL == buf)) ++open_allocs; return result; } /** * Custom `free()` function used for memory tests */ static void test_free (void *buf) { if (NULL != buf) --open_allocs; free (buf); } /** * Custom `rng()` function used for client mode tests */ static size_t test_rng (void *cls, void *buf, size_t buf_len) { for (size_t i = 0; i < buf_len; ++i) { ((char *) buf) [i] = (char) (rand () % 0xFF); } return buf_len; } /** * Helper function which allocates a big amount of data */ static void allocate_length_test_data (char **buf1, char **buf2, size_t buf_len, const char *buf1_prefix, size_t buf1_prefix_len) { if (NULL != *buf1) free (*buf1); if (NULL != *buf2) free (*buf2); *buf1 = (char *) malloc (buf_len + buf1_prefix_len); *buf2 = (char *) malloc (buf_len); if ((NULL == buf1) || (NULL == buf2)) return; memcpy (*buf1, buf1_prefix, buf1_prefix_len); for (size_t i = 0; i < buf_len; i += 64) { size_t bytes_to_copy = buf_len - i; if (64 < bytes_to_copy) bytes_to_copy = 64; memcpy (*buf1 + i + buf1_prefix_len, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-", bytes_to_copy); memcpy (*buf2 + i, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-", bytes_to_copy); } } /** * Helper function which performs a single decoder test */ static int test_decode_single (unsigned int test_line, int flags, size_t max_payload_size, size_t decode_count, size_t buf_step, const char *buf, size_t buf_len, const char *expected_payload, size_t expected_payload_len, int expected_return, int expected_valid, size_t expected_streambuf_read_len) { struct MHD_WebSocketStream *ws = NULL; int ret = MHD_WEBSOCKET_STATUS_OK; /* initialize stream */ ret = MHD_websocket_stream_init2 (&ws, flags, max_payload_size, malloc, realloc, free, NULL, test_rng); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Allocation failed for decode test in line %u.\n", (unsigned int) test_line); return 1; } /* perform decoding in a loop */ size_t streambuf_read_len = 0; size_t payload_len = 0; char *payload = NULL; for (size_t i = 0; i < decode_count; ++i) { size_t streambuf_read_len_ = 0; size_t bytes_to_take = buf_len - streambuf_read_len; if ((0 != buf_step) && (buf_step < bytes_to_take)) bytes_to_take = buf_step; ret = MHD_websocket_decode (ws, buf + streambuf_read_len, bytes_to_take, &streambuf_read_len_, &payload, &payload_len); streambuf_read_len += streambuf_read_len_; if (i + 1 < decode_count) { if (payload) { MHD_websocket_free (ws, payload); payload = NULL; payload_len = 0; } } } /* check the (last) result */ if (ret != expected_return) { fprintf (stderr, "Decode test failed in line %u: The return value should be %d, but is %d\n", (unsigned int) test_line, (int) expected_return, (int) ret); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } if (payload_len != expected_payload_len) { fprintf (stderr, "Decode test failed in line %u: The payload_len should be %u, but is %u\n", (unsigned int) test_line, (unsigned int) expected_payload_len, (unsigned int) payload_len); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } if (0 != payload_len) { if (NULL == payload) { fprintf (stderr, "Decode test failed in line %u: The payload is NULL\n", (unsigned int) test_line); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } else if (NULL == expected_payload) { fprintf (stderr, "Decode test failed in line %u: The expected_payload is NULL (wrong test declaration)\n", (unsigned int) test_line); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } else if (0 != memcmp (payload, expected_payload, payload_len)) { fprintf (stderr, "Decode test failed in line %u: The payload differs from the expected_payload\n", (unsigned int) test_line); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } } else { if (NULL != payload) { fprintf (stderr, "Decode test failed in line %u: The payload is not NULL, but payload_len is 0\n", (unsigned int) test_line); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } else if (NULL != expected_payload) { fprintf (stderr, "Decode test failed in line %u: The expected_payload is not NULL, but expected_payload_len is 0 (wrong test declaration)\n", (unsigned int) test_line); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } } if (streambuf_read_len != expected_streambuf_read_len) { fprintf (stderr, "Decode test failed in line %u: The streambuf_read_len should be %u, but is %u\n", (unsigned int) test_line, (unsigned int) expected_streambuf_read_len, (unsigned int) streambuf_read_len); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } ret = MHD_websocket_stream_is_valid (ws); if (ret != expected_valid) { fprintf (stderr, "Decode test failed in line %u: The stream validity should be %u, but is %u\n", (unsigned int) test_line, (int) expected_valid, (int) ret); MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 1; } /* cleanup */ MHD_websocket_free (ws, payload); MHD_websocket_stream_free (ws); return 0; } /** * Test procedure for `MHD_websocket_stream_init()` and * `MHD_websocket_stream_init2()` */ int test_inits () { int failed = 0; struct MHD_WebSocketStream *ws; int ret; /* ------------------------------------------------------------------------------ All valid flags ------------------------------------------------------------------------------ */ /* Regular test: all valid flags for init (only the even ones work) */ for (int i = 0; i < 7; ++i) { ws = NULL; ret = MHD_websocket_stream_init (&ws, i, 0); if (((0 == (i & MHD_WEBSOCKET_FLAG_CLIENT)) && ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws))) || ((0 != (i & MHD_WEBSOCKET_FLAG_CLIENT)) && ((MHD_WEBSOCKET_STATUS_OK == ret) || (NULL != ws)))) { fprintf (stderr, "Init test failed in line %u for flags %d.\n", (unsigned int) __LINE__, (int) i); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } } /* Regular test: all valid flags for init2 */ for (int i = 0; i < 7; ++i) { ws = NULL; ret = MHD_websocket_stream_init2 (&ws, i, 0, test_malloc, test_realloc, test_free, NULL, test_rng); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for flags %d.\n", (unsigned int) __LINE__, (int) i); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } } /* Fail test: Invalid flags for init */ for (int i = 4; i < 32; ++i) { int flags = 1 << i; ws = NULL; ret = MHD_websocket_stream_init (&ws, flags, 0); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u for invalid flags %d.\n", (unsigned int) __LINE__, (int) flags); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } } /* Fail test: Invalid flag for init2 */ for (int i = 4; i < 32; ++i) { int flags = 1 << i; ws = NULL; ret = MHD_websocket_stream_init2 (&ws, flags, 0, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u for invalid flags %d.\n", (unsigned int) __LINE__, (int) flags); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } } /* ------------------------------------------------------------------------------ max_payload_size ------------------------------------------------------------------------------ */ /* Regular test: max_payload_size = 0 for init */ ws = NULL; ret = MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: max_payload_size = 0 for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Edge test (success): max_payload_size = 1 for init */ ws = NULL; ret = MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 1); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 1.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Edge test (success): max_payload_size = 1 for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 1, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 1.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: max_payload_size = 1000 for init */ ws = NULL; ret = MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 1000); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 1000.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: max_payload_size = 1000 for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 1000, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 1000.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } #ifdef ENABLE_64BIT_TESTS /* Edge test (success): max_payload_size = 0x7FFFFFFFFFFFFFFF for init */ ws = NULL; ret = MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, (uint64_t) 0x7FFFFFFFFFFFFFFF); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0x7FFFFFFFFFFFFFFF.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Edge test (success): max_payload_size = 0x7FFFFFFFFFFFFFFF for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, (uint64_t) 0x7FFFFFFFFFFFFFFF, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0x7FFFFFFFFFFFFFFF.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Edge test (fail): max_payload_size = 0x8000000000000000 for init */ ws = NULL; ret = MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, (uint64_t) 0x8000000000000000); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0x8000000000000000.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Edge test (fail): max_payload_size = 0x8000000000000000 for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, (uint64_t) 0x8000000000000000, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u for max_payload_size 0x8000000000000000.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } #endif /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: websocket stream variable missing for init */ ws = NULL; ret = MHD_websocket_stream_init (NULL, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Fail test: websocket stream variable missing for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (NULL, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Fail test: malloc missing for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, NULL, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Fail test: realloc missing for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, NULL, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Fail test: free missing for init2 */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, NULL, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: rng given for server mode (will be ignored) */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, test_rng); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: cls_rng given for server mode (will be ignored) */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, (void *) 12345, test_rng); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Regular test: rng given for client mode */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, test_rng); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL == ws) ) { fprintf (stderr, "Init test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } /* Fail test: rng not given for client mode */ ws = NULL; ret = MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != ws) ) { fprintf (stderr, "Init test failed in line %u %u.\n", (unsigned int) __LINE__, ret); ++failed; } if (NULL != ws) { MHD_websocket_stream_free (ws); ws = NULL; } return failed != 0 ? 0x01 : 0x00; } /** * Test procedure for `MHD_websocket_create_accept_header()` */ int test_accept () { int failed = 0; char accept_key[29]; int ret; /* ------------------------------------------------------------------------------ accepting ------------------------------------------------------------------------------ */ /* Regular test: Test case from RFC6455 4.2.2 */ memset (accept_key, 0, 29); ret = MHD_websocket_create_accept_header ("dGhlIHNhbXBsZSBub25jZQ==", accept_key); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != memcmp (accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", 29))) { fprintf (stderr, "Accept test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: missing sec-key value */ memset (accept_key, 0, 29); ret = MHD_websocket_create_accept_header (NULL, accept_key); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "Accept test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: missing accept variable */ memset (accept_key, 0, 29); ret = MHD_websocket_create_accept_header ("dGhlIHNhbXBsZSBub25jZQ==", NULL); if (MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) { fprintf (stderr, "Accept test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x02 : 0x00; } /** * Test procedure for `MHD_websocket_decode()` */ int test_decodes () { int failed = 0; char *buf1 = NULL, *buf2 = NULL; /* ------------------------------------------------------------------------------ text frame ------------------------------------------------------------------------------ */ /* Regular test: Masked text frame from RFC 6455, must succeed for server */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58", 11, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Unmasked text frame from RFC 6455, must succeed for client */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x05\x48\x65\x6c\x6c\x6f", 7, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Fail test: Unmasked text frame from RFC 6455, must fail for server */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x05\x48\x65\x6c\x6c\x6f", 7, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Masked text frame from RFC 6455, must fail for client */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Text frame with UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x90\x00\x00\x00\x00" "This is my n" "\xC3\xB6" "te", 22, "This is my n" "\xC3\xB6" "te", 16, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 22); /* Fail test: Text frame with with invalid UTF-8 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8F\x00\x00\x00\x00" "This is my n" "\xFF" "te", 21, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 18); /* Fail test: Text frame with broken UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8F\x00\x00\x00\x00" "This is my n" "\xC3" "te", 21, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 19); /* Regular test: Text frame without payload and mask (caller = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x80\x01\x02\x03\x04", 6, NULL, 0, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Fail test: Text frame without payload and no mask (caller = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Text frame without payload and mask (caller = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 2); /* Fail test: Text frame without payload and no mask (caller = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x80\x01\x02\x03\x04", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* ------------------------------------------------------------------------------ binary frame ------------------------------------------------------------------------------ */ /* Regular test: Masked binary frame (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58", 11, "Hello", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Unmasked binary frame (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x05\x48\x65\x6c\x6c\x6f", 7, "Hello", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Fail test: Unmasked binary frame (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x05\x48\x65\x6c\x6c\x6f", 7, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Masked binary frame (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Binary frame without payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Regular test: Fragmented binary frame without payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00", 12, NULL, 0, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 12); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00", 12, NULL, 0, MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00", 12, NULL, 0, MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 12); /* Regular test: Fragmented binary frame with payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06", 18, "\x01\x02\x03\x04\x05\x06", 6, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 18); /* Regular test: Fragmented binary frame with payload, fragments to the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06", 18, "\x01\x02\x03", 3, MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 9); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06", 18, "\x04\x05\x06", 3, MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 18); /* Regular test: Fragmented binary frame with payload, fragments to the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C", 36, "\x01\x02\x03", 3, MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 9); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C", 36, "\x04\x05\x06", 3, MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 18); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 3rd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 3, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C", 36, "\x07\x08\x09", 3, MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 27); /* Regular test: Fragmented binary frame without payload, fragments to the caller, 4th call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 4, 0, "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C", 36, "\x0A\x0B\x0C", 3, MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 36); /* Regular test: Binary frame with bytes which look like invalid UTF-8 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x85\x00\x00\x00\x00" "Hell\xf6", 11, "Hell\xf6", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Binary frame with bytes which look like broken UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x85\x00\x00\x00\x00" "H\xC3llo", 11, "H\xC3llo", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Binary frame with bytes which look like valid UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x82\x85\x00\x00\x00\x00" "H\xC3\xA4lo", 11, "H\xC3\xA4lo", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x02\x82\x00\x00\x00\x00" "H\xC3" "\x80\x83\x00\x00\x00\x00" "\xA4lo", 17, "H\xC3\xA4lo", 5, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence, fragments to the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x02\x82\x00\x00\x00\x00" "H\xC3" "\x80\x83\x00\x00\x00\x00" "\xA4lo", 17, "H\xC3", 2, MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 8); /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence, fragments to the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x02\x82\x00\x00\x00\x00" "H\xC3" "\x80\x83\x00\x00\x00\x00" "\xA4lo", 17, "\xA4lo", 3, MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* ------------------------------------------------------------------------------ close frame ------------------------------------------------------------------------------ */ /* Regular test: Close frame with no payload but with mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 6); /* Regular test: Close frame with no payload (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 2); /* Fail test: Close frame with no payload and no mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Close frame with no payload but with mask (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Close frame with 2 byte payload for close reason */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x82\x00\x00\x00\x00\x03\xEB", 8, "\x03\xEB", 2, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 8); /* Fail test: Close frame with 1 byte payload (no valid close reason) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x81\x00\x00\x00\x00\x03", 7, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Close frame with close reason and UTF-8 description */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x95\x00\x00\x00\x00\x03\xEB" "Something was wrong", 27, "\x03\xEB" "Something was wrong", 21, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 27); /* Regular test: Close frame with close reason and UTF-8 description (with UTF-8 sequence) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x96\x00\x00\x00\x00\x03\xEB" "Something was wr" "\xC3\xB6" "ng", 28, "\x03\xEB" "Something was wr" "\xC3\xB6" "ng", 22, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 28); /* Fail test: Close frame with close reason and invalid UTF-8 in description */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x95\x00\x00\x00\x00\x03\xEB" "Something was wr" "\xFF" "ng", 27, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 24); /* Fail test: Close frame with close reason and broken UTF-8 sequence in description */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x95\x00\x00\x00\x00\x03\xEB" "Something was wr" "\xC3" "ng", 27, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 25); /* Edge test (success): Close frame with 125 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFD\x00\x00\x00\x00\x03\xEB" "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. :-)", 131, "\x03\xEB" "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. :-)", 125, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 131); /* Edge test (failure): Close frame with 126 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFE\x00\x7e\x00\x00\x00\x00\x03\xEB" "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. >:-)", 134, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Close frame with 500 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFE\x01\xf4\x00\x00\x00\x00\x03\xEB" "The payload of this test isn't parsed.", 49, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Edge test (failure): Close frame with 65535 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFE\xff\xff\x00\x00\x00\x00\x03\xEB" "The payload of this test isn't parsed.", 49, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Edge test (failure): Close frame with 65536 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFF\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03\xEB" "The payload of this test isn't parsed.", 54, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Close frame with 1000000 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\xFF\x00\x00\x00\x00\x00\x0F\x42\x40\x00\x00\x00\x00\x03\xEB" "The payload of this test isn't parsed.", 54, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* ------------------------------------------------------------------------------ ping frame ------------------------------------------------------------------------------ */ /* Regular test: Ping frame with no payload but with mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Regular test: Ping frame with no payload (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 2); /* Fail test: Ping frame with no payload and no mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Ping frame with no payload but with mask (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Ping frame with some (masked) payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x88\x01\x20\x03\x40\xFF\xFF\xFF\xFF\x00\x00\x00\x00", 14, "\xFE\xDF\xFC\xBF\x01\x20\x03\x40", 8, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 14); /* Edge test (success): Ping frame with one byte of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x81\x00\x00\x00\x00" "a", 7, "a", 1, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Edge test (success): Ping frame with 125 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\xFD\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 131, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 131); /* Edge test (fail): Ping frame with 126 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\xFE\x00\x7E\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 134, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Ping frame with UTF-8 data */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x90\x00\x00\x00\x00" "Ping is bin" "\xC3\xA4" "ry.", 22, "Ping is bin" "\xC3\xA4" "ry.", 16, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 22); /* Regular test: Ping frame with invalid UTF-8 data */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x8F\x00\x00\x00\x00" "Ping is bin" "\xFF" "ry.", 21, "Ping is bin" "\xFF" "ry.", 15, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 21); /* Regular test: Ping frame with broken UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x8F\x00\x00\x00\x00" "Ping is bin" "\xC3" "ry.", 21, "Ping is bin" "\xC3" "ry.", 15, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 21); /* ------------------------------------------------------------------------------ pong frame ------------------------------------------------------------------------------ */ /* Regular test: Pong frame with no payload but with mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Regular test: Pong frame with no payload (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 2); /* Fail test: Pong frame with no payload and no mask (decoder = server) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x00", 2, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Fail test: Pong frame with no payload but with mask (decoder = client) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_CLIENT | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Pong frame with some (masked) payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x88\x01\x20\x03\x40\xFF\xFF\xFF\xFF\x00\x00\x00\x00", 14, "\xFE\xDF\xFC\xBF\x01\x20\x03\x40", 8, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 14); /* Edge test (success): Pong frame with one byte of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x81\x00\x00\x00\x00" "a", 7, "a", 1, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Edge test (success): Pong frame with 125 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\xFD\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 131, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 131); /* Edge test (fail): Pong frame with 126 bytes of payload */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\xFE\x00\x7E\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 134, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 1); /* Regular test: Pong frame with UTF-8 data */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x90\x00\x00\x00\x00" "Pong is bin" "\xC3\xA4" "ry.", 22, "Pong is bin" "\xC3\xA4" "ry.", 16, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 22); /* Regular test: Pong frame with invalid UTF-8 data */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x8F\x00\x00\x00\x00" "Pong is bin" "\xFF" "ry.", 21, "Pong is bin" "\xFF" "ry.", 15, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 21); /* Regular test: Pong frame with broken UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8A\x8F\x00\x00\x00\x00" "Pong is bin" "\xC3" "ry.", 21, "Pong is bin" "\xC3" "ry.", 15, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 21); /* ------------------------------------------------------------------------------ fragmentation ------------------------------------------------------------------------------ */ /* Regular test: Fragmented, masked text frame, we are the server and don't want fragments as caller */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58", 17, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented, masked text frame, we are the server and don't want fragments as caller, but call decode two times */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58", 17, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, one call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58", 17, "Hel", 3, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 9); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, second call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58", 17, "lo", 2, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, third call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 3, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58", 17, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58", 23, "Hel", 3, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 9); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58", 23, "l", 1, MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 3rd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 3, 0, "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58", 23, "o", 1, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 23); /* ------------------------------------------------------------------------------ invalid flags ------------------------------------------------------------------------------ */ /* Regular test: Template with valid data for the next tests (this one must succeed) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x85\x00\x00\x00\x00Hello", 11, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Fail test: RSV1 flag set */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x91\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: RSV2 flag set */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\xA1\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: RSV3 flag set */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\xC1\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* ------------------------------------------------------------------------------ invalid opcodes ------------------------------------------------------------------------------ */ /* Fail test: Invalid opcode 0 (0 is usually valid, but only if there was a data frame before) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x80\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 3 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x83\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 4 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x84\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 5 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x85\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 6 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x86\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 7 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x87\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 0x0B */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8B\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 0x0C */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8c\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 0x0D */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8d\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 0x0E */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8e\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Invalid opcode 0x0F */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x8f\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* ------------------------------------------------------------------------------ control frames without FIN flag ------------------------------------------------------------------------------ */ /* Fail test: Close frame without FIN flag */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x08\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Ping frame without FIN flag */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x09\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Fail test: Pong frame without FIN flag */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x0a\x85\x00\x00\x00\x00Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* ------------------------------------------------------------------------------ length checks (without max_payload_len) ------------------------------------------------------------------------------ */ /* Edge test (success): 0 bytes of payload (requires 1 byte length) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x80\x00\x00\x00\x00", 6, NULL, 0, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 6); /* Edge test (success): 1 byte of payload (requires 1 byte length) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x81\x00\x00\x00\x00" "a", 7, "a", 1, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Edge test (success): 125 bytes of payload (requires 1 byte length) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xfd\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 131, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 131); /* Edge test (success): 126 bytes of payload (requires 2 byte length) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xfe\x00\x7e\x00\x00\x00\x00" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 134, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 126, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 134); /* Edge test (success): 65535 bytes of payload (requires 2 byte length) */ allocate_length_test_data (&buf1, &buf2, 65535, "\x81\xfe\xff\xff\x00\x00\x00\x00", 8); failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, buf1, 65535 + 8, buf2, 65535, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 65535 + 8); /* Edge test (success): 65536 bytes of payload (requires 8 byte length) */ allocate_length_test_data (&buf1, &buf2, 65536, "\x81\xff\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00", 14); failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, buf1, 65536 + 14, buf2, 65536, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 65536 + 14); /* Regular test: 1 MB of payload */ allocate_length_test_data (&buf1, &buf2, 1048576, "\x81\xff\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00", 14); failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, buf1, 1048576 + 14, buf2, 1048576, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 1048576 + 14); /* Regular test: 100 MB of payload */ allocate_length_test_data (&buf1, &buf2, 104857600, "\x81\xff\x00\x00\x00\x00\x06\x40\x00\x00\x00\x00\x00\x00", 14); failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, buf1, 104857600 + 14, buf2, 104857600, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 104857600 + 14); if (NULL != buf1) { free (buf1); buf1 = NULL; } if (NULL != buf2) { free (buf2); buf2 = NULL; } #ifdef ENABLE_64BIT_TESTS /* Edge test (success): Maximum allowed length (here is only the header checked) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\x7f\xff\xff\xff\xff\xff\xff\xff", 10, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 10); #else /* Edge test (fail): Maximum allowed length (the size is allowed, but the system cannot handle this amount of memory) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\x7f\xff\xff\xff\xff\xff\xff\xff", 10, NULL, 0, MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED, MHD_WEBSOCKET_VALIDITY_INVALID, 10); #endif /* Edge test (fail): Too big payload length */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\x80\x00\x00\x00\x00\x00\x00\x00", 10, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* Edge test (fail): Too big payload length */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\xff\xff\xff\xff\xff\xff\xff\xff", 10, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* Fail test: Not the smallest payload length syntax used (2 byte instead of 1 byte) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xfe\x00\x05\x00\x00\x00\x00" "abcde", 13, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 4); /* Fail test: Not the smallest payload length syntax used (8 byte instead of 1 byte) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00" "abcde", 13, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* Fail test: Not the smallest payload length syntax used (8 byte instead of 2 byte) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\xff\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00" "abcde", 13, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* ------------------------------------------------------------------------------ length checks (with max_payload_len) ------------------------------------------------------------------------------ */ /* Regular test: Frame with less payload than specified as limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 100, 1, 0, "\x81\x85\x00\x00\x00\x00" "Hello", 11, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Edge test (success): Frame with the same payload as the specified limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 5, 1, 0, "\x81\x85\x00\x00\x00\x00" "Hello", 11, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Edge test (fail): Frame with more payload than specified as limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 4, 1, 0, "\x81\x85\x00\x00\x00\x00" "Hello", 11, NULL, 0, MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED, MHD_WEBSOCKET_VALIDITY_INVALID, 2); /* Regular test: Fragmented frames with the sum of payload less than specified as limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 100, 1, 0, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Edge test (success): Fragmented frames with the sum of payload equal to the specified limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 5, 1, 0, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, "Hello", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Edge test (fail): Fragmented frames with the sum of payload more than specified as limit */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 4, 1, 0, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, NULL, 0, MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED, MHD_WEBSOCKET_VALIDITY_INVALID, 15); /* Edge test (success): Fragmented frames with the sum of payload greater than the specified limit, but we take fragments (one call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 5, 1, 0, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, "Hel", 3, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 9); /* Edge test (success): Fragmented frames with the sum of payload greater than the specified limit, but we take fragments (two calls) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 5, 2, 0, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, "lo", 2, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* ------------------------------------------------------------------------------ UTF-8 sequences ------------------------------------------------------------------------------ */ /* Regular test: No UTF-8 characters */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 a ", 16, " a ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Fail test: A UTF-8 tail character without sequence start character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xA4 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Regular test: A two byte UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xC3\xA4 ", 16, " \xC3\xA4 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Fail test: A broken two byte UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xC3 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Fail test: A two byte UTF-8 sequence with one UTF-8 tail too much */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xC3\xA4\xA4 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 9); /* Regular test: A three byte UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\x8F\x8F ", 16, " \xEF\x8F\x8F ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Fail test: A broken byte UTF-8 sequence (two of three bytes) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 9); /* Fail test: A broken byte UTF-8 sequence (one of three bytes) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Fail test: A three byte UTF-8 sequence followed by one UTF-8 tail byte */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* Regular test: A four byte UTF-8 sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F\x8F ", 16, " \xF2\x8F\x8F\x8F ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Fail test: A broken four byte UTF-8 sequence (three of four bytes) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 10); /* Fail test: A broken four byte UTF-8 sequence (two of four bytes) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF2\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 9); /* Fail test: A broken four byte UTF-8 sequence (one of four bytes) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF2 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Fail test: A four byte UTF-8 sequence followed by UTF-8 tail */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 11); /* Fail test: A five byte UTF-8 sequence (only up to four bytes allowed) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xFB\x8F\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Fail test: A six byte UTF-8 sequence (only up to four bytes allowed) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xFD\x8F\x8F\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Fail test: A seven byte UTF-8 sequence (only up to four bytes allowed) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xFE\x8F\x8F\x8F\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Fail test: A eight byte UTF-8 sequence (only up to four bytes allowed) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xFF\x8F\x8F\x8F\x8F\x8F\x8F\x8F ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Edge test (success): The maximum allowed UTF-8 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF4\x8F\xBF\xBF ", 16, " \xF4\x8F\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The maximum allowed UTF-8 character + 1 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF4\x90\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The last valid UTF8-1 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \x7F ", 16, " \x7F ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the last valid UTF8-1 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Edge test (fail): The value before the first valid UTF8-2 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xC1\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Edge test (success): The first valid UTF8-2 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xC2\x80 ", 16, " \xC2\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-2 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xDF\xBF ", 16, " \xDF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the lst valid UTF8-2 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE0\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): The value before the first valid UTF8-3 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE0\x9F\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-3 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE0\xA0\x80 ", 16, " \xE0\xA0\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-3 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE0\xBF\xBF ", 16, " \xE0\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the first valid UTF8-3 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE0\xC0\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-3 character (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xE1\x80\x80 ", 16, " \xE1\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-3 character (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEC\xBF\xBF ", 16, " \xEC\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the last valid UTF8-3 character (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEC\xC0\xBF ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): The value before the first valid UTF8-3 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xED\x7F\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-3 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xED\x80\x80 ", 16, " \xED\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-3 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xED\x9F\xBF ", 16, " \xED\x9F\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the last valid UTF8-3 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xED\xA0\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): The value before the first valid UTF8-3 character (tail 4) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEE\x7F\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-3 character (tail 4) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEE\x80\x80 ", 16, " \xEE\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-3 character (tail 4) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\xBF\xBF ", 16, " \xEF\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the last valid UTF8-3 character (tail 4) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\xBF\xC0 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 9); /* Edge test (fail): The value after the last valid UTF8-3 character (tail 4) #2 */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xEF\xC0\xBF ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): The value before the first valid UTF8-4 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF0\x8F\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-4 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF0\x90\x80\x80 ", 16, " \xF0\x90\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-4 character (tail 1) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF0\xBF\xBF\xBF ", 16, " \xF0\xBF\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The first valid UTF8-4 character (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF1\x80\x80\x80 ", 16, " \xF1\x80\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-4 character (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF3\xBF\xBF\xBF ", 16, " \xF3\xBF\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): A value before the last valid UTF8-4 character in the second byte (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF3\x7F\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): A value after the last valid UTF8-4 character in the second byte (tail 2) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF3\xC0\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (success): The first valid UTF8-4 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF4\x80\x80\x80 ", 16, " \xF4\x80\x80\x80 ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (success): The last valid UTF8-4 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF4\x8F\xBF\xBF ", 16, " \xF4\x8F\xBF\xBF ", 10, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 16); /* Edge test (fail): The value after the last valid UTF8-4 character (tail 3) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF4\x90\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 8); /* Edge test (fail): The first byte value the last valid UTF8-4 character */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x8A\x00\x00\x00\x00 \xF5\x90\x80\x80 ", 16, NULL, 0, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* ------------------------------------------------------------------------------ Unfinished UTF-8 sequence between fragmented text frame ------------------------------------------------------------------------------ */ /* Regular test: UTF-8 sequence between fragments, no fragmentation for the caller */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x8D\x00\x00\x00\x00" "This is my n" "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te", 28, "This is my n" "\xC3\xB6" "te", 16, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 28); /* Regular test: UTF-8 sequence between fragments, fragmentation for the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x8D\x00\x00\x00\x00" "This is my n" "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te", 28, "This is my n", 12, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 19); /* Regular test: UTF-8 sequence between fragments, fragmentation for the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x8D\x00\x00\x00\x00" "This is my n" "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te", 28, "\xC3\xB6" "te", 4, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 28); /* Edge test (success): UTF-8 sequence between fragments, but nothing before, fragmentation for the caller, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x81\x00\x00\x00\x00\xC3\x80\x81\x00\x00\x00\x00\xB6", 14, NULL, 0, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 7); /* Edge test (success): UTF-8 sequence between fragments, but nothing before, fragmentation for the caller, 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x81\x00\x00\x00\x00\xC3\x80\x81\x00\x00\x00\x00\xB6", 14, "\xC3\xB6", 2, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 14); /* ------------------------------------------------------------------------------ Decoding with broken stream ------------------------------------------------------------------------------ */ /* Failure test: Invalid sequence */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\xFF\x81\x85\x00\x00\x00\x00" "Hello", 12, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Failure test: Call after invalidated stream */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\xFF\x81\x85\x00\x00\x00\x00" "Hello", 12, NULL, 0, MHD_WEBSOCKET_STATUS_STREAM_BROKEN, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Failure test: Call after invalidated stream (but with different buffer) */ { struct MHD_WebSocketStream *ws; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0)) { size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; ret = MHD_websocket_decode (ws, "\xFF", 1, &streambuf_read_len, &payload, &payload_len); if (MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR != ret) { fprintf (stderr, "Test failed in line %u: The return value should be -1, but is %d\n", (unsigned int) __LINE__, (int) ret); ++failed; } else { ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00" "Hello", 11, &streambuf_read_len, &payload, &payload_len); if (MHD_WEBSOCKET_STATUS_STREAM_BROKEN != ret) { fprintf (stderr, "Test failed in line %u: The return value should be -2, but is %d\n", (unsigned int) __LINE__, (int) ret); ++failed; } } MHD_websocket_stream_free (ws); } else { fprintf (stderr, "Individual test failed in line %u\n", (unsigned int) __LINE__); ++failed; } } /* ------------------------------------------------------------------------------ frame after close frame ------------------------------------------------------------------------------ */ /* Regular test: Close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x88\x80\x00\x00\x00\x00\x81\x85\x00\x00\x00\x00" "Hello", 17, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 6); /* Failure test: Text frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x81\x85\x00\x00\x00\x00" "Hello", 17, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 6); /* Failure test: Binary frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x82\x85\x00\x00\x00\x00" "Hello", 17, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 6); /* Failure test: Continue frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x80\x85\x00\x00\x00\x00" "Hello", 17, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 6); /* Regular test: Ping frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x89\x85\x00\x00\x00\x00" "Hello", 17, "Hello", 5, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 17); /* Regular test: Pong frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x8A\x85\x00\x00\x00\x00" "Hello", 17, "Hello", 5, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 17); /* Regular test: Close frame after close frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x88\x80\x00\x00\x00\x00\x88\x80\x00\x00\x00\x00", 12, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 12); /* ------------------------------------------------------------------------------ decoding byte-by-byte ------------------------------------------------------------------------------ */ /* Regular test: Text frame, 2 bytes per loop, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 2, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 2); /* Regular test: Text frame, 2 bytes per loop, 11th call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 11, 2, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 22); /* Regular test: Text frame, 2 bytes per loop, 12th call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 12, 2, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, "This is the test.", 17, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 23); /* Regular test: Text frame, 1 byte per loop, 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 1, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 1); /* Regular test: Text frame, 1 byte per loop, 22nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 22, 1, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, NULL, 0, MHD_WEBSOCKET_STATUS_OK, MHD_WEBSOCKET_VALIDITY_VALID, 22); /* Regular test: Text frame, 1 byte per loop, 23rd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 23, 1, "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/", 23, "This is the test.", 17, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 23); /* ------------------------------------------------------------------------------ mix of fragmented data frames and control frames ------------------------------------------------------------------------------ */ /* Regular test: Fragmented text frame mixed with one ping frame (1st call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x89\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, NULL, 0, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented text frame mixed with one ping frame (2nd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x01\x85\x00\x00\x00\x00" "This \x89\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, "This is the test.", 17, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 35); /* Regular test: Fragmented text frame mixed with one close frame (1st call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x88\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 17); /* Fail test: Fragmented text frame mixed with one ping frame (2nd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x01\x85\x00\x00\x00\x00" "This \x88\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 17); /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (1st call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x89\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, "This ", 5, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (2nd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x85\x00\x00\x00\x00" "This \x89\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, NULL, 0, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 17); /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (3rd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 3, 0, "\x01\x85\x00\x00\x00\x00" "This \x89\x80\x00\x00\x00\x00" "\x80\x8C\x00\x00\x00\x00" "is the test.", 35, "is the test.", 12, MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 35); /* ------------------------------------------------------------------------------ mix of fragmented data frames and data frames ------------------------------------------------------------------------------ */ /* Fail test: Fragmented text frame mixed with one non-fragmented binary frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x82\x81\x00\x00\x00\x00" "a\x80\x8C\x00\x00\x00\x00" "is the test.", 36, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 11); /* Regular test: Fragmented text frame mixed with one non-fragmented binary frame; the caller wants fragments; 1st call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x82\x81\x00\x00\x00\x00" "a\x80\x8C\x00\x00\x00\x00" "is the test.", 36, "This ", 5, MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Fail test: Fragmented text frame mixed with one non-fragmented binary frame; the caller wants fragments; 2nd call */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0, 2, 0, "\x01\x85\x00\x00\x00\x00" "This \x82\x81\x00\x00\x00\x00" "a\x80\x8C\x00\x00\x00\x00" "is the test.", 36, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 11); /* Fail test: Fragmented text frame mixed with one fragmented binary frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x02\x81\x00\x00\x00\x00" "a\x80\x8C\x00\x00\x00\x00" "is the test.", 36, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 11); /* Fail test: Fragmented text frame, continue frame, non-fragmented binary frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x00\x8C\x00\x00\x00\x00" "is the test.\x82\x81\x00\x00\x00\x00" "a", 36, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 29); /* Fail test: Fragmented text frame, continue frame, fragmented binary frame */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x01\x85\x00\x00\x00\x00" "This \x00\x8C\x00\x00\x00\x00" "is the test.\x02\x81\x00\x00\x00\x00" "a", 36, NULL, 0, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 29); /* ------------------------------------------------------------------------------ multiple data frames ------------------------------------------------------------------------------ */ /* Regular test: Text frame, binary frame, text frame (1st call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x81\x85\x00\x00\x00\x00" "This \x82\x87\x00\x00\x00\x00" "is the \x81\x85\x00\x00\x00\x00" "test.", 35, "This ", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Text frame, binary frame, text frame (2nd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x81\x85\x00\x00\x00\x00" "This \x82\x87\x00\x00\x00\x00" "is the \x81\x85\x00\x00\x00\x00" "test.", 35, "is the ", 7, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 24); /* Regular test: Text frame, binary frame, text frame (3rd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 3, 0, "\x81\x85\x00\x00\x00\x00" "This \x82\x87\x00\x00\x00\x00" "is the \x81\x85\x00\x00\x00\x00" "test.", 35, "test.", 5, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 35); /* ------------------------------------------------------------------------------ multiple control frames ------------------------------------------------------------------------------ */ /* Regular test: Ping frame, pong frame, close frame (1st call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, "\x89\x85\x00\x00\x00\x00" "This \x8A\x87\x00\x00\x00\x00" "is the \x88\x85\x00\x00\x00\x00" "test.", 35, "This ", 5, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 11); /* Regular test: Ping frame, pong frame, close frame (2nd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 2, 0, "\x89\x85\x00\x00\x00\x00" "This \x8A\x87\x00\x00\x00\x00" "is the \x88\x85\x00\x00\x00\x00" "test.", 35, "is the ", 7, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, 24); /* Regular test: Ping frame, pong frame, close frame (3rd call) */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 3, 0, "\x89\x85\x00\x00\x00\x00" "This \x8A\x87\x00\x00\x00\x00" "is the \x88\x85\x00\x00\x00\x00" "test.", 35, "test.", 5, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, 35); /* ------------------------------------------------------------------------------ generated close frames for errors ------------------------------------------------------------------------------ */ /* Regular test: Close frame generated for protocol error */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS | MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR, 0, 1, 0, "\xFF", 1, "\x88\x02\x03\xEA", 4, MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 0); /* Regular test: Close frame generated for UTF-8 sequence error */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS | MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR, 0, 1, 0, "\x81\x85\x00\x00\x00\x00T\xFFst.", 11, "\x88\x02\x03\xEF", 4, MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR, MHD_WEBSOCKET_VALIDITY_INVALID, 7); /* Regular test: Close frame generated for message size exceeded */ failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS | MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR, 3, 1, 0, "\x81\x85\x00\x00\x00\x00T\xFFst.", 11, "\x88\x02\x03\xF1", 4, MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED, MHD_WEBSOCKET_VALIDITY_INVALID, 2); /* ------------------------------------------------------------------------------ terminating NUL character ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *ws; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0)) { size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; /* Regular test: text frame */ ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00" "Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) || (5 != payload_len) || (NULL == payload) || (0 != memcmp ("Hello", payload, 5 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: text frame fragment */ ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) || (5 != payload_len) || (NULL == payload) || (0 != memcmp ("Hello", payload, 5 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: binary frame */ ret = MHD_websocket_decode (ws, "\x82\x85\x00\x00\x00\x00" "Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_BINARY_FRAME != ret) || (5 != payload_len) || (NULL == payload) || (0 != memcmp ("Hello", payload, 5 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: binary frame fragment */ ret = MHD_websocket_decode (ws, "\x02\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_BINARY_FRAME != ret) || (5 != payload_len) || (NULL == payload) || (0 != memcmp ("Hello", payload, 5 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } MHD_websocket_stream_free (ws); } else { fprintf (stderr, "Individual decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } } { struct MHD_WebSocketStream *ws; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS, 0)) { size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; /* Regular test: text frame fragment (caller wants fragment, 1st call) */ ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo", 17, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT != ret) || (3 != payload_len) || (NULL == payload) || (0 != memcmp ("Hel", payload, 3 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: text frame fragment (caller wants fragment, 2nd call) */ ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "Hel\x80\x82\x00\x00\x00\x00" "lo" + streambuf_read_len, 17 - streambuf_read_len, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT != ret) || (2 != payload_len) || (NULL == payload) || (0 != memcmp ("lo", payload, 2 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: text frame fragment with broken UTF-8 sequence (caller wants fragment, 1st call) */ ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "He\xC3\x80\x82\x00\x00\x00\x00" "\xB6o", 17, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT != ret) || (2 != payload_len) || (NULL == payload) || (0 != memcmp ("He", payload, 2 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } /* Regular test: text frame fragment with broken UTF-8 sequence (caller wants fragment, 2nd call) */ ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "He\xC3\x80\x82\x00\x00\x00\x00" "\xB6o" + streambuf_read_len, 17 - streambuf_read_len, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT != ret) || (3 != payload_len) || (NULL == payload) || (0 != memcmp ("\xC3\xB6o", payload, 3 + 1))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != payload) { MHD_websocket_free (ws, payload); payload = NULL; } MHD_websocket_stream_free (ws); } else { fprintf (stderr, "Individual decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } } /* ------------------------------------------------------------------------------ invalid parameters ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *ws; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0)) { size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; /* Failure test: `ws` is NULL */ payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (NULL, "\x81\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != payload) || (0 != payload_len) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Failure test: `buf` is NULL, while `buf_len` != 0 */ payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, NULL, 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != payload) || (0 != payload_len) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Failure test: `streambuf_read_len` is NULL */ payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hello", 11, NULL, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != payload) || (0 != payload_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Failure test: `payload` is NULL */ payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, NULL, &payload_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != payload_len) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Failure test: `payload_len` is NULL */ payload = (char *) (uintptr_t) 0xBAADF00D; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != payload) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Regular test: `buf` is NULL and `buf_len` is 0 */ payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, NULL, 0, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL != payload) || (0 != payload_len) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Regular test: `buf` is not NULL and `buf_len` is 0 */ payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hello", 0, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL != payload) || (0 != payload_len) || (0 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } MHD_websocket_stream_free (ws); } else { fprintf (stderr, "Parameter decode tests failed in line %u\n", (unsigned int) __LINE__); ++failed; } } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *ws; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; /* Failure test: No memory allocation at the start */ disable_alloc = 1; payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (NULL != payload) || (0 != payload_len) || (1000 == streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Failure test: No memory allocation after fragmented frame */ disable_alloc = 0; payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x01\x83\x00\x00\x00\x00" "Hel", 9, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (NULL != payload) || (0 != payload_len) || (9 != streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid ( ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } disable_alloc = 1; payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; streambuf_read_len = 1000; ret = MHD_websocket_decode (ws, "\x80\x82\x00\x00\x00\x00" "lo", 8, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (NULL != payload) || (0 != payload_len) || (1000 == streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid ( ws))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } /* Regular test: Success after memory allocation ok again */ /* (streambuf_read_len may not be overwritten for this test) */ disable_alloc = 0; payload = (char *) (uintptr_t) 0xBAADF00D; payload_len = 0x87654321; size_t old_streambuf_read_len = streambuf_read_len; ret = MHD_websocket_decode (ws, "\x80\x82\x00\x00\x00\x00lo" + old_streambuf_read_len, 8 - old_streambuf_read_len, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) || (NULL == payload) || (5 != payload_len) || (8 != streambuf_read_len + old_streambuf_read_len) || (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid ( ws)) || (0 != memcmp ("Hello", payload, 5))) { fprintf (stderr, "Decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == payload) { payload = NULL; } if (NULL != payload) { MHD_websocket_free (ws, payload); } MHD_websocket_stream_free (ws); } else { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory decode tests failed in line %u\n", (unsigned int) __LINE__); ++failed; } } /* ------------------------------------------------------------------------------ memory leak test, when freeing while decoding ------------------------------------------------------------------------------ */ { disable_alloc = 0; struct MHD_WebSocketStream *ws; size_t streambuf_read_len = 0; char *payload = NULL; size_t payload_len = 0; int ret = 0; /* Regular test: Free while decoding of data frame */ open_allocs = 0; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { ret = MHD_websocket_decode (ws, "\x81\x85\x00\x00\x00\x00Hel", 9, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (9 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (0 != open_allocs) { fprintf (stderr, "Memory decode test failed in line %u (memory leak detected)\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: Free while decoding of control frame */ open_allocs = 0; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { ret = MHD_websocket_decode (ws, "\x88\x85\x00\x00\x00\x00Hel", 9, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (9 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (0 != open_allocs) { fprintf (stderr, "Memory decode test failed in line %u (memory leak detected)\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: Free while decoding of fragmented data frame */ open_allocs = 0; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { ret = MHD_websocket_decode (ws, "\x01\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (11 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (0 != open_allocs) { fprintf (stderr, "Memory decode test failed in line %u (memory leak detected)\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: Free while decoding of continued fragmented data frame */ open_allocs = 0; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { ret = MHD_websocket_decode (ws, "\x01\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (11 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_decode (ws, "\x80\x85\x00\x00\x00\x00Hel", 9, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (9 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (0 != open_allocs) { fprintf (stderr, "Memory decode test failed in line %u (memory leak detected)\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: Free while decoding of control frame during fragmented data frame */ open_allocs = 0; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { ret = MHD_websocket_decode (ws, "\x01\x85\x00\x00\x00\x00Hello", 11, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (11 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_decode (ws, "\x88\x85\x00\x00\x00\x00Hel", 9, &streambuf_read_len, &payload, &payload_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (0 != payload_len) || (NULL != payload) || (9 != streambuf_read_len) ) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } ret = MHD_websocket_stream_free (ws); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "Memory decode test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (0 != open_allocs) { fprintf (stderr, "Memory decode test failed in line %u (memory leak detected)\n", (unsigned int) __LINE__); ++failed; } } else { fprintf (stderr, "Memory test failed in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) { free (buf1); buf1 = NULL; } if (NULL != buf2) { free (buf2); buf2 = NULL; } return failed != 0 ? 0x04 : 0x00; } /** * Test procedure for `MHD_websocket_encode_text()` */ int test_encodes_text () { int failed = 0; struct MHD_WebSocketStream *wss; struct MHD_WebSocketStream *wsc; int ret; char *buf1 = NULL, *buf2 = NULL; char *frame = NULL; size_t frame_len = 0; int utf8_step = 0; if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc, MHD_WEBSOCKET_FLAG_CLIENT, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode text tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); return 0x08; } if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss, MHD_WEBSOCKET_FLAG_SERVER, 0)) { fprintf (stderr, "No encode text tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); if (NULL != wsc) MHD_websocket_stream_free (wsc); return 0x08; } /* ------------------------------------------------------------------------------ Encoding ------------------------------------------------------------------------------ */ /* Regular test: Some data without UTF-8, we are server */ ret = MHD_websocket_encode_text (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x09" "blablabla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data without UTF-8, we are client */ ret = MHD_websocket_encode_text (wsc, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (15 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "blablabla", 9, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Some data with UTF-8, we are server */ ret = MHD_websocket_encode_text (wss, "bla" "\xC3\xA4" "blabla", 11, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x0B" "bla" "\xC3\xA4" "blabla", 13))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data with UTF-8, we are client */ ret = MHD_websocket_encode_text (wsc, "bla" "\xC3\xA4" "blabla", 11, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (17 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "bla" "\xC3\xA4" "blabla", 11, MHD_WEBSOCKET_STATUS_TEXT_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Edge test (success): Some data with NUL characters, we are server */ ret = MHD_websocket_encode_text (wss, "bla" "\0\0\0" "bla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x09" "bla" "\0\0\0" "bla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: Some data with broken UTF-8, we are server */ ret = MHD_websocket_encode_text (wss, "bla" "\xC3" "blabla", 10, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Fragmentation ------------------------------------------------------------------------------ */ /* Regular test: Some data without UTF-8 */ ret = MHD_websocket_encode_text (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x81\x09" "blablabla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: First fragment without UTF-8 */ ret = MHD_websocket_encode_text (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_FIRST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x01\x09" "blablabla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Middle fragment without UTF-8 */ ret = MHD_websocket_encode_text (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x00\x09" "blablabla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment without UTF-8 */ ret = MHD_websocket_encode_text (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x09" "blablabla", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): First fragment with UTF-8 on the edge */ ret = MHD_websocket_encode_text (wss, "blablabl\xC3", 9, MHD_WEBSOCKET_FRAGMENTATION_FIRST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 != utf8_step) || (0 != memcmp (frame, "\x01\x09" "blablabl\xC3", 11))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Last fragment with UTF-8 on the edge */ ret = MHD_websocket_encode_text (wss, "\xA4" "blablabla", 10, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (12 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0A" "\xA4" "blablabla", 12))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: Last fragment with UTF-8 on the edge (here with wrong old utf8_step) */ utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL; ret = MHD_websocket_encode_text (wss, "\xA4" "blablabla", 10, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) || (0 != frame_len) || (NULL != frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF2TAIL_1OF1 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1; ret = MHD_websocket_encode_text (wss, "\xA4" "blablabla", 10, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (12 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0A" "\xA4" "blablabla", 12))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL1_1OF2 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2; ret = MHD_websocket_encode_text (wss, "\xA0\x80" "blablabla", 11, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0B" "\xA0\x80" "blablabla", 13))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL2_1OF2 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2; ret = MHD_websocket_encode_text (wss, "\x80\x80" "blablabla", 11, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0B" "\x80\x80" "blablabla", 13))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL_1OF2 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2; ret = MHD_websocket_encode_text (wss, "\x80\x80" "blablabla", 11, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0B" "\x80\x80" "blablabla", 13))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL_2OF2 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2; ret = MHD_websocket_encode_text (wss, "\x80" " blablabla", 11, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0B" "\x80" " blablabla", 13))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL1_1OF3 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3; ret = MHD_websocket_encode_text (wss, "\x90\x80\x80" "blablabla", 12, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (14 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0C" "\x90\x80\x80" "blablabla", 14))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL2_1OF3 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3; ret = MHD_websocket_encode_text (wss, "\x80\x80\x80" "blablabla", 12, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (14 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0C" "\x80\x80\x80" "blablabla", 14))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_1OF3 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3; ret = MHD_websocket_encode_text (wss, "\x80\x80\x80" "blablabla", 12, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (14 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0C" "\x80\x80\x80" "blablabla", 14))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_2OF3 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3; ret = MHD_websocket_encode_text (wss, "\x80\x80" " blablabla", 12, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (14 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0C" "\x80\x80" " blablabla", 14))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_3OF3 */ utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3; ret = MHD_websocket_encode_text (wss, "\x80" " blablabla", 12, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (14 != frame_len) || (NULL == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x0C" "\x80" " blablabla", 14))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Length checks ------------------------------------------------------------------------------ */ /* Edge test (success): Text frame without data */ ret = MHD_websocket_encode_text (wss, NULL, 0, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x00", 2))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Text frame with 1 byte of data */ ret = MHD_websocket_encode_text (wss, "a", 1, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (3 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x01" "a", 3))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Text frame with 125 bytes of data */ ret = MHD_websocket_encode_text (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (127 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x7D" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 127))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Text frame with 126 bytes of data */ ret = MHD_websocket_encode_text (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 126, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (130 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x7E\x00\x7E" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 130))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Text frame with 65535 bytes of data */ allocate_length_test_data (&buf1, &buf2, 65535, "\x81\x7E\xFF\xFF", 4); ret = MHD_websocket_encode_text (wss, buf2, 65535, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (65535 + 4 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 65535 + 4))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Text frame with 65536 bytes of data */ allocate_length_test_data (&buf1, &buf2, 65536, "\x81\x7F\x00\x00\x00\x00\x00\x01\x00\x00", 10); ret = MHD_websocket_encode_text (wss, buf2, 65536, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (65536 + 10 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 65536 + 10))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Text frame with 100 MB of data */ allocate_length_test_data (&buf1, &buf2, 104857600, "\x81\x7F\x00\x00\x00\x00\x06\x40\x00\x00", 10); ret = MHD_websocket_encode_text (wss, buf2, 104857600, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (104857600 + 10 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 104857600 + 10))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } if (NULL != buf1) { free (buf1); buf1 = NULL; } if (NULL != buf2) { free (buf2); buf2 = NULL; } #ifdef ENABLE_64BIT_TESTS /* Fail test: frame_len is greater than 0x7FFFFFFFFFFFFFFF (this is the maximum allowed payload size) */ frame_len = 0; ret = MHD_websocket_encode_text (wss, "abc", (uint64_t) 0x8000000000000000, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } #endif /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `ws` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (NULL, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `payload_utf8` not passed, but `payload_utf8_len` != 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, NULL, 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `payload_utf8` passed, but `payload_utf8_len` == 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, "abc", 0, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x81\x00", 2))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `frame` not passed */ frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, NULL, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Fail test: `frame_len` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, NULL, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `utf8_step` passed for non-fragmentation (is allowed and `utf8_step` will be filled then) */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = -99; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x81\x03" "abc", 5))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `utf8_step` passed for non-fragmentation with invalid UTF-8 (is allowed and `utf8_step` will be filled then) */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = -99; ret = MHD_websocket_encode_text (wss, "ab\xC3", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) || (0 != frame_len) || (NULL != frame) || (MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 != utf8_step) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `utf8_step` not passed for fragmentation #1 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_FIRST, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `utf8_step` not passed for fragmentation #2 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `utf8_step` not passed for fragmentation #3 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `utf8_step` passed for fragmentation #1 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = -99; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_FIRST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x01\x03" "abc", 5))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `utf8_step` passed for fragmentation #2 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x00\x03" "abc", 5))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `utf8_step` passed for fragmentation #3 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) || (0 != memcmp (frame, "\x80\x03" "abc", 5))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `fragmentation` has an invalid value */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; utf8_step = -99; ret = MHD_websocket_encode_text (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_LAST + 1, &frame, &frame_len, &utf8_step); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) || (-99 != utf8_step) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *wsx; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx, MHD_WEBSOCKET_FLAG_SERVER, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Fail test: allocation while no memory available */ disable_alloc = 1; ret = MHD_websocket_encode_text (wsx, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } /* Regular test: allocation while memory is available again */ disable_alloc = 0; ret = MHD_websocket_encode_text (wsx, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x81\x03" "abc", 5))) { fprintf (stderr, "Encode text test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } MHD_websocket_stream_free (wsx); } else { fprintf (stderr, "Couldn't perform memory test for text encoding in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) free (buf1); if (NULL != buf2) free (buf2); if (NULL != wsc) MHD_websocket_stream_free (wsc); if (NULL != wss) MHD_websocket_stream_free (wss); return failed != 0 ? 0x08 : 0x00; } /** * Test procedure for `MHD_websocket_encode_binary()` */ int test_encodes_binary () { int failed = 0; struct MHD_WebSocketStream *wss; struct MHD_WebSocketStream *wsc; int ret; char *buf1 = NULL, *buf2 = NULL; char *frame = NULL; size_t frame_len = 0; if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc, MHD_WEBSOCKET_FLAG_CLIENT, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode binary tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); return 0x10; } if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss, MHD_WEBSOCKET_FLAG_SERVER, 0)) { fprintf (stderr, "No encode binary tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); if (NULL != wsc) MHD_websocket_stream_free (wsc); return 0x10; } /* ------------------------------------------------------------------------------ Encoding ------------------------------------------------------------------------------ */ /* Regular test: Some data, we are server */ ret = MHD_websocket_encode_binary (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x09" "blablabla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data, we are client */ ret = MHD_websocket_encode_binary (wsc, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (15 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "blablabla", 9, MHD_WEBSOCKET_STATUS_BINARY_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Edge test (success): Some data with NUL characters, we are server */ ret = MHD_websocket_encode_binary (wss, "bla" "\0\0\0" "bla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x09" "bla" "\0\0\0" "bla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data which looks like broken UTF-8, we are server */ ret = MHD_websocket_encode_binary (wss, "bla" "\xC3" "blabla", 10, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (12 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x0A" "bla" "\xC3" "blabla", 12))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Fragmentation ------------------------------------------------------------------------------ */ /* Regular test: Some data */ ret = MHD_websocket_encode_binary (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x09" "blablabla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: First fragment */ ret = MHD_websocket_encode_binary (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_FIRST, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x02\x09" "blablabla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Middle fragment */ ret = MHD_websocket_encode_binary (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x00\x09" "blablabla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Last fragment */ ret = MHD_websocket_encode_binary (wss, "blablabla", 9, MHD_WEBSOCKET_FRAGMENTATION_LAST, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x80\x09" "blablabla", 11))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Length checks ------------------------------------------------------------------------------ */ /* Edge test (success): Binary frame without data */ ret = MHD_websocket_encode_binary (wss, NULL, 0, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x00", 2))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Binary frame with 1 byte of data */ ret = MHD_websocket_encode_binary (wss, "a", 1, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (3 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x01" "a", 3))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Binary frame with 125 bytes of data */ ret = MHD_websocket_encode_binary (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (127 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x7D" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 127))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Binary frame with 126 bytes of data */ ret = MHD_websocket_encode_binary (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 126, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (130 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x7E\x00\x7E" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 130))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Binary frame with 65535 bytes of data */ allocate_length_test_data (&buf1, &buf2, 65535, "\x82\x7E\xFF\xFF", 4); ret = MHD_websocket_encode_binary (wss, buf2, 65535, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (65535 + 4 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 65535 + 4))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Binary frame with 65536 bytes of data */ allocate_length_test_data (&buf1, &buf2, 65536, "\x82\x7F\x00\x00\x00\x00\x00\x01\x00\x00", 10); ret = MHD_websocket_encode_binary (wss, buf2, 65536, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (65536 + 10 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 65536 + 10))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Binary frame with 100 MB of data */ allocate_length_test_data (&buf1, &buf2, 104857600, "\x82\x7F\x00\x00\x00\x00\x06\x40\x00\x00", 10); ret = MHD_websocket_encode_binary (wss, buf2, 104857600, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (104857600 + 10 != frame_len) || (NULL == frame) || (0 != memcmp (frame, buf1, 104857600 + 10))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } if (NULL != buf1) { free (buf1); buf1 = NULL; } if (NULL != buf2) { free (buf2); buf2 = NULL; } #ifdef ENABLE_64BIT_TESTS /* Fail test: `frame_len` is greater than 0x7FFFFFFFFFFFFFFF (this is the maximum allowed payload size) */ frame_len = 0; ret = MHD_websocket_encode_binary (wss, "abc", (uint64_t) 0x8000000000000000, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } #endif /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `ws` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_binary (NULL, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `payload` not passed, but `payload_len` != 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_binary (wss, NULL, 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `payload` passed, but `payload_len` == 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_binary (wss, "abc", 0, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x82\x00", 2))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `frame` not passed */ frame_len = 0x87654321; ret = MHD_websocket_encode_binary (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, NULL, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Fail test: `frame_len` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; ret = MHD_websocket_encode_binary (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `fragmentation` has an invalid value */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_binary (wss, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_LAST + 1, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *wsx; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx, MHD_WEBSOCKET_FLAG_SERVER, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Fail test: allocation while no memory available */ disable_alloc = 1; ret = MHD_websocket_encode_binary (wsx, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } /* Regular test: allocation while memory is available again */ disable_alloc = 0; ret = MHD_websocket_encode_binary (wsx, "abc", 3, MHD_WEBSOCKET_FRAGMENTATION_NONE, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x82\x03" "abc", 5))) { fprintf (stderr, "Encode binary test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } MHD_websocket_stream_free (wsx); } else { fprintf (stderr, "Couldn't perform memory test for binary encoding in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) free (buf1); if (NULL != buf2) free (buf2); if (NULL != wsc) MHD_websocket_stream_free (wsc); if (NULL != wss) MHD_websocket_stream_free (wss); return failed != 0 ? 0x10 : 0x00; } /** * Test procedure for `MHD_websocket_encode_close()` */ int test_encodes_close () { int failed = 0; struct MHD_WebSocketStream *wss; struct MHD_WebSocketStream *wsc; int ret; char *buf1 = NULL, *buf2 = NULL; char *frame = NULL; size_t frame_len = 0; if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc, MHD_WEBSOCKET_FLAG_CLIENT, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode close tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); return 0x10; } if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wss, MHD_WEBSOCKET_FLAG_SERVER, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode close tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); if (NULL != wsc) MHD_websocket_stream_free (wsc); return 0x10; } /* ------------------------------------------------------------------------------ Encoding ------------------------------------------------------------------------------ */ /* Regular test: Some data, we are server */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x0B\x03\xE8" "blablabla", 13))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data, we are client */ ret = MHD_websocket_encode_close (wsc, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (17 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "\x03\xE8" "blablabla", 11, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Close reason without text, we are server */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (4 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x02\x03\xE8", 4))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Close reason without text, we are client */ ret = MHD_websocket_encode_close (wsc, MHD_WEBSOCKET_CLOSEREASON_REGULAR, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (8 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "\x03\xE8", 2, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Close without reason, we are server */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_NO_REASON, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x00", 2))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Close without reason, we are client */ ret = MHD_websocket_encode_close (wsc, MHD_WEBSOCKET_CLOSEREASON_NO_REASON, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (6 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, NULL, 0, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Close with UTF-8 sequence in reason, we are client */ ret = MHD_websocket_encode_close (wsc, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "bla" "\xC3\xA4" "blabla", 11, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (19 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "\x03\xE8" "bla" "\xC3\xA4" "blabla", 13, MHD_WEBSOCKET_STATUS_CLOSE_FRAME, MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Edge test (success): Close reason with NUL characters, we are server */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY, "bla" "\0\0\0" "bla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (13 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x0B\x03\xE9" "bla" "\0\0\0" "bla", 13))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: Some data with broken UTF-8, we are server */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "bla" "\xC3" "blabla", 10, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Length checks ------------------------------------------------------------------------------ */ /* Edge test (success): Close frame without payload */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_NO_REASON, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x00", 2))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Close frame only reason code */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (4 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x02\x03\xE8", 4))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Close frame with 1 bytes of reason text */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "a", 1, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x03\x03\xE8" "a", 5))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Close frame with 123 bytes of reason text */ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456", 123, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (127 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x7D\x03\xE8" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456", 127))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (fail): Close frame with 124 bytes of reason text*/ ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567", 124, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `ws` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (NULL, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `payload` not passed, but `payload_len` != 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, NULL, 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `payload` passed, but `payload_len` == 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (4 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x88\x02\x03\xE8", 4))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `frame` not passed */ frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 3, NULL, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Fail test: `frame_len` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 3, &frame, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: no reason code passed, but reason text */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, MHD_WEBSOCKET_CLOSEREASON_NO_REASON, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (fail): Invalid reason code */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, 1, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (fail): Invalid reason code */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, 999, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Custom reason code */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_close (wss, 2000, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (7 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x88\x05\x07\xD0" "abc", 7))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *wsx; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx, MHD_WEBSOCKET_FLAG_SERVER, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Fail test: allocation while no memory available */ disable_alloc = 1; ret = MHD_websocket_encode_close (wsx, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } /* Regular test: allocation while memory is available again */ disable_alloc = 0; ret = MHD_websocket_encode_close (wsx, MHD_WEBSOCKET_CLOSEREASON_REGULAR, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (7 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x88\x05\x03\xE8" "abc", 7))) { fprintf (stderr, "Encode close test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } MHD_websocket_stream_free (wsx); } else { fprintf (stderr, "Couldn't perform memory test for close encoding in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) free (buf1); if (NULL != buf2) free (buf2); if (NULL != wsc) MHD_websocket_stream_free (wsc); if (NULL != wss) MHD_websocket_stream_free (wss); return failed != 0 ? 0x20 : 0x00; } /** * Test procedure for `MHD_websocket_encode_ping()` */ int test_encodes_ping () { int failed = 0; struct MHD_WebSocketStream *wss; struct MHD_WebSocketStream *wsc; int ret; char *buf1 = NULL, *buf2 = NULL; char *frame = NULL; size_t frame_len = 0; if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc, MHD_WEBSOCKET_FLAG_CLIENT, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode ping tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); return 0x10; } if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss, MHD_WEBSOCKET_FLAG_SERVER, 0)) { fprintf (stderr, "No encode ping tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); if (NULL != wsc) MHD_websocket_stream_free (wsc); return 0x10; } /* ------------------------------------------------------------------------------ Encoding ------------------------------------------------------------------------------ */ /* Regular test: Some data, we are server */ ret = MHD_websocket_encode_ping (wss, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x09" "blablabla", 11))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data, we are client */ ret = MHD_websocket_encode_ping (wsc, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (15 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "blablabla", 9, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Ping without payload, we are server */ ret = MHD_websocket_encode_ping (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x00", 2))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Ping without payload, we are client */ ret = MHD_websocket_encode_ping (wsc, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (6 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, NULL, 0, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Ping with something like UTF-8 sequence in payload, we are client */ ret = MHD_websocket_encode_ping (wsc, "bla" "\xC3\xA4" "blabla", 11, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (17 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "bla" "\xC3\xA4" "blabla", 11, MHD_WEBSOCKET_STATUS_PING_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Edge test (success): Ping payload with NUL characters, we are server */ ret = MHD_websocket_encode_ping (wss, "bla" "\0\0\0" "bla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x09" "bla" "\0\0\0" "bla", 11))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Ping payload with with something which looks like broken UTF-8, we are server */ ret = MHD_websocket_encode_ping (wss, "bla" "\xC3" "blabla", 10, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (12 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x0A" "bla" "\xC3" "blabla", 12))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Length checks ------------------------------------------------------------------------------ */ /* Edge test (success): Ping frame without payload */ ret = MHD_websocket_encode_ping (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x00", 2))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Ping frame with one byte of payload */ ret = MHD_websocket_encode_ping (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x00", 2))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Ping frame with 125 bytes of payload */ ret = MHD_websocket_encode_ping (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (127 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x7D" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 127))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (fail): Ping frame with 126 bytes of payload */ ret = MHD_websocket_encode_ping (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 126, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `ws` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_ping (NULL, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `payload` not passed, but `payload_len` != 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_ping (wss, NULL, 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `payload` passed, but `payload_len` == 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_ping (wss, "abc", 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x89\x00", 2))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `frame` not passed */ frame_len = 0x87654321; ret = MHD_websocket_encode_ping (wss, "abc", 3, NULL, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Fail test: `frame_len` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; ret = MHD_websocket_encode_ping (wss, "abc", 3, &frame, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *wsx; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx, MHD_WEBSOCKET_FLAG_SERVER, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Fail test: allocation while no memory available */ disable_alloc = 1; ret = MHD_websocket_encode_ping (wsx, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } /* Regular test: allocation while memory is available again */ disable_alloc = 0; ret = MHD_websocket_encode_ping (wsx, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x89\x03" "abc", 5))) { fprintf (stderr, "Encode ping test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } MHD_websocket_stream_free (wsx); } else { fprintf (stderr, "Couldn't perform memory test for ping encoding in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) free (buf1); if (NULL != buf2) free (buf2); if (NULL != wsc) MHD_websocket_stream_free (wsc); if (NULL != wss) MHD_websocket_stream_free (wss); return failed != 0 ? 0x40 : 0x00; } /** * Test procedure for `MHD_websocket_encode_pong()` */ int test_encodes_pong () { int failed = 0; struct MHD_WebSocketStream *wss; struct MHD_WebSocketStream *wsc; int ret; char *buf1 = NULL, *buf2 = NULL; char *frame = NULL; size_t frame_len = 0; if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc, MHD_WEBSOCKET_FLAG_CLIENT, 0, malloc, realloc, free, NULL, test_rng)) { fprintf (stderr, "No encode pong tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); return 0x10; } if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss, MHD_WEBSOCKET_FLAG_SERVER, 0)) { fprintf (stderr, "No encode pong tests possible due to failed stream init in line %u\n", (unsigned int) __LINE__); if (NULL != wsc) MHD_websocket_stream_free (wsc); return 0x10; } /* ------------------------------------------------------------------------------ Encoding ------------------------------------------------------------------------------ */ /* Regular test: Some data, we are server */ ret = MHD_websocket_encode_pong (wss, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x09" "blablabla", 11))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Some data, we are client */ ret = MHD_websocket_encode_pong (wsc, "blablabla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (15 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "blablabla", 9, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Pong without payload, we are server */ ret = MHD_websocket_encode_pong (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x00", 2))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Pong without payload, we are client */ ret = MHD_websocket_encode_pong (wsc, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (6 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, NULL, 0, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Regular test: Pong with something like UTF-8 sequence in payload, we are client */ ret = MHD_websocket_encode_pong (wsc, "bla" "\xC3\xA4" "blabla", 11, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (17 != frame_len) || (NULL == frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } else { failed += test_decode_single (__LINE__, MHD_WEBSOCKET_FLAG_SERVER | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS, 0, 1, 0, frame, frame_len, "bla" "\xC3\xA4" "blabla", 11, MHD_WEBSOCKET_STATUS_PONG_FRAME, MHD_WEBSOCKET_VALIDITY_VALID, frame_len); } if (NULL != frame) { MHD_websocket_free (wsc, frame); frame = NULL; } /* Edge test (success): Pong payload with NUL characters, we are server */ ret = MHD_websocket_encode_pong (wss, "bla" "\0\0\0" "bla", 9, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (11 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x09" "bla" "\0\0\0" "bla", 11))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: Pong payload with with something which looks like broken UTF-8, we are server */ ret = MHD_websocket_encode_pong (wss, "bla" "\xC3" "blabla", 10, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (12 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x0A" "bla" "\xC3" "blabla", 12))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Length checks ------------------------------------------------------------------------------ */ /* Edge test (success): Pong frame without payload */ ret = MHD_websocket_encode_pong (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x00", 2))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Pong frame with one byte of payload */ ret = MHD_websocket_encode_pong (wss, NULL, 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x00", 2))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (success): Pong frame with 125 bytes of payload */ ret = MHD_websocket_encode_pong (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 125, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (127 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x7D" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678", 127))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Edge test (fail): Pong frame with 126 bytes of payload */ ret = MHD_websocket_encode_pong (wss, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 126, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `ws` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_pong (NULL, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `payload` not passed, but `payload_len` != 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_pong (wss, NULL, 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Regular test: `payload` passed, but `payload_len` == 0 */ frame = (char *) (uintptr_t) 0xBAADF00D; frame_len = 0x87654321; ret = MHD_websocket_encode_pong (wss, "abc", 0, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (2 != frame_len) || (NULL == frame) || (((char *) (uintptr_t) 0xBAADF00D) == frame) || (0 != memcmp (frame, "\x8A\x00", 2))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* Fail test: `frame` not passed */ frame_len = 0x87654321; ret = MHD_websocket_encode_pong (wss, "abc", 3, NULL, &frame_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (0 != frame_len) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Fail test: `frame_len` not passed */ frame = (char *) (uintptr_t) 0xBAADF00D; ret = MHD_websocket_encode_pong (wss, "abc", 3, &frame, NULL); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (NULL != frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (((char *) (uintptr_t) 0xBAADF00D) == frame) { frame = NULL; } if (NULL != frame) { MHD_websocket_free (wss, frame); frame = NULL; } /* ------------------------------------------------------------------------------ validity after temporary out-of-memory ------------------------------------------------------------------------------ */ { struct MHD_WebSocketStream *wsx; if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx, MHD_WEBSOCKET_FLAG_SERVER, 0, test_malloc, test_realloc, test_free, NULL, NULL)) { /* Fail test: allocation while no memory available */ disable_alloc = 1; ret = MHD_websocket_encode_pong (wsx, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) || (0 != frame_len) || (NULL != frame) ) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } /* Regular test: allocation while memory is available again */ disable_alloc = 0; ret = MHD_websocket_encode_pong (wsx, "abc", 3, &frame, &frame_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (5 != frame_len) || (NULL == frame) || (0 != memcmp (frame, "\x8A\x03" "abc", 5))) { fprintf (stderr, "Encode pong test failed in line %u\n", (unsigned int) __LINE__); ++failed; } if (NULL != frame) { MHD_websocket_free (wsx, frame); frame = NULL; } MHD_websocket_stream_free (wsx); } else { fprintf (stderr, "Couldn't perform memory test for pong encoding in line %u\n", (unsigned int) __LINE__); ++failed; } } if (NULL != buf1) free (buf1); if (NULL != buf2) free (buf2); if (NULL != wsc) MHD_websocket_stream_free (wsc); if (NULL != wss) MHD_websocket_stream_free (wss); return failed != 0 ? 0x80 : 0x00; } /** * Test procedure for `MHD_websocket_split_close_reason()` */ int test_split_close_reason () { int failed = 0; const char *payload; unsigned short reason_code; const char *reason_utf8; size_t reason_utf8_len; int ret; /* ------------------------------------------------------------------------------ Normal splits ------------------------------------------------------------------------------ */ /* Regular test: Reason code + Reason text */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = "\x03\xE8" "abc"; ret = MHD_websocket_split_close_reason (payload, 5, &reason_code, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) || (3 != reason_utf8_len) || (payload + 2 != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: Reason code */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = "\x03\xE8"; ret = MHD_websocket_split_close_reason (payload, 2, &reason_code, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) || (0 != reason_utf8_len) || (NULL != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: No payload */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = NULL; ret = MHD_websocket_split_close_reason (payload, 0, &reason_code, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) || (0 != reason_utf8_len) || (NULL != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: `payload` is not NULL given, but `payload_len` == 0 */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = "abc"; ret = MHD_websocket_split_close_reason (payload, 0, &reason_code, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) || (0 != reason_utf8_len) || (NULL != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Wrong parameters ------------------------------------------------------------------------------ */ /* Fail test: `payload` not passed, but `payload_len` != 0 */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = NULL; ret = MHD_websocket_split_close_reason (payload, 3, &reason_code, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) || (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) || (0 != reason_utf8_len) || (NULL != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: `reason_code` not passed */ reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; reason_utf8_len = 12345; payload = "\x03\xE8" "abc"; ret = MHD_websocket_split_close_reason (payload, 5, NULL, &reason_utf8, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (3 != reason_utf8_len) || (payload + 2 != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: `reason_utf8` not passed */ reason_code = 9999; reason_utf8_len = 12345; payload = "\x03\xE8" "abc"; ret = MHD_websocket_split_close_reason (payload, 5, &reason_code, NULL, &reason_utf8_len); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) || (3 != reason_utf8_len) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: `reason_utf8_len` not passed */ reason_code = 9999; reason_utf8 = (const char *) (intptr_t) 0xBAADF00D; payload = "\x03\xE8" "abc"; ret = MHD_websocket_split_close_reason (payload, 5, &reason_code, &reason_utf8, NULL); if ((MHD_WEBSOCKET_STATUS_OK != ret) || (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) || (payload + 2 != reason_utf8) ) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } /* Regular test: `reason_code`, `reason_utf8` and `reason_utf8_len` not passed */ /* (this is not prohibited, although it doesn't really make sense) */ payload = "\x03\xE8" "abc"; ret = MHD_websocket_split_close_reason (payload, 5, NULL, NULL, NULL); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "split close reason test failed in line %u\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x100 : 0x00; } /** * Test procedure for `MHD_websocket_check_http_version()` */ int test_check_http_version () { int failed = 0; int ret; /* ------------------------------------------------------------------------------ Version check with valid HTTP version syntax ------------------------------------------------------------------------------ */ /* Regular test: HTTP/1.1 */ ret = MHD_websocket_check_http_version ("HTTP/1.1"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Regular test: HTTP/1.2 */ ret = MHD_websocket_check_http_version ("HTTP/1.2"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Regular test: HTTP/1.10 */ ret = MHD_websocket_check_http_version ("HTTP/1.10"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Regular test: HTTP/2.0 */ ret = MHD_websocket_check_http_version ("HTTP/2.0"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Regular test: HTTP/3.0 */ ret = MHD_websocket_check_http_version ("HTTP/3.0"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: HTTP/1.0 */ ret = MHD_websocket_check_http_version ("HTTP/1.0"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: HTTP/0.9 */ ret = MHD_websocket_check_http_version ("HTTP/0.9"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Version check edge cases ------------------------------------------------------------------------------ */ /* Edge test (success): HTTP/123.45 */ ret = MHD_websocket_check_http_version ("HTTP/123.45"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/1.45 */ ret = MHD_websocket_check_http_version ("HTTP/1.45"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/01.1 */ ret = MHD_websocket_check_http_version ("HTTP/01.1"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/0001.1 */ ret = MHD_websocket_check_http_version ("HTTP/0001.1"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/1.01 */ ret = MHD_websocket_check_http_version ("HTTP/1.01"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/1.0001 */ ret = MHD_websocket_check_http_version ("HTTP/1.0001"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/0001.0001 */ ret = MHD_websocket_check_http_version ("HTTP/0001.0001"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/2.000 */ ret = MHD_websocket_check_http_version ("HTTP/2.000"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): HTTP/0.0 */ ret = MHD_websocket_check_http_version ("HTTP/0.0"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): HTTP/00.0 */ ret = MHD_websocket_check_http_version ("HTTP/00.0"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): HTTP/00.0 */ ret = MHD_websocket_check_http_version ("HTTP/0.00"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Invalid version syntax ------------------------------------------------------------------------------ */ /* Fail test: (empty string) */ ret = MHD_websocket_check_http_version (""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: http/1.1 */ ret = MHD_websocket_check_http_version ("http/1.1"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: "HTTP / 1.1" */ ret = MHD_websocket_check_http_version ("HTTP / 1.1"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: NULL as version */ ret = MHD_websocket_check_http_version (NULL); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_http_version test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x200 : 0x00; } /** * Test procedure for `MHD_websocket_check_connection_header()` */ int test_check_connection_header () { int failed = 0; int ret; /* ------------------------------------------------------------------------------ Check with valid Connection header syntax ------------------------------------------------------------------------------ */ /* Regular test: Upgrade */ ret = MHD_websocket_check_connection_header ("Upgrade"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Regular test: keep-alive, Upgrade */ ret = MHD_websocket_check_connection_header ("keep-alive, Upgrade"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: keep-alive */ ret = MHD_websocket_check_connection_header ("keep-alive"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: close */ ret = MHD_websocket_check_connection_header ("close"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Connection check edge cases ------------------------------------------------------------------------------ */ /* Edge test (success): keep-alive,Upgrade */ ret = MHD_websocket_check_connection_header ("keep-alive,Upgrade"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Upgrade, keep-alive */ ret = MHD_websocket_check_connection_header ("Upgrade, keep-alive"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Upgrade,keep-alive */ ret = MHD_websocket_check_connection_header ("Upgrade,keep-alive"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Transfer-Encoding,Upgrade,keep-alive */ ret = MHD_websocket_check_connection_header ( "Transfer-Encoding,Upgrade,keep-alive"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Transfer-Encoding , Upgrade , keep-alive */ ret = MHD_websocket_check_connection_header ( "Transfer-Encoding , Upgrade , keep-alive"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): upgrade */ ret = MHD_websocket_check_connection_header ("upgrade"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): UPGRADE */ ret = MHD_websocket_check_connection_header ("UPGRADE"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): All allowed token characters, then upgrade token */ ret = MHD_websocket_check_connection_header ( "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,Upgrade"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Different, allowed whitespaces */ ret = MHD_websocket_check_connection_header (" \tUpgrade \t"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_connection_header ("\rUpgrade"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_connection_header ("\nUpgrade"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_connection_header ("\vUpgrade"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_connection_header ("\fUpgrade"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Invalid header syntax ------------------------------------------------------------------------------ */ /* Fail test: (empty string) */ ret = MHD_websocket_check_connection_header (""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: (Disallowed) multiple word token with the term "Upgrade" in it */ ret = MHD_websocket_check_connection_header ("Upgrade or Downgrade"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: Invalid characters */ ret = MHD_websocket_check_connection_header ("\"Upgrade\""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: NULL as connection */ ret = MHD_websocket_check_connection_header (NULL); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_connection_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x400 : 0x00; } /** * Test procedure for `MHD_websocket_check_upgrade_header()` */ int test_check_upgrade_header () { int failed = 0; int ret; /* ------------------------------------------------------------------------------ Check with valid Upgrade header syntax ------------------------------------------------------------------------------ */ /* Regular test: websocket */ ret = MHD_websocket_check_upgrade_header ("websocket"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: HTTP/2.0 */ ret = MHD_websocket_check_upgrade_header ("HTTP/2.0"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Upgrade check edge cases ------------------------------------------------------------------------------ */ /* Edge test (success): websocket,HTTP/2.0 */ ret = MHD_websocket_check_upgrade_header ("websocket,HTTP/2.0"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): websocket ,HTTP/2.0 */ ret = MHD_websocket_check_upgrade_header (" websocket ,HTTP/2.0"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): HTTP/2.0, websocket */ ret = MHD_websocket_check_upgrade_header ("HTTP/2.0, websocket "); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): websocket/13 */ ret = MHD_websocket_check_upgrade_header ("websocket/13"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): WeBsOcKeT */ ret = MHD_websocket_check_upgrade_header ("WeBsOcKeT"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): WEBSOCKET */ ret = MHD_websocket_check_upgrade_header ("WEBSOCKET"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): All allowed token characters plus /, then websocket keyword */ ret = MHD_websocket_check_upgrade_header ( "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/,websocket"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (success): Different, allowed whitespaces */ ret = MHD_websocket_check_upgrade_header (" \twebsocket \t"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_upgrade_header ("\rwebsocket"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_upgrade_header ("\nwebsocket"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_upgrade_header ("\vwebsocket"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): Different, disallowed whitespaces */ ret = MHD_websocket_check_upgrade_header ("\fwebsocket"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Invalid header syntax ------------------------------------------------------------------------------ */ /* Fail test: (empty string) */ ret = MHD_websocket_check_upgrade_header (""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: (Disallowed) multiple word token with the term "websocket" in it */ ret = MHD_websocket_check_upgrade_header ("websocket or something"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: Invalid characters */ ret = MHD_websocket_check_upgrade_header ("\"websocket\""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: NULL as upgrade */ ret = MHD_websocket_check_upgrade_header (NULL); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_upgrade_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x800 : 0x00; } /** * Test procedure for `MHD_websocket_check_version_header()` */ int test_check_version_header () { int failed = 0; int ret; /* ------------------------------------------------------------------------------ Check with valid Upgrade header syntax ------------------------------------------------------------------------------ */ /* Regular test: 13 */ ret = MHD_websocket_check_version_header ("13"); if (MHD_WEBSOCKET_STATUS_OK != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Version check edge cases ------------------------------------------------------------------------------ */ /* Edge test (fail): 14 */ ret = MHD_websocket_check_version_header ("14"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): 12 */ ret = MHD_websocket_check_version_header ("12"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): 0 */ ret = MHD_websocket_check_version_header ("1"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): 1 */ ret = MHD_websocket_check_version_header ("1"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): 130 */ ret = MHD_websocket_check_version_header ("130"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Edge test (fail): " 13" */ ret = MHD_websocket_check_version_header (" 13"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Invalid header syntax ------------------------------------------------------------------------------ */ /* Fail test: (empty string) */ ret = MHD_websocket_check_version_header (""); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* Fail test: Invalid characters */ ret = MHD_websocket_check_version_header ("abc"); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } /* ------------------------------------------------------------------------------ Missing parameters ------------------------------------------------------------------------------ */ /* Fail test: NULL as version */ ret = MHD_websocket_check_version_header (NULL); if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret) { fprintf (stderr, "check_version_header test failed in line %u.\n", (unsigned int) __LINE__); ++failed; } return failed != 0 ? 0x1000 : 0x00; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ /* seed random number generator */ srand ((unsigned long) time (NULL)); /* perform tests */ errorCount += test_inits (); errorCount += test_accept (); errorCount += test_decodes (); errorCount += test_encodes_text (); errorCount += test_encodes_binary (); errorCount += test_encodes_close (); errorCount += test_encodes_ping (); errorCount += test_encodes_pong (); errorCount += test_split_close_reason (); errorCount += test_check_http_version (); errorCount += test_check_connection_header (); errorCount += test_check_upgrade_header (); errorCount += test_check_version_header (); /* output result */ if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.2/src/datadir/0000755000175000017500000000000015035216652013563 500000000000000libmicrohttpd-1.0.2/src/datadir/cert-and-key-for-wireshark.pem0000644000175000017500000000325014674632555021266 00000000000000-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8 CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7 dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2 wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE qdJNJ1DkyUc9dN2cliX4R+rG -----END PRIVATE KEY----- libmicrohttpd-1.0.2/src/datadir/cert-and-key.pem0000644000175000017500000000701714674632555016512 00000000000000-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8 CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7 dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2 wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE qdJNJ1DkyUc9dN2cliX4R+rG -----END PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4 NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2 psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5 qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27 /w0gW9EVWzFhsFeGEssi -----END CERTIFICATE----- libmicrohttpd-1.0.2/src/Makefile.in0000644000175000017500000005334415035216307014146 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @RUN_LIBCURL_TESTS_TRUE@am__append_1 = testcurl @RUN_LIBCURL_TESTS_TRUE@@RUN_ZZUF_TESTS_TRUE@am__append_2 = testzzuf # Finally (last!) also build experimental lib... @HAVE_EXPERIMENTAL_TRUE@am__append_3 = microhttpd_ws @BUILD_EXAMPLES_TRUE@am__append_4 = examples @BUILD_TOOLS_TRUE@am__append_5 = tools subdir = src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = include microhttpd . testcurl testzzuf microhttpd_ws \ examples tools am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = include microhttpd . $(am__append_1) $(am__append_2) \ $(am__append_3) $(am__append_4) $(am__append_5) EXTRA_DIST = \ datadir/cert-and-key.pem \ datadir/cert-and-key-for-wireshark.pem all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile .NOTPARALLEL: # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/testzzuf/0000755000175000017500000000000015035216652014051 500000000000000libmicrohttpd-1.0.2/src/testzzuf/zzuf_socat_test_runner.sh0000755000175000017500000000645714674632555021177 00000000000000#!/bin/sh if set -m ; then : ; else echo "The shell $SHELL does not support background jobs, the test cannot run." 1>&2 exit 77 fi socat_listen_ip='127.0.0.121' socat_listen_port='10121' mhd_listen_port='4010' max_runtime_sec='1800' if test "x${ZZUF}" = "xno" ; then echo "zzuf command missing" 1>&2 exit 77 fi if command -v "${ZZUF}" > /dev/null 2>&1 ; then : ; else echo "zzuf command missing" 1>&2 exit 77 fi if test "x${SOCAT}" = "xno" ; then echo "socat command missing" 1>&2 exit 77 fi if command -v "${SOCAT}" > /dev/null 2>&1 ; then : ; else echo "socat command missing" 1>&2 exit 77 fi socat_test_params="-ls -lu \ -T0.1 -4 \ TCP-LISTEN:${socat_listen_port},bind=${socat_listen_ip},reuseaddr,linger=2,linger2=1,accept-timeout=0.1 \ TCP:127.0.0.1:${mhd_listen_port},reuseaddr" echo "## Trying to run socat to test ports availability..." if "${SOCAT}" ${socat_test_params} ; then echo "Success." else echo "socat test run failed" 1>&2 exit 77 fi # fuzz the input only for IP ${socat_listen_ip}. libcurl uses another IP # in this test therefore libcurl input is not fuzzed. zzuf_all_params="--ratio=0.001:0.4 --autoinc --verbose --signal \ --max-usertime=${max_runtime_sec} --check-exit --network --allow=${socat_listen_ip} --exclude=." if test -n "${ZZUF_SEED}" ; then zzuf_all_params="${zzuf_all_params} --seed=${ZZUF_SEED}" fi if test -n "${ZZUF_FLAGS}" ; then zzuf_all_params="${zzuf_all_params} ${ZZUF_FLAGS}" fi # Uncomment the next line to see more zzuf data in logs #zzuf_all_params="${zzuf_all_params} -dd" socat_options="-ls -lu \ -T3 -4" socat_addr1="TCP-LISTEN:${socat_listen_port},bind=${socat_listen_ip},reuseaddr,nodelay,linger=2,linger2=1,accept-timeout=${max_runtime_sec},fork" socat_addr2="TCP:127.0.0.1:${mhd_listen_port},reuseaddr,connect-timeout=3,nodelay,linger=2,linger2=1" if test -n "${SOCAT_FLAGS}" ; then socat_options="${socat_options} ${SOCAT_FLAGS}" fi # Uncomment the next line to see more socat data in logs #socat_options="${socat_options} -dd -D" # Uncomment the next line to see all traffic in logs #socat_options="${socat_options} -v" stop_zzuf_socat () { trap - EXIT if test -n "$zzuf_pid" ; then echo "The test has been interrupted." 1>&2 test "x$zzuf_pid" = "xstarting" && zzuf_pid=$! # Finish zzuf + socat kill -TERM ${zzuf_pid} -${zzuf_pid} # Finish the test kill -INT %2 2> /dev/null || kill -INT %1 2> /dev/null exit 99 fi } echo "## Starting zzuf with socat to reflect fuzzed traffic..." trap 'stop_zzuf_socat' EXIT zzuf_pid="starting" "${ZZUF}" ${zzuf_all_params} "${SOCAT}" ${socat_options} ${socat_addr1} ${socat_addr2} & if test $? -eq 0 ; then zzuf_pid=$! echo "zzuf with socat has been started." else zzuf_pid='' echo "Failed to start zzuf with socat" 1>&2 exit 99 fi echo "## Starting real test of $@ with traffic fuzzed by zzuf with socat..." "$@" --with-socat test_result=$? trap - EXIT echo "$@ has exited with the return code $test_result" if kill -s 0 -- $$ 2> /dev/null ; then if kill -s 0 -- ${zzuf_pid} -${zzuf_pid} ; then : ; else echo "No running zzuf with socat is detected after the test." 1>&2 echo "Looks like zzuf ended prematurely, at least part of the testing has not been performed." 1>&2 test_result=99 fi fi kill -TERM ${zzuf_pid} -${zzuf_pid} zzuf_pid='' exit $test_result libmicrohttpd-1.0.2/src/testzzuf/README0000644000175000017500000000112414674632555014663 00000000000000Testcases in this directory require zzuf and socat. zzuf is used to randomly mess with the TCP connection between the CURL clients and the MHD server. The goal is to expose problems in MHD's error handling (by introducing random syntax errors). socat is used to listen on port 11081 and forward the randomzied stream to port 11080 where MHD is waiting. As a result, the testcases in this directory do NOT check that whatever CURL returns is what was expected -- random modifications to the TCP stream can have random effects ;-). Testcases "fail" if the code crashes or hangs indefinitely. libmicrohttpd-1.0.2/src/testzzuf/zzuf_test_runner.sh0000755000175000017500000000466014674632555020000 00000000000000#!/bin/sh mhd_listen_ip='127.0.0.1' max_runtime_sec='1800' if test "x${ZZUF}" = "xno" ; then echo "zzuf command missing" 1>&2 exit 77 fi if command -v "${ZZUF}" > /dev/null 2>&1 ; then : ; else echo "zzuf command missing" 1>&2 exit 77 fi run_with_socat () { echo "Trying to run the test with socat..." script_dir="" if command -v dirname > /dev/null 2>&1 ; then test_dir=`dirname /` if test "x${test_dir}" = "x/" ; then if dirname "$1" > /dev/null 2>&1 ; then script_dir=`dirname "$1"` if test -n "${script_dir}" ; then # Assume script is not in the root dir script_dir="${script_dir}/" else script_dir="./" fi fi fi fi if test -z "${script_dir}" ; then if echo "$1" | sed 's|[^/]*$||' > /dev/null 2>&1 ; then script_dir=`echo "$1" | sed 's|[^/]*$||'` if test -z "${script_dir}" ; then script_dir="./" fi fi fi if test -z "${script_dir}" ; then echo "Cannot determine script location, will try current directory." 1>&2 script_dir="./" fi $SHELL "${script_dir}zzuf_socat_test_runner.sh" "$@" exit $? } # zzuf cannot pass-through the return value of checked program # so try the direct dry-run first to get possible 77 or 99 codes echo "## Dry-run of the $@..." if "$@" --dry-run ; then echo "# Dry-run succeeded." else res_code=$? echo "Dry-run failed with exit code $res_code." 1>&2 if test $res_code -ne 99; then run_with_socat "$@" fi echo "$@ will not be run with zzuf." 1>&2 exit $res_code fi # fuzz the input only for IP ${mhd_listen_ip}. libcurl uses another IP # in this test therefore libcurl input is not fuzzed. zzuf_all_params="--ratio=0.001:0.4 --autoinc --verbose --signal \ --max-usertime=${max_runtime_sec} --check-exit --network \ --allow=${mhd_listen_ip} --exclude=." if test -n "${ZZUF_SEED}" ; then zzuf_all_params="${zzuf_all_params} --seed=${ZZUF_SEED}" fi if test -n "${ZZUF_FLAGS}" ; then zzuf_all_params="${zzuf_all_params} ${ZZUF_FLAGS}" fi # Uncomment the next line to see more data in logs #zzuf_all_params="${zzuf_all_params} -dd" echo "## Dry-run of the $@ with zzuf..." if "$ZZUF" ${zzuf_all_params} "$@" --dry-run ; then echo "# Dry-run with zzuf succeeded." else res_code=$? echo "$@ cannot be run with zzuf directly." 1>&2 run_with_socat "$@" exit $res_code fi echo "## Real test of $@ with zzuf..." "$ZZUF" ${zzuf_all_params} "$@" exit $? libmicrohttpd-1.0.2/src/testzzuf/mhd_debug_funcs.c0000644000175000017500000000551214760713574017265 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_debug_funcs.c * @brief Implementations of MHD private debug functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_debug_funcs.h" #include "internal.h" #include "mhd_sockets.h" /** * Checks whether MHD can use accept() syscall and * avoid accept4() syscall. * @return non-zero if accept() is possible, * zero if accept4() is always used by MHD */ int MHD_is_avoid_accept4_possible_ (void) { #if ! defined(USE_ACCEPT4) return ! 0; #else /* ! USE_ACCEPT4 */ return (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_DEBUG_BUILD)) ? ! 0 : 0; #endif /* ! USE_ACCEPT4 */ } /** * Switch MHD daemon to use accept() syscalls for new connections. * @param daemon the daemon to operate */ void MHD_avoid_accept4_ (struct MHD_Daemon *daemon) { (void) daemon; /* Mute compiler warning */ #ifdef USE_ACCEPT4 #ifdef _DEBUG daemon->avoid_accept4 = true; #else /* ! _DEBUG */ abort (); #endif /* ! _DEBUG */ #endif /* USE_ACCEPT4 */ } #ifdef MHD_ASAN_ACTIVE #define MHD_ASAN_ENABLED_ 1 #else /* ! MHD_ASAN_ACTIVE */ #ifdef __SANITIZE_ADDRESS__ #define MHD_ASAN_ENABLED_ 1 #else /* ! __SANITIZE_ADDRESS__ */ #if defined(__has_feature) #if __has_feature(address_sanitizer) #define MHD_ASAN_ENABLED_ 1 #endif /* __has_feature(address_sanitizer) */ #endif /* __has_feature */ #endif /* ! __SANITIZE_ADDRESS__ */ #endif /* ! MHD_ASAN_ACTIVE */ /** * Checks whether any know sanitizer is enabled for this build. * zzuf does not work together with sanitizers as both are intercepting * standard library calls. * @return non-zero if any sanitizer is enabled, * zero otherwise */ int MHD_are_sanitizers_enabled_ (void) { int ret = 0; #ifdef MHD_ASAN_ENABLED_ ++ret; #endif /* ! MHD_ASAN_ENABLED_ */ #if defined(__has_feature) #if __has_feature(thread_sanitizer) ++ret; #endif #if __has_feature(memory_sanitizer) ++ret; #endif #if __has_feature(dataflow_sanitizer) ++ret; #endif #else /* ! defined(__has_feature) */ #ifdef __SANITIZE_THREAD__ ++ret; #endif #endif /* ! defined(__has_feature) */ return ret; } libmicrohttpd-1.0.2/src/testzzuf/Makefile.in0000644000175000017500000017746515035216310016051 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage check_PROGRAMS = test_get$(EXEEXT) test_get_chunked$(EXEEXT) \ test_post$(EXEEXT) test_post_form$(EXEEXT) test_put$(EXEEXT) \ test_put_chunked$(EXEEXT) test_put_large$(EXEEXT) \ test_get_long_uri$(EXEEXT) test_get_long_header$(EXEEXT) \ test_get_close$(EXEEXT) test_get_chunked_close$(EXEEXT) \ test_post_close$(EXEEXT) test_post_form_close$(EXEEXT) \ test_put_close$(EXEEXT) test_put_chunked_close$(EXEEXT) \ test_put_large_close$(EXEEXT) test_get_long_uri_close$(EXEEXT) \ test_get_long_header_close$(EXEEXT) test_get10$(EXEEXT) \ test_get_chunked10$(EXEEXT) test_post10$(EXEEXT) \ test_post_form10$(EXEEXT) test_put10$(EXEEXT) \ test_put_large10$(EXEEXT) test_get_long_uri10$(EXEEXT) \ test_get_long_header10$(EXEEXT) subdir = src/testzzuf ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(dist_check_SCRIPTS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__objects_1 = mhd_debug_funcs.$(OBJEXT) am_test_get_OBJECTS = test_get.$(OBJEXT) $(am__objects_1) test_get_OBJECTS = $(am_test_get_OBJECTS) test_get_LDADD = $(LDADD) test_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__objects_2 = test_get.$(OBJEXT) $(am__objects_1) am_test_get10_OBJECTS = $(am__objects_2) test_get10_OBJECTS = $(am_test_get10_OBJECTS) test_get10_LDADD = $(LDADD) test_get10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_OBJECTS = $(am__objects_2) test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS) test_get_chunked_LDADD = $(LDADD) test_get_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_3 = $(am__objects_2) am_test_get_chunked10_OBJECTS = $(am__objects_3) test_get_chunked10_OBJECTS = $(am_test_get_chunked10_OBJECTS) test_get_chunked10_LDADD = $(LDADD) test_get_chunked10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_OBJECTS = $(am__objects_3) test_get_chunked_close_OBJECTS = $(am_test_get_chunked_close_OBJECTS) test_get_chunked_close_LDADD = $(LDADD) test_get_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close_OBJECTS = $(am__objects_2) test_get_close_OBJECTS = $(am_test_get_close_OBJECTS) test_get_close_LDADD = $(LDADD) test_get_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header_OBJECTS = $(am__objects_2) test_get_long_header_OBJECTS = $(am_test_get_long_header_OBJECTS) test_get_long_header_LDADD = $(LDADD) test_get_long_header_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header10_OBJECTS = $(am__objects_3) test_get_long_header10_OBJECTS = $(am_test_get_long_header10_OBJECTS) test_get_long_header10_LDADD = $(LDADD) test_get_long_header10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header_close_OBJECTS = $(am__objects_3) test_get_long_header_close_OBJECTS = \ $(am_test_get_long_header_close_OBJECTS) test_get_long_header_close_LDADD = $(LDADD) test_get_long_header_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri_OBJECTS = $(am__objects_2) test_get_long_uri_OBJECTS = $(am_test_get_long_uri_OBJECTS) test_get_long_uri_LDADD = $(LDADD) test_get_long_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri10_OBJECTS = $(am__objects_3) test_get_long_uri10_OBJECTS = $(am_test_get_long_uri10_OBJECTS) test_get_long_uri10_LDADD = $(LDADD) test_get_long_uri10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri_close_OBJECTS = $(am__objects_3) test_get_long_uri_close_OBJECTS = \ $(am_test_get_long_uri_close_OBJECTS) test_get_long_uri_close_LDADD = $(LDADD) test_get_long_uri_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_OBJECTS = $(am__objects_2) test_post_OBJECTS = $(am_test_post_OBJECTS) test_post_LDADD = $(LDADD) test_post_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post10_OBJECTS = $(am__objects_3) test_post10_OBJECTS = $(am_test_post10_OBJECTS) test_post10_LDADD = $(LDADD) test_post10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_close_OBJECTS = $(am__objects_3) test_post_close_OBJECTS = $(am_test_post_close_OBJECTS) test_post_close_LDADD = $(LDADD) test_post_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form_OBJECTS = $(am__objects_2) test_post_form_OBJECTS = $(am_test_post_form_OBJECTS) test_post_form_LDADD = $(LDADD) test_post_form_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form10_OBJECTS = $(am__objects_3) test_post_form10_OBJECTS = $(am_test_post_form10_OBJECTS) test_post_form10_LDADD = $(LDADD) test_post_form10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form_close_OBJECTS = $(am__objects_3) test_post_form_close_OBJECTS = $(am_test_post_form_close_OBJECTS) test_post_form_close_LDADD = $(LDADD) test_post_form_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_OBJECTS = $(am__objects_2) test_put_OBJECTS = $(am_test_put_OBJECTS) test_put_LDADD = $(LDADD) test_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put10_OBJECTS = $(am__objects_3) test_put10_OBJECTS = $(am_test_put10_OBJECTS) test_put10_LDADD = $(LDADD) test_put10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_OBJECTS = $(am__objects_2) test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS) test_put_chunked_LDADD = $(LDADD) test_put_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_close_OBJECTS = $(am__objects_3) test_put_chunked_close_OBJECTS = $(am_test_put_chunked_close_OBJECTS) test_put_chunked_close_LDADD = $(LDADD) test_put_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_close_OBJECTS = $(am__objects_3) test_put_close_OBJECTS = $(am_test_put_close_OBJECTS) test_put_close_LDADD = $(LDADD) test_put_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_OBJECTS = $(am__objects_2) test_put_large_OBJECTS = $(am_test_put_large_OBJECTS) test_put_large_LDADD = $(LDADD) test_put_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large10_OBJECTS = $(am__objects_3) test_put_large10_OBJECTS = $(am_test_put_large10_OBJECTS) test_put_large10_LDADD = $(LDADD) test_put_large10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_close_OBJECTS = $(am__objects_3) test_put_large_close_OBJECTS = $(am_test_put_large_close_OBJECTS) test_put_large_close_LDADD = $(LDADD) test_put_large_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/mhd_debug_funcs.Po \ ./$(DEPDIR)/test_get.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(test_get_SOURCES) $(test_get10_SOURCES) \ $(test_get_chunked_SOURCES) $(test_get_chunked10_SOURCES) \ $(test_get_chunked_close_SOURCES) $(test_get_close_SOURCES) \ $(test_get_long_header_SOURCES) \ $(test_get_long_header10_SOURCES) \ $(test_get_long_header_close_SOURCES) \ $(test_get_long_uri_SOURCES) $(test_get_long_uri10_SOURCES) \ $(test_get_long_uri_close_SOURCES) $(test_post_SOURCES) \ $(test_post10_SOURCES) $(test_post_close_SOURCES) \ $(test_post_form_SOURCES) $(test_post_form10_SOURCES) \ $(test_post_form_close_SOURCES) $(test_put_SOURCES) \ $(test_put10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_chunked_close_SOURCES) $(test_put_close_SOURCES) \ $(test_put_large_SOURCES) $(test_put_large10_SOURCES) \ $(test_put_large_close_SOURCES) DIST_SOURCES = $(test_get_SOURCES) $(test_get10_SOURCES) \ $(test_get_chunked_SOURCES) $(test_get_chunked10_SOURCES) \ $(test_get_chunked_close_SOURCES) $(test_get_close_SOURCES) \ $(test_get_long_header_SOURCES) \ $(test_get_long_header10_SOURCES) \ $(test_get_long_header_close_SOURCES) \ $(test_get_long_uri_SOURCES) $(test_get_long_uri10_SOURCES) \ $(test_get_long_uri_close_SOURCES) $(test_post_SOURCES) \ $(test_post10_SOURCES) $(test_post_close_SOURCES) \ $(test_post_form_SOURCES) $(test_post_form10_SOURCES) \ $(test_post_form_close_SOURCES) $(test_put_SOURCES) \ $(test_put10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_chunked_close_SOURCES) $(test_put_close_SOURCES) \ $(test_put_large_SOURCES) $(test_put_large10_SOURCES) \ $(test_put_large_close_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver README DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = . # ZZUF_SEED can be redefined to use other initial seeds # for extended testing. E.g., # make ZZUF_SEED=1234 check ZZUF_SEED = 0 # Additional flags for zzuf ZZUF_FLAGS = # Additional flags for socat (if socat is used) SOCAT_FLAGS = @FORCE_USE_ZZUF_SOCAT_FALSE@TEST_RUNNER_SCRIPT = zzuf_test_runner.sh @FORCE_USE_ZZUF_SOCAT_TRUE@TEST_RUNNER_SCRIPT = zzuf_socat_test_runner.sh AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ ZZUF="$(ZZUF)" ; export ZZUF ; \ ZZUF_SEED="$(ZZUF_SEED)" ; export ZZUF_SEED ; \ ZZUF_FLAGS="$(ZZUF_FLAGS)" ; export ZZUF_FLAGS ; \ SOCAT="$(SOCAT)" ; export SOCAT ; \ SOCAT_FLAGS="$(SOCAT_FLAGS)" ; export SOCAT_FLAGS ; LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ TESTS = $(check_PROGRAMS) dist_check_SCRIPTS = zzuf_test_runner.sh zzuf_socat_test_runner.sh LOG_COMPILER = @SHELL@ "$(srcdir)/$(TEST_RUNNER_SCRIPT)" @VHEAVY_TESTS_TRUE@check_SCRIPTS = warn_vheavy_use tests_common_sources = mhd_debug_funcs.h mhd_debug_funcs.c test_get_SOURCES = \ test_get.c $(tests_common_sources) test_get_chunked_SOURCES = $(test_get_SOURCES) test_post_SOURCES = $(test_get_SOURCES) test_post_form_SOURCES = $(test_get_SOURCES) test_put_SOURCES = $(test_get_SOURCES) test_put_chunked_SOURCES = $(test_get_SOURCES) test_put_large_SOURCES = $(test_get_SOURCES) test_get_long_uri_SOURCES = $(test_get_SOURCES) test_get_long_header_SOURCES = $(test_get_SOURCES) test_get_close_SOURCES = $(test_get_SOURCES) test_get_chunked_close_SOURCES = $(test_get_chunked_SOURCES) test_post_close_SOURCES = $(test_post_SOURCES) test_post_form_close_SOURCES = $(test_post_form_SOURCES) test_put_close_SOURCES = $(test_put_SOURCES) test_put_chunked_close_SOURCES = $(test_put_chunked_SOURCES) test_put_large_close_SOURCES = $(test_put_large_SOURCES) test_get_long_uri_close_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header_close_SOURCES = $(test_get_long_header_SOURCES) test_get10_SOURCES = $(test_get_SOURCES) test_get_chunked10_SOURCES = $(test_get_chunked_SOURCES) test_post10_SOURCES = $(test_post_SOURCES) test_post_form10_SOURCES = $(test_post_form_SOURCES) test_put10_SOURCES = $(test_put_SOURCES) test_put_large10_SOURCES = $(test_put_large_SOURCES) test_get_long_uri10_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header10_SOURCES = $(test_get_long_header_SOURCES) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testzzuf/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testzzuf/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) @rm -f test_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS) test_get10$(EXEEXT): $(test_get10_OBJECTS) $(test_get10_DEPENDENCIES) $(EXTRA_test_get10_DEPENDENCIES) @rm -f test_get10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get10_OBJECTS) $(test_get10_LDADD) $(LIBS) test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) @rm -f test_get_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS) test_get_chunked10$(EXEEXT): $(test_get_chunked10_OBJECTS) $(test_get_chunked10_DEPENDENCIES) $(EXTRA_test_get_chunked10_DEPENDENCIES) @rm -f test_get_chunked10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked10_OBJECTS) $(test_get_chunked10_LDADD) $(LIBS) test_get_chunked_close$(EXEEXT): $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_DEPENDENCIES) $(EXTRA_test_get_chunked_close_DEPENDENCIES) @rm -f test_get_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_LDADD) $(LIBS) test_get_close$(EXEEXT): $(test_get_close_OBJECTS) $(test_get_close_DEPENDENCIES) $(EXTRA_test_get_close_DEPENDENCIES) @rm -f test_get_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close_OBJECTS) $(test_get_close_LDADD) $(LIBS) test_get_long_header$(EXEEXT): $(test_get_long_header_OBJECTS) $(test_get_long_header_DEPENDENCIES) $(EXTRA_test_get_long_header_DEPENDENCIES) @rm -f test_get_long_header$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header_OBJECTS) $(test_get_long_header_LDADD) $(LIBS) test_get_long_header10$(EXEEXT): $(test_get_long_header10_OBJECTS) $(test_get_long_header10_DEPENDENCIES) $(EXTRA_test_get_long_header10_DEPENDENCIES) @rm -f test_get_long_header10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header10_OBJECTS) $(test_get_long_header10_LDADD) $(LIBS) test_get_long_header_close$(EXEEXT): $(test_get_long_header_close_OBJECTS) $(test_get_long_header_close_DEPENDENCIES) $(EXTRA_test_get_long_header_close_DEPENDENCIES) @rm -f test_get_long_header_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header_close_OBJECTS) $(test_get_long_header_close_LDADD) $(LIBS) test_get_long_uri$(EXEEXT): $(test_get_long_uri_OBJECTS) $(test_get_long_uri_DEPENDENCIES) $(EXTRA_test_get_long_uri_DEPENDENCIES) @rm -f test_get_long_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri_OBJECTS) $(test_get_long_uri_LDADD) $(LIBS) test_get_long_uri10$(EXEEXT): $(test_get_long_uri10_OBJECTS) $(test_get_long_uri10_DEPENDENCIES) $(EXTRA_test_get_long_uri10_DEPENDENCIES) @rm -f test_get_long_uri10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri10_OBJECTS) $(test_get_long_uri10_LDADD) $(LIBS) test_get_long_uri_close$(EXEEXT): $(test_get_long_uri_close_OBJECTS) $(test_get_long_uri_close_DEPENDENCIES) $(EXTRA_test_get_long_uri_close_DEPENDENCIES) @rm -f test_get_long_uri_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri_close_OBJECTS) $(test_get_long_uri_close_LDADD) $(LIBS) test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) @rm -f test_post$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS) test_post10$(EXEEXT): $(test_post10_OBJECTS) $(test_post10_DEPENDENCIES) $(EXTRA_test_post10_DEPENDENCIES) @rm -f test_post10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post10_OBJECTS) $(test_post10_LDADD) $(LIBS) test_post_close$(EXEEXT): $(test_post_close_OBJECTS) $(test_post_close_DEPENDENCIES) $(EXTRA_test_post_close_DEPENDENCIES) @rm -f test_post_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_close_OBJECTS) $(test_post_close_LDADD) $(LIBS) test_post_form$(EXEEXT): $(test_post_form_OBJECTS) $(test_post_form_DEPENDENCIES) $(EXTRA_test_post_form_DEPENDENCIES) @rm -f test_post_form$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form_OBJECTS) $(test_post_form_LDADD) $(LIBS) test_post_form10$(EXEEXT): $(test_post_form10_OBJECTS) $(test_post_form10_DEPENDENCIES) $(EXTRA_test_post_form10_DEPENDENCIES) @rm -f test_post_form10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form10_OBJECTS) $(test_post_form10_LDADD) $(LIBS) test_post_form_close$(EXEEXT): $(test_post_form_close_OBJECTS) $(test_post_form_close_DEPENDENCIES) $(EXTRA_test_post_form_close_DEPENDENCIES) @rm -f test_post_form_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form_close_OBJECTS) $(test_post_form_close_LDADD) $(LIBS) test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) @rm -f test_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS) test_put10$(EXEEXT): $(test_put10_OBJECTS) $(test_put10_DEPENDENCIES) $(EXTRA_test_put10_DEPENDENCIES) @rm -f test_put10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put10_OBJECTS) $(test_put10_LDADD) $(LIBS) test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) @rm -f test_put_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS) test_put_chunked_close$(EXEEXT): $(test_put_chunked_close_OBJECTS) $(test_put_chunked_close_DEPENDENCIES) $(EXTRA_test_put_chunked_close_DEPENDENCIES) @rm -f test_put_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_close_OBJECTS) $(test_put_chunked_close_LDADD) $(LIBS) test_put_close$(EXEEXT): $(test_put_close_OBJECTS) $(test_put_close_DEPENDENCIES) $(EXTRA_test_put_close_DEPENDENCIES) @rm -f test_put_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_close_OBJECTS) $(test_put_close_LDADD) $(LIBS) test_put_large$(EXEEXT): $(test_put_large_OBJECTS) $(test_put_large_DEPENDENCIES) $(EXTRA_test_put_large_DEPENDENCIES) @rm -f test_put_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_OBJECTS) $(test_put_large_LDADD) $(LIBS) test_put_large10$(EXEEXT): $(test_put_large10_OBJECTS) $(test_put_large10_DEPENDENCIES) $(EXTRA_test_put_large10_DEPENDENCIES) @rm -f test_put_large10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large10_OBJECTS) $(test_put_large10_LDADD) $(LIBS) test_put_large_close$(EXEEXT): $(test_put_large_close_OBJECTS) $(test_put_large_close_DEPENDENCIES) $(EXTRA_test_put_large_close_DEPENDENCIES) @rm -f test_put_large_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_close_OBJECTS) $(test_put_large_close_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_debug_funcs.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) $(check_SCRIPTS) $(dist_check_SCRIPTS) @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) $(check_SCRIPTS) $(dist_check_SCRIPTS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_get.log: test_get$(EXEEXT) @p='test_get$(EXEEXT)'; \ b='test_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked.log: test_get_chunked$(EXEEXT) @p='test_get_chunked$(EXEEXT)'; \ b='test_get_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post.log: test_post$(EXEEXT) @p='test_post$(EXEEXT)'; \ b='test_post'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form.log: test_post_form$(EXEEXT) @p='test_post_form$(EXEEXT)'; \ b='test_post_form'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put.log: test_put$(EXEEXT) @p='test_put$(EXEEXT)'; \ b='test_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked.log: test_put_chunked$(EXEEXT) @p='test_put_chunked$(EXEEXT)'; \ b='test_put_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large.log: test_put_large$(EXEEXT) @p='test_put_large$(EXEEXT)'; \ b='test_put_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri.log: test_get_long_uri$(EXEEXT) @p='test_get_long_uri$(EXEEXT)'; \ b='test_get_long_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header.log: test_get_long_header$(EXEEXT) @p='test_get_long_header$(EXEEXT)'; \ b='test_get_long_header'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close.log: test_get_close$(EXEEXT) @p='test_get_close$(EXEEXT)'; \ b='test_get_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close.log: test_get_chunked_close$(EXEEXT) @p='test_get_chunked_close$(EXEEXT)'; \ b='test_get_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_close.log: test_post_close$(EXEEXT) @p='test_post_close$(EXEEXT)'; \ b='test_post_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form_close.log: test_post_form_close$(EXEEXT) @p='test_post_form_close$(EXEEXT)'; \ b='test_post_form_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_close.log: test_put_close$(EXEEXT) @p='test_put_close$(EXEEXT)'; \ b='test_put_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked_close.log: test_put_chunked_close$(EXEEXT) @p='test_put_chunked_close$(EXEEXT)'; \ b='test_put_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_close.log: test_put_large_close$(EXEEXT) @p='test_put_large_close$(EXEEXT)'; \ b='test_put_large_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri_close.log: test_get_long_uri_close$(EXEEXT) @p='test_get_long_uri_close$(EXEEXT)'; \ b='test_get_long_uri_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header_close.log: test_get_long_header_close$(EXEEXT) @p='test_get_long_header_close$(EXEEXT)'; \ b='test_get_long_header_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get10.log: test_get10$(EXEEXT) @p='test_get10$(EXEEXT)'; \ b='test_get10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked10.log: test_get_chunked10$(EXEEXT) @p='test_get_chunked10$(EXEEXT)'; \ b='test_get_chunked10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post10.log: test_post10$(EXEEXT) @p='test_post10$(EXEEXT)'; \ b='test_post10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form10.log: test_post_form10$(EXEEXT) @p='test_post_form10$(EXEEXT)'; \ b='test_post_form10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put10.log: test_put10$(EXEEXT) @p='test_put10$(EXEEXT)'; \ b='test_put10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large10.log: test_put_large10$(EXEEXT) @p='test_put_large10$(EXEEXT)'; \ b='test_put_large10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri10.log: test_get_long_uri10$(EXEEXT) @p='test_get_long_uri10$(EXEEXT)'; \ b='test_get_long_uri10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header10.log: test_get_long_header10$(EXEEXT) @p='test_get_long_header10$(EXEEXT)'; \ b='test_get_long_header10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(check_SCRIPTS) \ $(dist_check_SCRIPTS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/mhd_debug_funcs.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/mhd_debug_funcs.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la .NOTPARALLEL: @VHEAVY_TESTS_TRUE@.PHONY: warn_vheavy_use warn_vheavy_use: @echo "NOTICE" ; \ echo "NOTICE: Full heavy tests are enabled. Each test may take up to several minutes to complete." ; \ echo "NOTICE" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/testzzuf/mhd_debug_funcs.h0000644000175000017500000000327214760713577017276 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_debug_funcs.h * @brief Declarations of MHD private debug functions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_DEBUG_FUNCS_H #define MHD_DEBUG_FUNCS_H 1 struct MHD_Daemon; /** * Checks whether MHD can use accept() syscall and * avoid accept4() syscall. * @return non-zero if accept() is possible, * zero if accept4() is always used by MHD */ int MHD_is_avoid_accept4_possible_ (void); /** * Switch MHD daemon to use accept() syscalls for new connections. * @param daemon the daemon to operate */ void MHD_avoid_accept4_ (struct MHD_Daemon *daemon); /** * Checks whether any know sanitizer is enabled for this build. * zzuf does not work together with sanitizers as both are intercepting * standard library calls. * @return non-zero if any sanitizer is enabled, * zero otherwise */ int MHD_are_sanitizers_enabled_ (void); #endif /* MHD_DEBUG_FUNCS_H */ libmicrohttpd-1.0.2/src/testzzuf/Makefile.am0000644000175000017500000000720314760713600016026 00000000000000# This Makefile.am is in the public domain SUBDIRS = . # ZZUF_SEED can be redefined to use other initial seeds # for extended testing. E.g., # make ZZUF_SEED=1234 check ZZUF_SEED = 0 # Additional flags for zzuf ZZUF_FLAGS = # Additional flags for socat (if socat is used) SOCAT_FLAGS = if FORCE_USE_ZZUF_SOCAT TEST_RUNNER_SCRIPT = zzuf_socat_test_runner.sh else TEST_RUNNER_SCRIPT = zzuf_test_runner.sh endif AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ ZZUF="$(ZZUF)" ; export ZZUF ; \ ZZUF_SEED="$(ZZUF_SEED)" ; export ZZUF_SEED ; \ ZZUF_FLAGS="$(ZZUF_FLAGS)" ; export ZZUF_FLAGS ; \ SOCAT="$(SOCAT)" ; export SOCAT ; \ SOCAT_FLAGS="$(SOCAT_FLAGS)" ; export SOCAT_FLAGS ; if USE_COVERAGE AM_CFLAGS += -fprofile-arcs -ftest-coverage endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la check_PROGRAMS = \ test_get \ test_get_chunked \ test_post \ test_post_form \ test_put \ test_put_chunked \ test_put_large \ test_get_long_uri \ test_get_long_header \ test_get_close \ test_get_chunked_close \ test_post_close \ test_post_form_close \ test_put_close \ test_put_chunked_close \ test_put_large_close \ test_get_long_uri_close \ test_get_long_header_close \ test_get10 \ test_get_chunked10 \ test_post10 \ test_post_form10 \ test_put10 \ test_put_large10 \ test_get_long_uri10 \ test_get_long_header10 .NOTPARALLEL: TESTS = $(check_PROGRAMS) dist_check_SCRIPTS = zzuf_test_runner.sh zzuf_socat_test_runner.sh LOG_COMPILER = @SHELL@ "$(srcdir)/$(TEST_RUNNER_SCRIPT)" if VHEAVY_TESTS check_SCRIPTS = warn_vheavy_use .PHONY: warn_vheavy_use endif warn_vheavy_use: @echo "NOTICE" ; \ echo "NOTICE: Full heavy tests are enabled. Each test may take up to several minutes to complete." ; \ echo "NOTICE" tests_common_sources = mhd_debug_funcs.h mhd_debug_funcs.c test_get_SOURCES = \ test_get.c $(tests_common_sources) test_get_chunked_SOURCES = $(test_get_SOURCES) test_post_SOURCES = $(test_get_SOURCES) test_post_form_SOURCES = $(test_get_SOURCES) test_put_SOURCES = $(test_get_SOURCES) test_put_chunked_SOURCES = $(test_get_SOURCES) test_put_large_SOURCES = $(test_get_SOURCES) test_get_long_uri_SOURCES = $(test_get_SOURCES) test_get_long_header_SOURCES = $(test_get_SOURCES) test_get_close_SOURCES = $(test_get_SOURCES) test_get_chunked_close_SOURCES = $(test_get_chunked_SOURCES) test_post_close_SOURCES = $(test_post_SOURCES) test_post_form_close_SOURCES = $(test_post_form_SOURCES) test_put_close_SOURCES = $(test_put_SOURCES) test_put_chunked_close_SOURCES = $(test_put_chunked_SOURCES) test_put_large_close_SOURCES = $(test_put_large_SOURCES) test_get_long_uri_close_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header_close_SOURCES = $(test_get_long_header_SOURCES) test_get10_SOURCES = $(test_get_SOURCES) test_get_chunked10_SOURCES = $(test_get_chunked_SOURCES) test_post10_SOURCES = $(test_post_SOURCES) test_post_form10_SOURCES = $(test_post_form_SOURCES) test_put10_SOURCES = $(test_put_SOURCES) test_put_large10_SOURCES = $(test_put_large_SOURCES) test_get_long_uri10_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header10_SOURCES = $(test_get_long_header_SOURCES) libmicrohttpd-1.0.2/src/testzzuf/test_get.c0000644000175000017500000014351714760713574015777 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_get.c * @brief Several testcases for libmicrohttpd with input fuzzing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_debug_funcs.h" #include "test_helpers.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ /** * A larger loop count will run more random tests -- * which would be good, except that it may take too * long for most user's patience. So this small * value is the default. * Can be redefined by CPPFLAGS=-DLOOP_COUNT=123 */ #ifndef LOOP_COUNT #ifndef _MHD_VHEAVY_TESTS #define LOOP_COUNT 10 #else /* ! _MHD_HEAVY_TESTS */ #define LOOP_COUNT 200 #endif /* ! _MHD_HEAVY_TESTS */ #endif /* LOOP_COUNT */ #ifdef _DEBUG /* Uncomment the next line (or use CPPFLAGS) to see all request and response bodies in log */ /* #define TEST_PRINT_BODY */ /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are sent by libcurl */ /* #define TEST_PRINT_BODY_RQ 1 */ /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are received by libcurl */ /* #define TEST_PRINT_BODY_RP 1 */ #endif /* _DEBUG */ #define MHD_TIMEOUT 2 #define CURL_TIMEOUT 5 /* Global test parameters */ static int oneone; static int dry_run; static int use_get; static int use_get_chunked; static int use_put; static int use_put_large; static int use_put_chunked; static int use_post; static int use_post_form; static int use_long_header; static int use_long_uri; static int use_close; static int run_with_socat; #define TEST_BASE_URI "http:/" "/127.0.0.1/test_uri" #define TEST_BASE_URI_SOCAT "http:/" "/127.0.0.121/test_uri" #define SOCAT_PORT 10121 #define TEST_BASE_PORT 4010 #define EMPTY_PAGE "Empty page." #define EMPTY_PAGE_ALT "Alternative empty page." #define METHOD_NOT_SUPPORTED "HTTP method is not supported." #define POST_DATA_BROKEN "The POST request is ill-formed." #define POST_KEY1 "test" #define POST_VALUE1 "test_post" #define POST_KEY2 "library" #define POST_VALUE2 "GNU libmicrohttpd" #define POST_URLENC_DATA \ POST_KEY1 "=" POST_VALUE1 "&" POST_KEY2 "=" "GNU%20libmicrohttpd" #define PUT_NORMAL_SIZE 11 /* Does not need to be very large as MHD buffer will be made smaller anyway */ #define PUT_LARGE_SIZE (4 * 1024) /* The length of "very long" URI and header strings. MHD uses smaller buffer. */ #define TEST_STRING_VLONG_LEN 8 * 1024 #if ! CURL_AT_LEAST_VERSION (7,56,0) #define TEST_USE_STATIC_POST_DATA 1 static struct curl_httppost *post_first; static struct curl_httppost *post_last; #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */ static struct curl_slist *libcurl_long_header; /** * Initialise long header for libcurl * * @return non-zero if succeed, * zero if failed */ static int long_header_init (void) { char *buf; buf = malloc (TEST_STRING_VLONG_LEN + 1); if (NULL == buf) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return 0; } buf[TEST_STRING_VLONG_LEN] = 0; buf[0] = 'A'; memset (buf + 1, 'a', TEST_STRING_VLONG_LEN / 2 - 2); buf[TEST_STRING_VLONG_LEN / 2 - 1] = ':'; buf[TEST_STRING_VLONG_LEN / 2] = ' '; memset (buf + TEST_STRING_VLONG_LEN / 2 + 1, 'c', TEST_STRING_VLONG_LEN / 2 - 1); libcurl_long_header = curl_slist_append (NULL, buf); free (buf); if (NULL != libcurl_long_header) return ! 0; /* Success exit point */ fprintf (stderr, "curl_slist_append() failed " "at line %d.\n", (int) __LINE__); return 0; /* Failure exit point */ } /** * Globally initialise test environment * @return non-zero if succeed, * zero if failed */ static int test_global_init (void) { libcurl_long_header = NULL; if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32)) { fprintf (stderr, "curl_global_init() failed " "at line %d.\n", (int) __LINE__); return 0; } if (long_header_init ()) { #ifndef TEST_USE_STATIC_POST_DATA return 1; /* Success exit point */ #else /* ! TEST_USE_STATIC_POST_DATA */ post_first = NULL; post_last = NULL; if ((CURL_FORMADD_OK != curl_formadd (&post_first, &post_last, CURLFORM_PTRNAME, POST_KEY1, CURLFORM_NAMELENGTH, (long) MHD_STATICSTR_LEN_ (POST_KEY1), CURLFORM_PTRCONTENTS, POST_VALUE1, #if CURL_AT_LEAST_VERSION (7,46,0) CURLFORM_CONTENTLEN, (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE1), #else /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_CONTENTSLENGTH, (long) MHD_STATICSTR_LEN_ (POST_VALUE1), #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_END)) || (CURL_FORMADD_OK != curl_formadd (&post_first, &post_last, CURLFORM_PTRNAME, POST_KEY2, CURLFORM_NAMELENGTH, (long) MHD_STATICSTR_LEN_ (POST_KEY2), CURLFORM_PTRCONTENTS, POST_VALUE2, #if CURL_AT_LEAST_VERSION (7,46,0) CURLFORM_CONTENTLEN, (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE2), #else /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_CONTENTSLENGTH, (long) MHD_STATICSTR_LEN_ (POST_VALUE2), #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_END))) fprintf (stderr, "curl_formadd() failed " "at line %d.\n", (int) __LINE__); else return 1; /* Success exit point */ if (NULL != post_first) curl_formfree (post_first); curl_slist_free_all (libcurl_long_header); #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */ } curl_global_cleanup (); return 0; /* Failure exit point */ } /** * Globally de-initialise test environment */ static void test_global_deinit (void) { #ifdef TEST_USE_STATIC_POST_DATA curl_formfree (post_first); #endif /* TEST_USE_STATIC_POST_DATA */ curl_global_cleanup (); if (NULL != libcurl_long_header) curl_slist_free_all (libcurl_long_header); } /** * libcurl callback parameters for uploads, downloads and debug callbacks */ struct CBC { /* Upload members */ size_t up_pos; size_t up_size; /* Download members */ char *dn_buf; size_t dn_pos; size_t dn_buf_size; /* Debug callback members */ unsigned int excess_found; }; static void initCBC (struct CBC *libcurlcbc, char *dn_buf, size_t dn_buf_size) { libcurlcbc->up_pos = 0; if (use_put_large) libcurlcbc->up_size = PUT_LARGE_SIZE; else if (use_put) libcurlcbc->up_size = PUT_NORMAL_SIZE; else libcurlcbc->up_size = 0; libcurlcbc->dn_buf = dn_buf; libcurlcbc->dn_pos = 0; libcurlcbc->dn_buf_size = dn_buf_size; libcurlcbc->excess_found = 0; } static void resetCBC (struct CBC *libcurlcbc) { libcurlcbc->up_pos = 0; libcurlcbc->dn_pos = 0; } static size_t putBuffer (void *stream, size_t item_size, size_t nitems, void *ctx) { size_t to_fill; size_t i; struct CBC *cbc = ctx; to_fill = cbc->up_size - cbc->up_pos; /* Skip overflow check as the return value is valid anyway */ if (use_put_chunked) { /* Send data as several chunks */ if (to_fill > cbc->up_size / 3) to_fill = cbc->up_size / 3; } if (to_fill > item_size * nitems) to_fill = item_size * nitems; /* Avoid libcurl magic numbers */ #ifdef CURL_READFUNC_PAUSE if (CURL_READFUNC_ABORT == to_fill) to_fill -= 2; #endif /* CURL_READFUNC_PAUSE */ #ifdef CURL_READFUNC_ABORT if (CURL_READFUNC_ABORT == to_fill) --to_fill; #endif /* CURL_READFUNC_ABORT */ for (i = 0; i < to_fill; ++i) ((char *) stream)[i] = 'a' + (char) ((cbc->up_pos + i) % (unsigned char) ('z' - 'a' + 1)); cbc->up_pos += to_fill; return to_fill; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->dn_pos + size * nmemb > cbc->dn_buf_size) return 0; /* overflow */ memcpy (&cbc->dn_buf[cbc->dn_pos], ptr, size * nmemb); cbc->dn_pos += size * nmemb; return size * nmemb; } #define TEST_MAGIC_MARKER0 0xFEE1C0DE #define TEST_MAGIC_MARKER1 (TEST_MAGIC_MARKER0 + 1) #define TEST_MAGIC_MARKER2 (TEST_MAGIC_MARKER0 + 2) struct content_cb_param_strct { unsigned int magic0; /**< Must have TEST_MAGIC_MARKER0 value */ struct MHD_Response *response; /**< The pointer to the response structure */ }; /** * MHD content reader callback that returns * data in chunks. */ static ssize_t content_cb (void *cls, uint64_t pos, char *buf, size_t max) { struct content_cb_param_strct *param = (struct content_cb_param_strct *) cls; size_t fill_size; if ((unsigned int) TEST_MAGIC_MARKER0 != param->magic0) { fprintf (stderr, "Wrong cls pointer " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (pos >= 128 * 10) { if (MHD_YES != MHD_add_response_footer (param->response, "Footer", "working")) { fprintf (stderr, "MHD_add_response_footer() failed " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } return MHD_CONTENT_READER_END_OF_STREAM; } if (128 > max) fill_size = 128; else fill_size = max; memset (buf, 'A' + (char) (unsigned int) (pos / 128), fill_size); return (ssize_t) fill_size; } /** * Deallocate memory for callback cls. */ static void crcf (void *ptr) { free (ptr); } struct req_process_strct { unsigned int magic2; /**< Must have TEST_MAGIC_MARKER2 value */ int is_static; /**< Non-zero if statically allocated, zero if malloc()'ed */ struct MHD_PostProcessor *postprocsr; unsigned int post_data_sum; }; static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { struct req_process_strct *param = (struct req_process_strct *) cls; size_t i; (void) filename; (void) content_type; (void) transfer_encoding; (void) off; /* Unused. Mute compiler warnings. */ if (TEST_MAGIC_MARKER2 != param->magic2) { fprintf (stderr, "The 'param->magic2' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (MHD_POSTDATA_KIND != kind) { fprintf (stderr, "The 'kind' parameter has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (NULL != key) param->post_data_sum += (unsigned int) strlen (key); for (i = 0; size > i; ++i) param->post_data_sum += (unsigned int) (unsigned char) value[i]; return MHD_YES; } static void free_req_pr_data (struct req_process_strct *pr_data) { if (NULL == pr_data) return; if (TEST_MAGIC_MARKER2 != pr_data->magic2) { fprintf (stderr, "The 'pr_data->magic2' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (pr_data->is_static) { if (NULL != pr_data->postprocsr) { fprintf (stderr, "The 'pr_data->postprocsr' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } return; } if (NULL != pr_data->postprocsr) MHD_destroy_post_processor (pr_data->postprocsr); pr_data->postprocsr = NULL; free (pr_data); } struct ahc_param_strct { unsigned int magic1; /**< Must have TEST_MAGIC_MARKER1 value */ unsigned int err_flag; /**< Non-zero if any error is encountered */ unsigned int num_replies; /**< The number of replies sent for the current request */ }; static enum MHD_Result send_error_response (struct MHD_Connection *connection, struct ahc_param_strct *param, unsigned int status_code, const char *static_text, const size_t static_text_len) { struct MHD_Response *response; response = MHD_create_response_from_buffer_static (static_text_len, static_text); if (NULL != response) { if (MHD_YES == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close")) { if (MHD_YES == MHD_queue_response (connection, status_code, response)) { MHD_destroy_response (response); return MHD_YES; /* Success exit point */ } else fprintf (stderr, "MHD_queue_response() failed " "at line %d.\n", (int) __LINE__); } else fprintf (stderr, "MHD_add_response_header() failed " "at line %d.\n", (int) __LINE__); MHD_destroy_response (response); } else fprintf (stderr, "MHD_create_response_from_callback() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Failure exit point */ } static enum MHD_Result ahc_check (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static struct req_process_strct static_req_pr_data = { TEST_MAGIC_MARKER2, ! 0, NULL, 0 }; struct req_process_strct *req_pr_data; struct ahc_param_strct *param = (struct ahc_param_strct *) cls; struct MHD_Response *response; enum MHD_Result ret; unsigned char data_sum; int is_post_req; if (NULL == cls) { fprintf (stderr, "The 'cls' parameter is NULL " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1) { fprintf (stderr, "The 'param->magic1' has wrong value " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == connection) { fprintf (stderr, "The 'connection' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (1) { /* Simple check for 'connection' parameter validity */ const union MHD_ConnectionInfo *conn_info; conn_info = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CONNECTION_TIMEOUT); if (NULL == conn_info) { fprintf (stderr, "The 'MHD_get_connection_info' has returned NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } else if (MHD_TIMEOUT != conn_info->connection_timeout) { fprintf (stderr, "The 'MHD_get_connection_info' has returned " "unexpected timeout value " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } if (NULL == url) { fprintf (stderr, "The 'url' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } if (NULL == method) { fprintf (stderr, "The 'method' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (NULL == version) { fprintf (stderr, "The 'version' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (NULL == upload_data_size) { fprintf (stderr, "The 'upload_data_size' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if ((0 != *upload_data_size) && (NULL == upload_data)) { fprintf (stderr, "The 'upload_data' parameter is NULL " "while '*upload_data_size' is not zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if ((NULL != upload_data) && (0 == *upload_data_size)) { fprintf (stderr, "The 'upload_data' parameter is NOT NULL " "while '*upload_data_size' is zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (0 != param->num_replies) { /* Phantom "second" request due to the fuzzing of the input. Refuse. */ return MHD_NO; } is_post_req = (0 == strcmp (method, MHD_HTTP_METHOD_POST)); if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) && (0 != strcmp (method, MHD_HTTP_METHOD_PUT)) && (! is_post_req)) { /* Unsupported method for this callback */ return send_error_response (connection, param, MHD_HTTP_NOT_IMPLEMENTED, METHOD_NOT_SUPPORTED, MHD_STATICSTR_LEN_ (METHOD_NOT_SUPPORTED)); } if (NULL == *req_cls) { if (! is_post_req) { /* Use static memory */ *req_cls = &static_req_pr_data; } else { /* POST request, use PostProcessor */ req_pr_data = (struct req_process_strct *) malloc (sizeof (struct req_process_strct)); if (NULL == req_pr_data) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return MHD_NO; } req_pr_data->magic2 = TEST_MAGIC_MARKER2; req_pr_data->is_static = 0; req_pr_data->post_data_sum = 0; req_pr_data->postprocsr = MHD_create_post_processor (connection, 1024, &post_iterator, req_pr_data); if (NULL == req_pr_data->postprocsr) { free (req_pr_data); if (NULL == upload_data) return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST, POST_DATA_BROKEN, MHD_STATICSTR_LEN_ (POST_DATA_BROKEN)); else return MHD_NO; /* Cannot handle request, broken POST */ } *req_cls = req_pr_data; } if (NULL == upload_data) return MHD_YES; } req_pr_data = (struct req_process_strct *) *req_cls; data_sum = 0; if (NULL != upload_data) { if (is_post_req) { if (MHD_YES != MHD_post_process (req_pr_data->postprocsr, upload_data, *upload_data_size)) { free_req_pr_data (req_pr_data); *req_cls = NULL; /* Processing upload body (context), error reply cannot be queued here */ return MHD_NO; } *upload_data_size = 0; /* All data have been processed */ } else { /* Check that all 'upload_data' is addressable */ size_t pos; for (pos = 0; pos < *upload_data_size; ++pos) data_sum = (unsigned char) (data_sum + (unsigned char) upload_data[pos]); if (0 != *upload_data_size) { if (3 >= *upload_data_size) *upload_data_size = 0; /* Consume all incoming data */ else *upload_data_size = data_sum % *upload_data_size; /* Pseudo-random */ } } return MHD_YES; } if (is_post_req) { if (MHD_YES != MHD_destroy_post_processor (req_pr_data->postprocsr)) { free (req_pr_data); *req_cls = NULL; return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST, POST_DATA_BROKEN, MHD_STATICSTR_LEN_ (POST_DATA_BROKEN)); } req_pr_data->postprocsr = NULL; } data_sum += (unsigned char) req_pr_data->post_data_sum; free_req_pr_data (req_pr_data); *req_cls = NULL; ret = MHD_YES; if (use_get_chunked) { struct content_cb_param_strct *cnt_cb_param; cnt_cb_param = malloc (sizeof (struct content_cb_param_strct)); if (NULL == cnt_cb_param) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); /* External error, do not rise the error flag */ return MHD_NO; } cnt_cb_param->magic0 = (unsigned int) TEST_MAGIC_MARKER0; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &content_cb, cnt_cb_param, &crcf); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_callback() failed " "at line %d.\n", (int) __LINE__); free (cnt_cb_param); param->err_flag = 1; ret = MHD_NO; } else cnt_cb_param->response = response; } else if (use_get || use_put || use_post) { /* Randomly choose the response page for the POST requests */ if (0 == data_sum % 2) response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); else response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ ( \ EMPTY_PAGE_ALT), EMPTY_PAGE_ALT); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; ret = MHD_NO; } } else { fprintf (stderr, "Response is not implemented for this test. " "Internal logic is broken. " "At line %d.\n", (int) __LINE__); abort (); } if (NULL != response) { if ((MHD_YES == ret) && (use_close || (! oneone && (0 != strcmp (version, MHD_HTTP_VERSION_1_0))))) { ret = MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); if (MHD_YES != ret) { fprintf (stderr, "MHD_add_response_header() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } if (MHD_YES == ret) { ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) { fprintf (stderr, "MHD_queue_response() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } else param->num_replies++; MHD_destroy_response (response); } else { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); ret = MHD_NO; } return ret; } static void req_completed_cleanup (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct ahc_param_strct *param = (struct ahc_param_strct *) cls; struct req_process_strct *req_pr_data = (struct req_process_strct *) *req_cls; (void) connection; /* Unused. Mute compiler warning. */ if (NULL == param) { fprintf (stderr, "The 'cls' parameter is NULL at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1) { fprintf (stderr, "The 'param->magic1' has wrong value at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == req_pr_data) return; /* The data have been freed */ if ((unsigned int) TEST_MAGIC_MARKER2 != req_pr_data->magic2) { fprintf (stderr, "The 'req_pr_data->magic2' has wrong value at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (MHD_REQUEST_TERMINATED_COMPLETED_OK == toe) { fprintf (stderr, "The request completed successful, but request cls has" "not been cleared. " "At line %d.\n", (int) __LINE__); param->err_flag = 1; } if (req_pr_data->is_static) return; if (NULL != req_pr_data->postprocsr) MHD_destroy_post_processor (req_pr_data->postprocsr); req_pr_data->postprocsr = NULL; free (req_pr_data); *req_cls = NULL; } /* Un-comment the next line (or use CPPFLAGS) to avoid logging of the traffic with debug builds */ /* #define TEST_NO_PRINT_TRAFFIC 1 */ #ifdef _DEBUG #ifdef TEST_PRINT_BODY #ifndef TEST_PRINT_BODY_RQ #define TEST_PRINT_BODY_RQ 1 #endif /* TEST_PRINT_BODY_RQ */ #ifndef TEST_PRINT_BODY_RP #define TEST_PRINT_BODY_RP 1 #endif /* TEST_PRINT_BODY_RP */ #endif /* TEST_PRINT_BODY */ #endif /* _DEBUG */ static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *ctx) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); struct CBC *cbc = ctx; (void) handle; #if defined(_DEBUG) && ! defined(TEST_NO_PRINT_TRAFFIC) switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #ifdef TEST_PRINT_BODY_RP fprintf (stderr, "<| %.*s\n", (int) size, data); #endif /* TEST_PRINT_BODY_RP */ break; case CURLINFO_DATA_OUT: #ifdef TEST_PRINT_BODY_RQ fprintf (stderr, ">| %.*s\n", (int) size, data); #endif /* TEST_PRINT_BODY_RQ */ break; case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG && ! TEST_NO_PRINT_TRAFFIC */ if (use_close || ! oneone) { /* Check for extra data only if every connection is terminated by MHD after one request, otherwise MHD may react on garbage after request data. */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) { fprintf (stderr, "Extra data has been detected in MHD reply " "at line %d.\n", (int) __LINE__); cbc->excess_found++; } } } return 0; } static CURL * setupCURL (struct CBC *cbc, uint16_t port #ifndef TEST_USE_STATIC_POST_DATA , curl_mime **mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ) { CURL *c; CURLcode e; char *buf; const char *uri_to_use; const char *base_uri; #ifndef TEST_USE_STATIC_POST_DATA *mime = NULL; #endif /* ! TEST_USE_STATIC_POST_DATA */ base_uri = run_with_socat ? TEST_BASE_URI_SOCAT : TEST_BASE_URI; if (! use_long_uri) { uri_to_use = base_uri; buf = NULL; } else { size_t pos; size_t base_uri_len; base_uri_len = strlen (base_uri); buf = malloc (TEST_STRING_VLONG_LEN + 1); if (NULL == buf) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return NULL; } memcpy (buf, base_uri, base_uri_len); for (pos = base_uri_len; pos < TEST_STRING_VLONG_LEN; ++pos) { if (0 == pos % 9) buf[pos] = '/'; else buf[pos] = 'a' + (char) (unsigned char) (pos % ((unsigned char) ('z' - 'a' + 1))); } buf[TEST_STRING_VLONG_LEN] = 0; uri_to_use = buf; } if (run_with_socat) port = SOCAT_PORT; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed " "at line %d.\n", (int) __LINE__); return NULL; } if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_URL, uri_to_use))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) CURL_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) CURL_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L))) && #ifdef _DEBUG (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_VERBOSE, 1L))) && #endif /* _DEBUG */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGDATA, cbc))) && #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http"))) && #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http"))) && #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP))) && #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, oneone ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) && #if CURL_AT_LEAST_VERSION (7, 24, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, "host!127.0.0.101"))) && #else /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, "127.0.0.101"))) && #endif /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTPHEADER, use_long_header ? libcurl_long_header : NULL))) ) { if (NULL != buf) { free (buf); buf = NULL; } if (use_put) { if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READDATA, cbc))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_UPLOAD, (long) 1))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, use_put_chunked ? ((curl_off_t) -1) : ((curl_off_t) cbc->up_size))))) { return c; /* Success exit point for 'use_put' */ } else fprintf (stderr, "PUT-related curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else if (use_post) { if (! use_post_form) { if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POST, (long) 1))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_URLENC_DATA))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, MHD_STATICSTR_LEN_ (POST_URLENC_DATA))))) { return c; /* Success exit point for 'use_post' */ } else fprintf (stderr, "POST-related curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else { #ifndef TEST_USE_STATIC_POST_DATA *mime = curl_mime_init (c); if (NULL != *mime) { curl_mimepart *part; if ((NULL != (part = curl_mime_addpart (*mime))) && (CURLE_OK == curl_mime_name (part, POST_KEY1)) && (CURLE_OK == curl_mime_data (part, POST_VALUE1, MHD_STATICSTR_LEN_ (POST_VALUE1))) && (NULL != (part = curl_mime_addpart (*mime))) && (CURLE_OK == curl_mime_name (part, POST_KEY2)) && (CURLE_OK == curl_mime_data (part, POST_VALUE2, MHD_STATICSTR_LEN_ (POST_VALUE2)))) { if (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_MIMEPOST, *mime))) return c; /* Success exit point for 'use_post' */ else fprintf (stderr, "curl_easy_setopt(c, CURLOPT_MIMEPOST, mime) " "failed at line %d, error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else fprintf (stderr, "curl_mime_addpart(), curl_mime_name() or " "curl_mime_data() failed.\n"); } else fprintf (stderr, "curl_mime_init() failed.\n"); #else /* TEST_USE_STATIC_POST_DATA */ if (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTPPOST, post_first))) { return c; /* Success exit point for 'use_post' */ } else fprintf (stderr, "POST form-related curl_easy_setopt() failed, " "error: %s\n", curl_easy_strerror (e)); #endif /* TEST_USE_STATIC_POST_DATA */ } } else return c; /* Success exit point */ } else fprintf (stderr, "curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); curl_easy_cleanup (c); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != *mime) curl_mime_free (*mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ if (NULL != buf) free (buf); return NULL; /* Failure exit point */ } static struct MHD_Daemon * start_daemon_for_test (unsigned int daemon_flags, uint16_t *pport, struct ahc_param_strct *callback_param) { struct MHD_Daemon *d; struct MHD_OptionItem ops[] = { { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL } }; size_t num_opt; num_opt = 0; callback_param->magic1 = (unsigned int) TEST_MAGIC_MARKER1; callback_param->err_flag = 0; callback_param->num_replies = 0; if (use_put_large) { ops[num_opt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; ops[num_opt].value = (intptr_t) (PUT_LARGE_SIZE / 4); ++num_opt; } else if (use_long_header || use_long_uri) { ops[num_opt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; ops[num_opt].value = (intptr_t) (TEST_STRING_VLONG_LEN / 2); ++num_opt; } if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { ops[num_opt].option = MHD_OPTION_APP_FD_SETSIZE; ops[num_opt].value = (intptr_t) (FD_SETSIZE); ++num_opt; } d = MHD_start_daemon (daemon_flags /* | MHD_USE_ERROR_LOG */, *pport, NULL, NULL, &ahc_check, callback_param, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) MHD_TIMEOUT, MHD_OPTION_NOTIFY_COMPLETED, &req_completed_cleanup, callback_param, MHD_OPTION_ARRAY, ops, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "MHD_start_daemon() failed " "at line %d.\n", (int) __LINE__); return NULL; } /* Do not use accept4() as only accept() is intercepted by zzuf */ if (! run_with_socat) MHD_avoid_accept4_ (d); if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed " "at line %d.\n", (int) __LINE__); MHD_stop_daemon (d); return NULL; } *pport = dinfo->port; } return d; } static void print_test_starting (unsigned int daemon_flags) { fflush (stderr); if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { if (0 != (MHD_USE_THREAD_PER_CONNECTION & daemon_flags)) { if (0 != (MHD_USE_POLL & daemon_flags)) printf ("\nStarting test with internal polling by poll() and " "thread-per-connection.\n"); else printf ("\nStarting test with internal polling by select() and " "thread-per-connection.\n"); } else { if (0 != (MHD_USE_POLL & daemon_flags)) printf ("\nStarting test with internal polling by poll().\n"); else if (0 != (MHD_USE_EPOLL & daemon_flags)) printf ("\nStarting test with internal polling by 'epoll'.\n"); else printf ("\nStarting test with internal polling by select().\n"); } } else { if (0 != (MHD_USE_EPOLL & daemon_flags)) printf ("\nStarting test with%s thread safety with external polling " "and internal 'epoll'.\n", ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : "")); else printf ("\nStarting test with%s thread safety with external polling.\n", ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : "")); } fflush (stdout); } static unsigned int testInternalPolling (uint16_t *pport, unsigned int daemon_flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; struct ahc_param_strct callback_param; unsigned int ret; #ifndef TEST_USE_STATIC_POST_DATA curl_mime *mime; #endif /* ! TEST_USE_STATIC_POST_DATA */ if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { fprintf (stderr, "Wrong internal flags, the test is broken. " "At line %d.\n", (int) __LINE__); abort (); /* Wrong flags, error in code */ } print_test_starting (daemon_flags); initCBC (&cbc, buf, sizeof(buf)); d = start_daemon_for_test (daemon_flags, pport, &callback_param); if (d == NULL) return 1; ret = 0; c = setupCURL (&cbc, *pport #ifndef TEST_USE_STATIC_POST_DATA , &mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ); if (NULL != c) { int i; for (i = dry_run ? LOOP_COUNT : 0; i < LOOP_COUNT; i++) { fprintf (stderr, "."); callback_param.num_replies = 0; resetCBC (&cbc); /* Run libcurl without checking the result */ curl_easy_perform (c); fflush (stderr); } curl_easy_cleanup (c); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != mime) curl_mime_free (mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ } else ret = 99; /* Not an MHD error */ if ((0 == ret) && callback_param.err_flag) { fprintf (stderr, "One or more errors have been detected by " "access handler callback function. " "At line %d.\n", (int) __LINE__); ret = 1; } else if ((0 == ret) && cbc.excess_found) { fprintf (stderr, "The extra reply data have been detected one " "or more times. " "At line %d.\n", (int) __LINE__); ret = 1; } fprintf (stderr, "\n"); MHD_stop_daemon (d); fflush (stderr); return ret; } static unsigned int testExternalPolling (uint16_t *pport, unsigned int daemon_flags) { struct MHD_Daemon *d; CURLM *multi; char buf[2048]; struct CBC cbc; struct ahc_param_strct callback_param; unsigned int ret; #ifndef TEST_USE_STATIC_POST_DATA curl_mime *mime; #endif /* ! TEST_USE_STATIC_POST_DATA */ if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { fprintf (stderr, "Wrong internal flags, the test is broken. " "At line %d.\n", (int) __LINE__); abort (); /* Wrong flags, error in code */ } print_test_starting (daemon_flags); initCBC (&cbc, buf, sizeof(buf)); d = start_daemon_for_test (daemon_flags, pport, &callback_param); if (d == NULL) return 1; ret = 0; multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed " "at line %d.\n", (int) __LINE__); ret = 99; /* Not an MHD error */ } else { CURL *c; c = setupCURL (&cbc, *pport #ifndef TEST_USE_STATIC_POST_DATA , &mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ); if (NULL == c) ret = 99; /* Not an MHD error */ else { int i; for (i = dry_run ? LOOP_COUNT : 0; (i < LOOP_COUNT) && (0 == ret); i++) { CURLMcode mret; /* The same 'multi' handle will be used in transfers so connection will be reused. The same 'easy' handle is added (and removed later) to (re-)start the same transfer. */ mret = curl_multi_add_handle (multi, c); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_add_handle() failed at %d, " "error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); ret = 99; /* Not an MHD error */ } else { time_t start; fprintf (stderr, "."); callback_param.num_replies = 0; resetCBC (&cbc); start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; int maxfd_curl; MHD_socket maxfd_mhd; int maxfd; int running; struct timeval tv; maxfd_curl = 0; maxfd_mhd = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); if (0 == running) { int msgs_left; do { (void) curl_multi_info_read (multi, &msgs_left); } while (0 != msgs_left); break; /* The transfer has been finished */ } mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxfd_curl); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_fdset() failed at line %d, " "error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); ret = 99; /* Not an MHD error */ break; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxfd_mhd)) { fprintf (stderr, "MHD_get_fdset() failed " "at line %d.\n", (int) __LINE__); ret = 1; break; } #ifndef MHD_WINSOCK_SOCKETS if ((int) maxfd_mhd > maxfd_curl) maxfd = (int) maxfd_mhd; else #endif /* ! MHD_WINSOCK_SOCKETS */ maxfd = maxfd_curl; tv.tv_sec = 0; tv.tv_usec = 100 * 1000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } if (-1 == select (maxfd + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) fprintf (stderr, "Unexpected select() error " "at line %d.\n", (int) __LINE__); #else /* ! MHD_POSIX_SOCKETS */ if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count)) fprintf (stderr, "Unexpected select() error " "at line %d.\n", (int) __LINE__); Sleep ((unsigned long) tv.tv_usec / 1000); #endif /* ! MHD_POSIX_SOCKETS */ } MHD_run (d); } while (time (NULL) - start <= MHD_TIMEOUT); /* Remove 'easy' handle from 'multi' handle to * restart the transfer or to finish. */ curl_multi_remove_handle (multi, c); } } curl_easy_cleanup (c); } curl_multi_cleanup (multi); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != mime) curl_mime_free (mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ } if ((0 == ret) && callback_param.err_flag) { fprintf (stderr, "One or more errors have been detected by " "access handler callback function. " "At line %d.\n", (int) __LINE__); ret = 1; } else if ((0 == ret) && cbc.excess_found) { fprintf (stderr, "The extra reply data have been detected one " "or more times. " "At line %d.\n", (int) __LINE__); ret = 1; } fprintf (stderr, "\n"); MHD_stop_daemon (d); return 0; } static unsigned int run_all_checks (void) { uint16_t port; unsigned int testRes; unsigned int ret = 0; if (! run_with_socat) { if (MHD_are_sanitizers_enabled_ ()) { fprintf (stderr, "Direct run with zzuf does not work with sanitizers. " "At line %d.\n", (int) __LINE__); return 77; } if (! MHD_is_avoid_accept4_possible_ ()) { fprintf (stderr, "Non-debug build of MHD on this platform use accept4() function. " "Direct run with zzuf is not possible. " "At line %d.\n", (int) __LINE__); return 77; } if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else { port = TEST_BASE_PORT; /* Use predefined port, may break parallel testing of another MHD build */ if (oneone) port += 100; if (use_long_uri) port += 30; else if (use_long_header) port += 35; else if (use_get_chunked) port += 0; else if (use_get) port += 5; else if (use_post_form) port += 10; else if (use_post) port += 15; else if (use_put_large) port += 20; else if (use_put_chunked) port += 25; } } else port = TEST_BASE_PORT; /* Use predefined port, may break parallel testing of another MHD build */ if (! dry_run && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))) { testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { testRes = testInternalPolling (&port, MHD_USE_EPOLL_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; } testRes = testExternalPolling (&port, MHD_NO_FLAG); } testRes = testExternalPolling (&port, MHD_USE_NO_THREAD_SAFETY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; return ret; } int main (int argc, char *const *argv) { unsigned int res; int use_magic_exit_codes; oneone = ! has_in_name (argv[0], "10"); use_get = has_in_name (argv[0], "_get"); use_get_chunked = has_in_name (argv[0], "_get_chunked"); use_put = has_in_name (argv[0], "_put"); use_put_large = has_in_name (argv[0], "_put_large"); use_put_chunked = has_in_name (argv[0], "_put_chunked"); use_post = has_in_name (argv[0], "_post"); use_post_form = has_in_name (argv[0], "_post_form"); use_long_header = has_in_name (argv[0], "_long_header"); use_long_uri = has_in_name (argv[0], "_long_uri"); use_close = has_in_name (argv[0], "_close"); run_with_socat = has_param (argc, argv, "--with-socat"); dry_run = has_param (argc, argv, "--dry-run") || has_param (argc, argv, "-n"); if (1 != ((use_get ? 1 : 0) + (use_put ? 1 : 0) + (use_post ? 1 : 0))) { fprintf (stderr, "Wrong test name '%s': no or multiple indications " "for the test type.\n", argv[0] ? argv[0] : "(NULL)"); return 99; } use_magic_exit_codes = run_with_socat || dry_run; /* zzuf cannot bypass exit values. Unless 'dry run' is used, do not return errors for external error conditions (like out-of-memory) as they will be reported as test failures. */ if (! test_global_init ()) return use_magic_exit_codes ? 99 : 0; res = run_all_checks (); test_global_deinit (); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/0000755000175000017500000000000015035216652014330 500000000000000libmicrohttpd-1.0.2/src/microhttpd/basicauth.h0000644000175000017500000000256614760713577016411 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file basicauth.c * @brief Implements HTTP basic authentication methods * @author Amr Ali * @author Matthieu Speder * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BASICAUTH_H #define MHD_BASICAUTH_H 1 #include "mhd_str.h" /** * Beginning string for any valid Basic authentication header. */ #define _MHD_AUTH_BASIC_BASE "Basic" struct MHD_RqBAuth { struct _MHD_str_w_len token68; }; #endif /* ! MHD_BASICAUTH_H */ /* end of basicauth.h */ libmicrohttpd-1.0.2/src/microhttpd/sha512_256.c0000644000175000017500000007027715035214301016015 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha512_256.c * @brief Calculation of SHA-512/256 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha512_256.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA-512/256 calculation. * * @param ctx the calculation context */ void MHD_SHA512_256_init (struct Sha512_256Ctx *ctx) { /* Initial hash values, see FIPS PUB 180-4 clause 5.3.6.2 */ /* Values generated by "IV Generation Function" as described in * clause 5.3.6 */ ctx->H[0] = UINT64_C (0x22312194FC2BF72C); ctx->H[1] = UINT64_C (0x9F555FA3C84C64C2); ctx->H[2] = UINT64_C (0x2393B86B6F53B151); ctx->H[3] = UINT64_C (0x963877195940EABD); ctx->H[4] = UINT64_C (0x96283EE2A88EFFE3); ctx->H[5] = UINT64_C (0xBE5E1E2553863992); ctx->H[6] = UINT64_C (0x2B0199FC2C85B8AA); ctx->H[7] = UINT64_C (0x0EB72DDC81C52CA2); /* Initialise number of bytes and high part of number of bits. */ ctx->count = 0; ctx->count_bits_hi = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of SHA-512/256 transformation. * Gets full 128 bytes block of data and updates hash values; * @param H hash values * @param data the data buffer with #SHA512_256_BLOCK_SIZE bytes block */ static void sha512_256_transform (uint64_t H[SHA512_256_HASH_SIZE_WORDS], const void *data) { /* Working variables, see FIPS PUB 180-4 clause 6.7, 6.4. */ uint64_t a = H[0]; uint64_t b = H[1]; uint64_t c = H[2]; uint64_t d = H[3]; uint64_t e = H[4]; uint64_t f = H[5]; uint64_t g = H[6]; uint64_t h = H[7]; /* Data buffer, used as a cyclic buffer. See FIPS PUB 180-4 clause 5.2.2, 6.7, 6.4. */ uint64_t W[16]; #ifndef _MHD_GET_64BIT_BE_ALLOW_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT64_ALIGN)) { /* The input data is unaligned */ /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, sizeof(W)); /* The W[] buffer itself will be used as the source of the data, * but the data will be reloaded in correct bytes order on * the next steps */ data = (const void *) W; } #endif /* _MHD_GET_64BIT_BE_ALLOW_UNALIGNED */ /* 'Ch' and 'Maj' macro functions are defined with widely-used optimisation. See FIPS PUB 180-4 formulae 4.8, 4.9. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ /* Four 'Sigma' macro functions. See FIPS PUB 180-4 formulae 4.10, 4.11, 4.12, 4.13. */ #define SIG0(x) \ ( _MHD_ROTR64 ((x), 28) ^ _MHD_ROTR64 ((x), 34) ^ _MHD_ROTR64 ((x), 39) ) #define SIG1(x) \ ( _MHD_ROTR64 ((x), 14) ^ _MHD_ROTR64 ((x), 18) ^ _MHD_ROTR64 ((x), 41) ) #define sig0(x) \ ( _MHD_ROTR64 ((x), 1) ^ _MHD_ROTR64 ((x), 8) ^ ((x) >> 7) ) #define sig1(x) \ ( _MHD_ROTR64 ((x), 19) ^ _MHD_ROTR64 ((x), 61) ^ ((x) >> 6) ) /* One step of SHA-512/256 computation, see FIPS PUB 180-4 clause 6.4.2 step 3. * Note: this macro updates working variables in-place, without rotation. * Note: the first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in FIPS PUB 180-4 clause 6.4.2 step 3. the second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in FIPS PUB 180-4 clause 6.4.2 step 3. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA2STEP64(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt)); \ (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0) /* Get value of W(t) from input data buffer for 0 <= t <= 15, See FIPS PUB 180-4 clause 6.2. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 clause 3.1.2. */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_64BIT_BE (((const uint64_t*) (buf)) + (t)) /* 'W' generation and assignment for 16 <= t <= 79. See FIPS PUB 180-4 clause 6.4.2. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as a cyclic buffer. * Note: ((t-16) & 15) have same value as (t & 15) */ #define Wgen(w,t) ( (w)[(t - 16) & 15] + sig1 ((w)[((t) - 2) & 15]) \ + (w)[((t) - 7) & 15] + sig0 ((w)[((t) - 15) & 15]) ) #ifndef MHD_FAVOR_SMALL_CODE /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 clause 4.2.3 for K values. */ /* Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA2STEP64(a, b, c, d, e, f, g, h, K[0], data[0]); SHA2STEP64(h, a, b, c, d, e, f, g, K[1], data[1]); so current 'vD' will be used as 'vE' on next step, current 'vH' will be used as 'vA' on next step. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN if ((const void *) W == data) { /* The input data is already in the cyclic data buffer W[] in correct bytes order. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), W[0]); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), W[1]); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), W[2]); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), W[3]); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), W[4]); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), W[5]); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), W[6]); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), W[7]); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), W[8]); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), W[9]); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), W[10]); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), W[11]); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), W[12]); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), W[13]); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), W[14]); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), W[15]); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ if (1) { /* During first 16 steps, before making any calculations on each step, the W element is read from the input data buffer as big-endian value and stored in the array of W elements. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), \ W[0] = GET_W_FROM_DATA (data, 0)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), \ W[1] = GET_W_FROM_DATA (data, 1)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), \ W[2] = GET_W_FROM_DATA (data, 2)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), \ W[3] = GET_W_FROM_DATA (data, 3)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), \ W[4] = GET_W_FROM_DATA (data, 4)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), \ W[5] = GET_W_FROM_DATA (data, 5)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), \ W[6] = GET_W_FROM_DATA (data, 6)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), \ W[7] = GET_W_FROM_DATA (data, 7)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), \ W[8] = GET_W_FROM_DATA (data, 8)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), \ W[9] = GET_W_FROM_DATA (data, 9)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), \ W[10] = GET_W_FROM_DATA (data, 10)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), \ W[11] = GET_W_FROM_DATA (data, 11)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), \ W[12] = GET_W_FROM_DATA (data, 12)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), \ W[13] = GET_W_FROM_DATA (data, 13)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), \ W[14] = GET_W_FROM_DATA (data, 14)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), \ W[15] = GET_W_FROM_DATA (data, 15)); } /* During last 64 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 clause 4.2.3 for K values. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xe49b69c19ef14ad2), \ W[16 & 15] = Wgen (W,16)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xefbe4786384f25e3), \ W[17 & 15] = Wgen (W,17)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x0fc19dc68b8cd5b5), \ W[18 & 15] = Wgen (W,18)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x240ca1cc77ac9c65), \ W[19 & 15] = Wgen (W,19)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x2de92c6f592b0275), \ W[20 & 15] = Wgen (W,20)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4a7484aa6ea6e483), \ W[21 & 15] = Wgen (W,21)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5cb0a9dcbd41fbd4), \ W[22 & 15] = Wgen (W,22)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x76f988da831153b5), \ W[23 & 15] = Wgen (W,23)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x983e5152ee66dfab), \ W[24 & 15] = Wgen (W,24)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa831c66d2db43210), \ W[25 & 15] = Wgen (W,25)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb00327c898fb213f), \ W[26 & 15] = Wgen (W,26)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xbf597fc7beef0ee4), \ W[27 & 15] = Wgen (W,27)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xc6e00bf33da88fc2), \ W[28 & 15] = Wgen (W,28)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd5a79147930aa725), \ W[29 & 15] = Wgen (W,29)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x06ca6351e003826f), \ W[30 & 15] = Wgen (W,30)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x142929670a0e6e70), \ W[31 & 15] = Wgen (W,31)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x27b70a8546d22ffc), \ W[32 & 15] = Wgen (W,32)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x2e1b21385c26c926), \ W[33 & 15] = Wgen (W,33)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x4d2c6dfc5ac42aed), \ W[34 & 15] = Wgen (W,34)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x53380d139d95b3df), \ W[35 & 15] = Wgen (W,35)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x650a73548baf63de), \ W[36 & 15] = Wgen (W,36)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x766a0abb3c77b2a8), \ W[37 & 15] = Wgen (W,37)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x81c2c92e47edaee6), \ W[38 & 15] = Wgen (W,38)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x92722c851482353b), \ W[39 & 15] = Wgen (W,39)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xa2bfe8a14cf10364), \ W[40 & 15] = Wgen (W,40)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa81a664bbc423001), \ W[41 & 15] = Wgen (W,41)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xc24b8b70d0f89791), \ W[42 & 15] = Wgen (W,42)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xc76c51a30654be30), \ W[43 & 15] = Wgen (W,43)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xd192e819d6ef5218), \ W[44 & 15] = Wgen (W,44)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd69906245565a910), \ W[45 & 15] = Wgen (W,45)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xf40e35855771202a), \ W[46 & 15] = Wgen (W,46)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x106aa07032bbd1b8), \ W[47 & 15] = Wgen (W,47)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x19a4c116b8d2d0c8), \ W[48 & 15] = Wgen (W,48)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x1e376c085141ab53), \ W[49 & 15] = Wgen (W,49)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x2748774cdf8eeb99), \ W[50 & 15] = Wgen (W,50)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x34b0bcb5e19b48a8), \ W[51 & 15] = Wgen (W,51)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x391c0cb3c5c95a63), \ W[52 & 15] = Wgen (W,52)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4ed8aa4ae3418acb), \ W[53 & 15] = Wgen (W,53)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5b9cca4f7763e373), \ W[54 & 15] = Wgen (W,54)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x682e6ff3d6b2b8a3), \ W[55 & 15] = Wgen (W,55)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x748f82ee5defb2fc), \ W[56 & 15] = Wgen (W,56)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x78a5636f43172f60), \ W[57 & 15] = Wgen (W,57)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x84c87814a1f0ab72), \ W[58 & 15] = Wgen (W,58)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x8cc702081a6439ec), \ W[59 & 15] = Wgen (W,59)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x90befffa23631e28), \ W[60 & 15] = Wgen (W,60)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xa4506cebde82bde9), \ W[61 & 15] = Wgen (W,61)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xbef9a3f7b2c67915), \ W[62 & 15] = Wgen (W,62)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc67178f2e372532b), \ W[63 & 15] = Wgen (W,63)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xca273eceea26619c), \ W[64 & 15] = Wgen (W,64)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xd186b8c721c0c207), \ W[65 & 15] = Wgen (W,65)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xeada7dd6cde0eb1e), \ W[66 & 15] = Wgen (W,66)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xf57d4f7fee6ed178), \ W[67 & 15] = Wgen (W,67)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x06f067aa72176fba), \ W[68 & 15] = Wgen (W,68)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x0a637dc5a2c898a6), \ W[69 & 15] = Wgen (W,69)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x113f9804bef90dae), \ W[70 & 15] = Wgen (W,70)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x1b710b35131c471b), \ W[71 & 15] = Wgen (W,71)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x28db77f523047d84), \ W[72 & 15] = Wgen (W,72)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x32caab7b40c72493), \ W[73 & 15] = Wgen (W,73)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x3c9ebe0a15c9bebc), \ W[74 & 15] = Wgen (W,74)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x431d67c49c100d4c), \ W[75 & 15] = Wgen (W,75)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x4cc5d4becb3e42b6), \ W[76 & 15] = Wgen (W,76)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x597f299cfc657e2a), \ W[77 & 15] = Wgen (W,77)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5fcb6fab3ad6faec), \ W[78 & 15] = Wgen (W,78)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x6c44198c4a475817), \ W[79 & 15] = Wgen (W,79)); #else /* MHD_FAVOR_SMALL_CODE */ if (1) { unsigned int t; /* K constants array. See FIPS PUB 180-4 clause 4.2.3 for K values. */ static const uint64_t K[80] = { UINT64_C (0x428a2f98d728ae22), UINT64_C (0x7137449123ef65cd), UINT64_C (0xb5c0fbcfec4d3b2f), UINT64_C (0xe9b5dba58189dbbc), UINT64_C (0x3956c25bf348b538), UINT64_C (0x59f111f1b605d019), UINT64_C (0x923f82a4af194f9b), UINT64_C (0xab1c5ed5da6d8118), UINT64_C (0xd807aa98a3030242), UINT64_C (0x12835b0145706fbe), UINT64_C (0x243185be4ee4b28c), UINT64_C (0x550c7dc3d5ffb4e2), UINT64_C (0x72be5d74f27b896f), UINT64_C (0x80deb1fe3b1696b1), UINT64_C (0x9bdc06a725c71235), UINT64_C (0xc19bf174cf692694), UINT64_C (0xe49b69c19ef14ad2), UINT64_C (0xefbe4786384f25e3), UINT64_C (0x0fc19dc68b8cd5b5), UINT64_C (0x240ca1cc77ac9c65), UINT64_C (0x2de92c6f592b0275), UINT64_C (0x4a7484aa6ea6e483), UINT64_C (0x5cb0a9dcbd41fbd4), UINT64_C (0x76f988da831153b5), UINT64_C (0x983e5152ee66dfab), UINT64_C (0xa831c66d2db43210), UINT64_C (0xb00327c898fb213f), UINT64_C (0xbf597fc7beef0ee4), UINT64_C (0xc6e00bf33da88fc2), UINT64_C (0xd5a79147930aa725), UINT64_C (0x06ca6351e003826f), UINT64_C (0x142929670a0e6e70), UINT64_C (0x27b70a8546d22ffc), UINT64_C (0x2e1b21385c26c926), UINT64_C (0x4d2c6dfc5ac42aed), UINT64_C (0x53380d139d95b3df), UINT64_C (0x650a73548baf63de), UINT64_C (0x766a0abb3c77b2a8), UINT64_C (0x81c2c92e47edaee6), UINT64_C (0x92722c851482353b), UINT64_C (0xa2bfe8a14cf10364), UINT64_C (0xa81a664bbc423001), UINT64_C (0xc24b8b70d0f89791), UINT64_C (0xc76c51a30654be30), UINT64_C (0xd192e819d6ef5218), UINT64_C (0xd69906245565a910), UINT64_C (0xf40e35855771202a), UINT64_C (0x106aa07032bbd1b8), UINT64_C (0x19a4c116b8d2d0c8), UINT64_C (0x1e376c085141ab53), UINT64_C (0x2748774cdf8eeb99), UINT64_C (0x34b0bcb5e19b48a8), UINT64_C (0x391c0cb3c5c95a63), UINT64_C (0x4ed8aa4ae3418acb), UINT64_C (0x5b9cca4f7763e373), UINT64_C (0x682e6ff3d6b2b8a3), UINT64_C (0x748f82ee5defb2fc), UINT64_C (0x78a5636f43172f60), UINT64_C (0x84c87814a1f0ab72), UINT64_C (0x8cc702081a6439ec), UINT64_C (0x90befffa23631e28), UINT64_C (0xa4506cebde82bde9), UINT64_C (0xbef9a3f7b2c67915), UINT64_C (0xc67178f2e372532b), UINT64_C (0xca273eceea26619c), UINT64_C (0xd186b8c721c0c207), UINT64_C (0xeada7dd6cde0eb1e), UINT64_C (0xf57d4f7fee6ed178), UINT64_C (0x06f067aa72176fba), UINT64_C (0x0a637dc5a2c898a6), UINT64_C (0x113f9804bef90dae), UINT64_C (0x1b710b35131c471b), UINT64_C (0x28db77f523047d84), UINT64_C (0x32caab7b40c72493), UINT64_C (0x3c9ebe0a15c9bebc), UINT64_C (0x431d67c49c100d4c), UINT64_C (0x4cc5d4becb3e42b6), UINT64_C (0x597f299cfc657e2a), UINT64_C (0x5fcb6fab3ad6faec), UINT64_C (0x6c44198c4a475817)}; /* One step of SHA-512/256 computation with working variables rotation, see FIPS PUB 180-4 clause 6.4.2 step 3. * Note: this version of macro reassign all working variable on each step. */ #define SHA2STEP64RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ uint64_t tmp_h_ = (vH); \ SHA2STEP64((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt)); \ (vH) = (vG); \ (vG) = (vF); \ (vF) = (vE); \ (vE) = (vD); \ (vD) = (vC); \ (vC) = (vB); \ (vB) = (vA); \ (vA) = tmp_h_; } while (0) /* During first 16 steps, before making any calculations on each step, the W element is read from the input data buffer as big-endian value and stored in the array of W elements. */ for (t = 0; t < 16; ++t) { SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \ W[t] = GET_W_FROM_DATA (data, t)); } /* During last 64 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ for (t = 16; t < 80; ++t) { SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \ W[t & 15] = Wgen (W,t)); } } #endif /* MHD_FAVOR_SMALL_CODE */ /* Compute and store the intermediate hash. See FIPS PUB 180-4 clause 6.4.2 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA512_256_update (struct Sha512_256Ctx *ctx, const uint8_t *data, size_t length) { unsigned int bytes_have; /**< Number of bytes in the context buffer */ uint64_t count_hi; /**< The high part to be moved to another variable */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* ! MHD_FAVOR_SMALL_CODE */ /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); ctx->count += length; #if SIZEOF_SIZE_T > 7 if (length > ctx->count) ctx->count_bits_hi += 1U << 3; /* Value wrap */ #endif /* SIZEOF_SIZE_T > 7 */ count_hi = ctx->count >> 61; if (0 != count_hi) { ctx->count_bits_hi += count_hi; ctx->count &= UINT64_C (0x1FFFFFFFFFFFFFFF); } if (0 != bytes_have) { unsigned int bytes_left = SHA512_256_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process the full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha512_256_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA512_256_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha512_256_transform (ctx->H, data); data += SHA512_256_BLOCK_SIZE; length -= SHA512_256_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" insertion in bits. * See FIPS PUB 180-4 clause 5.1.2. */ #define SHA512_256_SIZE_OF_LEN_ADD_BITS 128 /** * Size of "length" insertion in bytes. */ #define SHA512_256_SIZE_OF_LEN_ADD (SHA512_256_SIZE_OF_LEN_ADD_BITS / 8) /** * Finalise SHA-512/256 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes */ void MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx, uint8_t digest[SHA512_256_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned int bytes_have; /**< Number of bytes in the context buffer */ /* Memorise the number of processed bits. The padding and other data added here during the postprocessing must not change the amount of hashed data. */ num_bits = ctx->count << 3; /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See FIPS PUB 180-4 clause 5.1.2. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of the first padding bit in byte is always predefined (0x80). */ /* Buffer always have space for one byte at least (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (SHA512_256_BLOCK_SIZE - bytes_have < SHA512_256_SIZE_OF_LEN_ADD) { /* No space in the current block to put the total length of message. Pad the current block with zeros and process it. */ if (bytes_have < SHA512_256_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA512_256_BLOCK_SIZE - bytes_have); /* Process the full block. */ sha512_256_transform (ctx->H, ctx->buffer); /* Start the new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD - bytes_have); /* Put high part of number of bits in processed message and then lower part of number of bits as big-endian values. See FIPS PUB 180-4 clause 5.1.2. */ /* Note: the target location is predefined and buffer is always aligned */ _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 2, ctx->count_bits_hi); _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 1, num_bits); /* Process the full final block. */ sha512_256_transform (ctx->H, ctx->buffer); /* Put in BE mode the leftmost part of the hash as the final digest. See FIPS PUB 180-4 clause 6.7. */ #ifndef _MHD_PUT_64BIT_BE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT64_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint64_t alig_dgst[SHA512_256_DIGEST_SIZE_WORDS]; _MHD_PUT_64BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_64BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_64BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_64BIT_BE (alig_dgst + 3, ctx->H[3]); /* Copy result to the unaligned destination address */ memcpy (digest, alig_dgst, SHA512_256_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_64BIT_BE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_64BIT_BE ((void *) (digest + 0 * SHA512_256_BYTES_IN_WORD), \ ctx->H[0]); _MHD_PUT_64BIT_BE ((void *) (digest + 1 * SHA512_256_BYTES_IN_WORD), \ ctx->H[1]); _MHD_PUT_64BIT_BE ((void *) (digest + 2 * SHA512_256_BYTES_IN_WORD), \ ctx->H[2]); _MHD_PUT_64BIT_BE ((void *) (digest + 3 * SHA512_256_BYTES_IN_WORD), \ ctx->H[3]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_64BIT_BE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Sha512_256Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.2/src/microhttpd/test_str_token.c0000644000175000017500000001122514760713574017475 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for some mhd_str functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include "mhd_str.h" static int expect_found_n (const char *str, const char *token, size_t token_len) { if (! MHD_str_has_token_caseless_ (str, token, token_len)) { fprintf (stderr, "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return false\n", str, token, (unsigned long) token_len); return 1; } return 0; } #define expect_found(s,t) expect_found_n ((s),(t),MHD_STATICSTR_LEN_ (t)) static int expect_not_found_n (const char *str, const char *token, size_t token_len) { if (MHD_str_has_token_caseless_ (str, token, token_len)) { fprintf (stderr, "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return true\n", str, token, (unsigned long) token_len); return 1; } return 0; } #define expect_not_found(s,t) expect_not_found_n ((s),(t),MHD_STATICSTR_LEN_ ( \ t)) static int check_match (void) { int errcount = 0; errcount += expect_found ("string", "string"); errcount += expect_found ("String", "string"); errcount += expect_found ("string", "String"); errcount += expect_found ("strinG", "String"); errcount += expect_found ("\t strinG", "String"); errcount += expect_found ("strinG\t ", "String"); errcount += expect_found (" \t tOkEn ", "toKEN"); errcount += expect_found ("not token\t, tOkEn ", "toKEN"); errcount += expect_found ("not token,\t tOkEn, more token", "toKEN"); errcount += expect_found ("not token,\t tOkEn\t, more token", "toKEN"); errcount += expect_found (",,,,,,test,,,,", "TESt"); errcount += expect_found (",,,,,\t,test,,,,", "TESt"); errcount += expect_found (",,,,,,test, ,,,", "TESt"); errcount += expect_found (",,,,,, test,,,,", "TESt"); errcount += expect_found (",,,,,, test not,test,,", "TESt"); errcount += expect_found (",,,,,, test not,,test,,", "TESt"); errcount += expect_found (",,,,,, test not ,test,,", "TESt"); errcount += expect_found (",,,,,, test", "TESt"); errcount += expect_found (",,,,,, test ", "TESt"); errcount += expect_found ("no test,,,,,, test ", "TESt"); return errcount; } static int check_not_match (void) { int errcount = 0; errcount += expect_not_found ("strin", "string"); errcount += expect_not_found ("Stringer", "string"); errcount += expect_not_found ("sstring", "String"); errcount += expect_not_found ("string", "Strin"); errcount += expect_not_found ("\t( strinG", "String"); errcount += expect_not_found (")strinG\t ", "String"); errcount += expect_not_found (" \t tOkEn t ", "toKEN"); errcount += expect_not_found ("not token\t, tOkEner ", "toKEN"); errcount += expect_not_found ("not token,\t tOkEns, more token", "toKEN"); errcount += expect_not_found ("not token,\t tOkEns\t, more token", "toKEN"); errcount += expect_not_found (",,,,,,testing,,,,", "TESt"); errcount += expect_not_found (",,,,,\t,test,,,,", "TESting"); errcount += expect_not_found ("tests,,,,,,quest, ,,,", "TESt"); errcount += expect_not_found (",,,,,, testÑ‹,,,,", "TESt"); errcount += expect_not_found (",,,,,, test not,Ñ…test,,", "TESt"); errcount += expect_not_found ("testing,,,,,, test not,,test2,,", "TESt"); errcount += expect_not_found (",testi,,,,, test not ,test,,", "TESting"); errcount += expect_not_found (",,,,,,2 test", "TESt"); errcount += expect_not_found (",,,,,,test test ", "test"); errcount += expect_not_found ("no test,,,,,, test test", "test"); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_match (); errcount += check_not_match (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/test_dauth_userhash.c0000644000175000017500000006050114760713574020475 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_dauth_userhash.c * @brief Tests for Digest Auth calculations of userhash * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "microhttpd.h" #include "test_helpers.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ static int verbose = 1; /* verbose level (0-1)*/ /* Declarations and data */ struct data_md5 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_MD5_DIGEST_SIZE]; }; static const struct data_md5 md5_tests[] = { {__LINE__, "u", "r", {0xba, 0x84, 0xbe, 0x20, 0x3f, 0xdf, 0xc7, 0xd3, 0x4e, 0x05, 0x4a, 0x76, 0xd2, 0x85, 0xd0, 0xc9}}, {__LINE__, "testuser", "testrealm", {0xab, 0xae, 0x15, 0x95, 0x24, 0xe5, 0x17, 0xbf, 0x48, 0xf4, 0x4a, 0xab, 0xfe, 0xb9, 0x37, 0x40}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, 0x18, 0xf6, 0x23, 0x72, 0x5f, 0xba, 0x42, 0x81}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0x26, 0x45, 0xae, 0x13, 0xd1, 0xa2, 0xa6, 0x9e, 0xd2, 0x6d, 0xd2, 0x1a, 0xa5, 0x52, 0x86, 0xe3}}, {__LINE__, "Mufasa", "myhost@example.com", {0x4f, 0xc8, 0x64, 0x02, 0xd7, 0x18, 0x5d, 0x7b, 0x38, 0xd4, 0x38, 0xad, 0xd5, 0x5a, 0x35, 0x84}}, {__LINE__, "Mufasa", "http-auth@example.org", {0x42, 0x38, 0xf3, 0xa1, 0x61, 0x67, 0x37, 0x3f, 0xeb, 0xb9, 0xbc, 0x4d, 0x43, 0xdb, 0x9c, 0xc4}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x2e, 0x06, 0x3f, 0xa2, 0xc5, 0x4d, 0xea, 0x1c, 0x36, 0x80, 0x8b, 0x7a, 0x6e, 0x3b, 0x14, 0xc9}} }; struct data_sha256 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_SHA256_DIGEST_SIZE]; }; static const struct data_sha256 sha256_tests[] = { {__LINE__, "u", "r", {0x1d, 0x8a, 0x03, 0xa6, 0xe2, 0x1a, 0x4c, 0xe7, 0x75, 0x06, 0x0e, 0xa5, 0x73, 0x60, 0x32, 0x9a, 0xc7, 0x50, 0xde, 0xa5, 0xd8, 0x47, 0x29, 0x7b, 0x42, 0xf0, 0xd4, 0x65, 0x39, 0xaf, 0x8a, 0xb2}}, {__LINE__, "testuser", "testrealm", {0x75, 0xaf, 0x8a, 0x35, 0x00, 0xf7, 0x71, 0xe5, 0x8a, 0x52, 0x09, 0x3a, 0x25, 0xe7, 0x90, 0x5d, 0x6e, 0x42, 0x8a, 0x51, 0x12, 0x85, 0xc1, 0x2e, 0xa1, 0x42, 0x0c, 0x73, 0x07, 0x8d, 0xfd, 0x61}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, 0xcf, 0x5f, 0xe6, 0xca, 0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, 0xa4, 0x5a, 0x0e, 0x35, 0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0x92, 0x9f, 0xac, 0x9e, 0x6c, 0x8b, 0x76, 0xcc, 0xab, 0xa9, 0xe0, 0x6f, 0xf6, 0x4d, 0xf2, 0x6f, 0xcb, 0x40, 0x56, 0x4c, 0x19, 0x9c, 0x32, 0xd9, 0xea, 0xd9, 0x12, 0x4b, 0x25, 0x34, 0xe1, 0xf9}}, {__LINE__, "Mufasa", "myhost@example.com", {0x97, 0x06, 0xf0, 0x07, 0x1c, 0xec, 0x05, 0x3f, 0x88, 0x22, 0xb6, 0x63, 0x69, 0xc4, 0xa4, 0x00, 0x39, 0x79, 0xb7, 0xe7, 0x42, 0xb7, 0x4e, 0x42, 0x59, 0x63, 0x57, 0xf4, 0xd3, 0x02, 0xae, 0x16}}, {__LINE__, "Mufasa", "http-auth@example.org", {0xa9, 0x47, 0xaa, 0xd2, 0x05, 0xe8, 0x0e, 0x42, 0x99, 0x58, 0xa3, 0x87, 0x39, 0x49, 0x44, 0xc6, 0xb4, 0x96, 0x30, 0x1e, 0x79, 0xf8, 0x9d, 0x35, 0xa4, 0xcc, 0x23, 0xb6, 0xee, 0x12, 0xb5, 0xb6}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x5a, 0x1a, 0x8a, 0x47, 0xdf, 0x5c, 0x29, 0x85, 0x51, 0xb9, 0xb4, 0x2b, 0xa9, 0xb0, 0x58, 0x35, 0x17, 0x4a, 0x5b, 0xd7, 0xd5, 0x11, 0xff, 0x7f, 0xe9, 0x19, 0x1d, 0x8e, 0x94, 0x6f, 0xc4, 0xe7}} }; struct data_sha512_256 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE]; }; static const struct data_sha512_256 sha512_256_tests[] = { {__LINE__, "u", "r", {0xc7, 0x38, 0xf2, 0xad, 0x40, 0x1b, 0xc8, 0x7a, 0x71, 0xfe, 0x78, 0x09, 0x60, 0x15, 0xc9, 0x7b, 0x9a, 0x26, 0xd5, 0x5f, 0x15, 0xe9, 0xf5, 0x0a, 0xc3, 0xa6, 0xde, 0x73, 0xdd, 0xcd, 0x3d, 0x08}}, {__LINE__, "testuser", "testrealm", {0x4f, 0x69, 0x1e, 0xe9, 0x50, 0x8a, 0xe4, 0x55, 0x21, 0x32, 0x9e, 0xcf, 0xd4, 0x91, 0xf7, 0xe2, 0x77, 0x4b, 0x6f, 0xb8, 0x60, 0x2c, 0x14, 0x86, 0xad, 0x94, 0x9d, 0x1c, 0x23, 0xd8, 0xa1, 0xf5}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0x62, 0xe1, 0xac, 0x9f, 0x6c, 0xb1, 0xeb, 0x26, 0xaa, 0x75, 0xeb, 0x5d, 0x46, 0xef, 0xcd, 0xc8, 0x9c, 0xcb, 0xa7, 0x81, 0xf0, 0xf9, 0xf7, 0x2f, 0x6a, 0xfd, 0xb9, 0x42, 0x65, 0xd9, 0xa7, 0x9a}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0xbd, 0x3e, 0xbc, 0x30, 0x10, 0x0b, 0x7c, 0xf1, 0x61, 0x45, 0x6c, 0xfe, 0x64, 0x1c, 0x4c, 0xd2, 0x82, 0xe0, 0x62, 0x6e, 0x2c, 0x5e, 0x09, 0xc2, 0x4c, 0x90, 0xb1, 0x60, 0x8a, 0xec, 0x28, 0x64}}, {__LINE__, "Mufasa", "myhost@example.com", {0xea, 0x4b, 0x59, 0x37, 0xde, 0x2c, 0x4e, 0x9f, 0x16, 0xf9, 0x9c, 0x31, 0x01, 0xb6, 0xdd, 0xf8, 0x8c, 0x85, 0xd7, 0xe8, 0xf1, 0x75, 0x90, 0xd0, 0x63, 0x2a, 0x75, 0x75, 0xe4, 0x80, 0x13, 0x69}}, {__LINE__, "Mufasa", "http-auth@example.org", {0xe2, 0xdf, 0xab, 0xd1, 0xa9, 0x6d, 0xdf, 0x86, 0x77, 0x10, 0xb6, 0x53, 0xb6, 0xe6, 0x85, 0x7d, 0x1f, 0x14, 0x70, 0x86, 0xde, 0x7d, 0x7e, 0xf7, 0x9d, 0xcd, 0x24, 0x98, 0x59, 0x87, 0x25, 0x70}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x79, 0x32, 0x63, 0xca, 0xab, 0xb7, 0x07, 0xa5, 0x62, 0x11, 0x94, 0x0d, 0x90, 0x41, 0x1e, 0xa4, 0xa5, 0x75, 0xad, 0xec, 0xcb, 0x7e, 0x36, 0x0a, 0xeb, 0x62, 0x4e, 0xd0, 0x6e, 0xce, 0x9b, 0x0b}} }; /* * Helper functions */ /** * Print bin as lower case hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0')); } *hex = 0; } /* Tests */ static unsigned int check_md5 (const struct data_md5 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_md5 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++) num_failed += check_md5 (md5_tests + i); return num_failed; } static unsigned int test_md5_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha256 (const struct data_sha256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++) num_failed += check_sha256 (sha256_tests + i); return num_failed; } static unsigned int test_sha256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha512_256 (const struct data_sha512_256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha512_256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++) num_failed += check_sha512_256 (sha512_256_tests + i); return num_failed; } static unsigned int test_sha512_256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } int main (int argc, char *argv[]) { unsigned int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")) verbose = 0; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) num_failed += test_md5 (); num_failed += test_md5_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) num_failed += test_sha256 (); num_failed += test_sha256_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256)) num_failed += test_sha512_256 (); num_failed += test_sha512_256_failure (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/digestauth.h0000644000175000017500000000437215035214301016555 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digestauth.c * @brief Implements HTTP digest authentication * @author Amr Ali * @author Matthieu Speder * @author Christian Grothoff (RFC 7616 support) * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_DIGESTAUTH_H #define MHD_DIGESTAUTH_H 1 #include "mhd_options.h" #include "mhd_str.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ /** * The maximum supported size for Digest Auth parameters, like "real", * "username" etc. This limitation is used only for quoted parameters. * Parameters without quoted backslash character will be processed as long * as they fit connection pool (buffer) size. */ #define _MHD_AUTH_DIGEST_MAX_PARAM_SIZE (65535) /** * Beginning string for any valid Digest Authentication header. */ #define _MHD_AUTH_DIGEST_BASE "Digest" /** * The token for MD5 algorithm. */ #define _MHD_MD5_TOKEN "MD5" /** * The token for SHA-256 algorithm. */ #define _MHD_SHA256_TOKEN "SHA-256" /** * The token for SHA-512/256 algorithm. */ #define _MHD_SHA512_256_TOKEN "SHA-512-256" /** * The suffix token for "session" algorithms. */ #define _MHD_SESS_TOKEN "-sess" /** * The "auth" token for QOP */ #define MHD_TOKEN_AUTH_ "auth" /** * The "auth-int" token for QOP */ #define MHD_TOKEN_AUTH_INT_ "auth-int" #endif /* ! MHD_DIGESTAUTH_H */ /* end of digestauth.h */ libmicrohttpd-1.0.2/src/microhttpd/mhd_panic.h0000644000175000017500000000465714760713577016373 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_panic.h * @brief Declaration and macros for MHD_panic() * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_PANIC_H #define MHD_PANIC_H 1 #include "mhd_options.h" #ifdef MHD_PANIC /* Override any possible defined MHD_PANIC macro with proper one */ #undef MHD_PANIC #endif /* MHD_PANIC */ /* If we have Clang or gcc >= 4.5, use __builtin_unreachable() */ #if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 4) || \ (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 5) #define BUILTIN_NOT_REACHED __builtin_unreachable () #elif defined(_MSC_FULL_VER) #define BUILTIN_NOT_REACHED __assume (0) #else #define BUILTIN_NOT_REACHED #endif /* The MHD_PanicCallback type, but without main header. */ /** * Handler for fatal errors. */ extern void (*mhd_panic) (void *cls, const char *file, unsigned int line, const char *reason); /** * Closure argument for "mhd_panic". */ extern void *mhd_panic_cls; #ifdef HAVE_MESSAGES /** * Trigger 'panic' action based on fatal errors. * * @param msg error message (const char *) */ #define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, msg); \ BUILTIN_NOT_REACHED; } while (0) #else /** * Trigger 'panic' action based on fatal errors. * * @param msg error message (const char *) */ #define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, NULL, __LINE__, NULL); \ BUILTIN_NOT_REACHED; } while (0) #endif #endif /* MHD_PANIC_H */ libmicrohttpd-1.0.2/src/microhttpd/mhd_compat.h0000644000175000017500000000545514760713577016561 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_compat.h * @brief Header for platform missing functions. * @author Karlson2k (Evgeny Grin) * * Provides compatibility for platforms with some missing * functionality. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_COMPAT_H #define MHD_COMPAT_H 1 #include "mhd_options.h" #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #ifdef HAVE_STRING_H /* for strerror() */ #include #endif /* HAVE_STRING_H */ /* MHD_strerror_ is strerror */ #define MHD_strerror_(errnum) strerror ((errnum)) /* Platform-independent snprintf name */ #if defined(HAVE_SNPRINTF) #define MHD_snprintf_ snprintf #else /* ! HAVE_SNPRINTF */ #if defined(_WIN32) && ! defined(__CYGWIN__) /* Emulate snprintf function on W32 */ int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format, ...); #define MHD_snprintf_ W32_snprintf #else /* ! _WIN32 || __CYGWIN__ */ #error \ Your platform does not support snprintf() and MHD does not know how to emulate it on your platform. #endif /* ! _WIN32 || __CYGWIN__ */ #endif /* ! HAVE_SNPRINTF */ #ifdef HAVE_RANDOM /** * Generate pseudo random number at least 30-bit wide. * @return pseudo random number at least 30-bit wide. */ #define MHD_random_() random () #else /* HAVE_RANDOM */ #ifdef HAVE_RAND /** * Generate pseudo random number at least 30-bit wide. * @return pseudo random number at least 30-bit wide. */ #define MHD_random_() ( (((long) rand ()) << 15) + (long) rand () ) #endif /* HAVE_RAND */ #endif /* HAVE_RANDOM */ #ifdef HAVE_CALLOC /** * MHD_calloc_ is platform-independent calloc() */ #define MHD_calloc_(n,s) calloc ((n),(s)) #else /* ! HAVE_CALLOC */ /** * MHD_calloc_ is platform-independent calloc() */ void *MHD_calloc_ (size_t nelem, size_t elsize); #endif /* ! HAVE_CALLOC */ #endif /* MHD_COMPAT_H */ libmicrohttpd-1.0.2/src/microhttpd/test_sha512_256.c0000644000175000017500000007264414760713574017100 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha512_256.h * @brief Unit tests for SHA-512/256 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "sha512_256.h" #include "test_helpers.h" #include #include static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA512_256_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0x53, 0x04, 0x8E, 0x26, 0x81, 0x94, 0x1E, 0xF9, 0x9B, 0x2E, 0x29, 0xB7, 0x6B, 0x4C, 0x7D, 0xAB, 0xE4, 0xC2, 0xD0, 0xC6, 0x34, 0xFC, 0x6D, 0x46, 0xE0, 0xE2, 0xF1, 0x31, 0x07, 0xE7, 0xAF, 0x23}}, {D_STR_W_LEN ("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhi" \ "jklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), {0x39, 0x28, 0xE1, 0x84, 0xFB, 0x86, 0x90, 0xF8, 0x40, 0xDA, 0x39, 0x88, 0x12, 0x1D, 0x31, 0xBE, 0x65, 0xCB, 0x9D, 0x3E, 0xF8, 0x3E, 0xE6, 0x14, 0x6F, 0xEA, 0xC8, 0x61, 0xE1, 0x9B, 0x56, 0x3A}}, {D_STR_W_LEN (""), /* The empty zero-size input */ {0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28, 0xab, 0x87, 0xc3, 0x62, 0x2c, 0x51, 0x14, 0x06, 0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, 0x73, 0x74, 0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0xc8, 0x7c, 0x5a, 0x55, 0x27, 0x77, 0x1b, 0xe7, 0x69, 0x3c, 0x50, 0x79, 0x32, 0xad, 0x7c, 0x79, 0xe9, 0x60, 0xa0, 0x18, 0xb7, 0x78, 0x2b, 0x6f, 0xa9, 0x7b, 0xa3, 0xa0, 0xb5, 0x18, 0x17, 0xa5}}, {D_STR_W_LEN ("Simple string."), {0xde, 0xcb, 0x3c, 0x81, 0x65, 0x4b, 0xa0, 0xf5, 0xf0, 0x45, 0x6b, 0x7e, 0x61, 0xf5, 0x0d, 0xf5, 0x38, 0xa4, 0xfc, 0xb1, 0x8a, 0x95, 0xff, 0x59, 0xbc, 0x04, 0x82, 0xcf, 0x23, 0xb2, 0x32, 0x56}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08, 0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82, 0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26, }}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0xd2, 0x6d, 0x24, 0x81, 0xa4, 0xf9, 0x0a, 0x72, 0xd2, 0x7f, 0xc1, 0xac, 0xac, 0xe1, 0xc0, 0x6b, 0x39, 0x94, 0xac, 0x73, 0x50, 0x2e, 0x27, 0x97, 0xa3, 0x65, 0x37, 0x4e, 0xbb, 0x5c, 0x27, 0xe9}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xad, 0xe9, 0x5d, 0x55, 0x3b, 0x9e, 0x45, 0x69, 0xdb, 0x53, 0xa4, 0x04, 0x92, 0xe7, 0x87, 0x94, 0xff, 0xc9, 0x98, 0x5f, 0x93, 0x03, 0x86, 0x45, 0xe1, 0x97, 0x17, 0x72, 0x7c, 0xbc, 0x31, 0x15}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0xbc, 0xab, 0xc6, 0x2c, 0x0a, 0x22, 0xd5, 0xcb, 0xac, 0xac, 0xe9, 0x25, 0xcf, 0xce, 0xaa, 0xaf, 0x0e, 0xa1, 0xed, 0x42, 0x46, 0x8a, 0xe2, 0x01, 0xee, 0x2f, 0xdb, 0x39, 0x75, 0x47, 0x73, 0xf1}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA512_256_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08, 0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82, 0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 }, /* 'A' x 72 times */ {0x36, 0x5d, 0x41, 0x0e, 0x55, 0xd1, 0xfd, 0xe6, 0xc3, 0xb8, 0x68, 0xcc, 0xed, 0xeb, 0xcd, 0x0d, 0x2e, 0x34, 0xb2, 0x5c, 0xdf, 0xe7, 0x79, 0xe2, 0xe9, 0x65, 0x07, 0x33, 0x78, 0x0d, 0x01, 0x89}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0xb9, 0xe5, 0x74, 0x11, 0xbf, 0xa2, 0x0e, 0x98, 0xbe, 0x08, 0x69, 0x2e, 0x17, 0x9e, 0xc3, 0xfe, 0x61, 0xe3, 0x7a, 0x80, 0x2e, 0x25, 0x8c, 0xf3, 0x76, 0xda, 0x9f, 0x5f, 0xcd, 0x87, 0x48, 0x0d}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x80, 0x15, 0x83, 0xed, 0x7d, 0xef, 0x9f, 0xdf, 0xfb, 0x83, 0x1f, 0xc5, 0x8b, 0x50, 0x37, 0x81, 0x00, 0xc3, 0x4f, 0xfd, 0xfe, 0xc2, 0x9b, 0xaf, 0xfe, 0x15, 0x66, 0xe5, 0x08, 0x42, 0x5e, 0xae}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x76, 0x2f, 0x27, 0x4d, 0xfa, 0xd5, 0xa9, 0x21, 0x4e, 0xe9, 0x56, 0x22, 0x54, 0x38, 0x71, 0x3e, 0xef, 0x14, 0xa9, 0x22, 0x37, 0xf3, 0xb0, 0x50, 0x3d, 0x95, 0x40, 0xb7, 0x08, 0x64, 0xa9, 0xfd}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72}, /* 1..72 sequence */ {0x3f, 0x5c, 0xd3, 0xec, 0x40, 0xc4, 0xb9, 0x78, 0x35, 0x57, 0xc6, 0x4f, 0x3e, 0x46, 0x82, 0xdc, 0xd4, 0x46, 0x11, 0xd0, 0xb3, 0x0a, 0xbb, 0x89, 0xf1, 0x1d, 0x34, 0xb5, 0xf9, 0xd5, 0x10, 0x35}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x08, 0x37, 0xa1, 0x1d, 0x99, 0x4d, 0x5a, 0xa8, 0x60, 0xd0, 0x69, 0x17, 0xa8, 0xa0, 0xf6, 0x3e, 0x31, 0x11, 0xb9, 0x56, 0x33, 0xde, 0xeb, 0x15, 0xee, 0xd9, 0x94, 0x93, 0x76, 0xf3, 0x7d, 0x36, }}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0xcf, 0x21, 0x4b, 0xb2, 0xdd, 0x40, 0x98, 0xdf, 0x3a, 0xb7, 0x21, 0xb4, 0x69, 0x0e, 0x19, 0x36, 0x24, 0xa9, 0xbe, 0x30, 0xf7, 0xd0, 0x75, 0xb0, 0x39, 0x94, 0x82, 0xda, 0x55, 0x97, 0xe4, 0x79}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x22, 0x31, 0xf2, 0xa1, 0xb4, 0x89, 0xb2, 0x44, 0xf7, 0x66, 0xa0, 0xb8, 0x31, 0xed, 0xb7, 0x73, 0x8a, 0x34, 0xdc, 0x11, 0xc8, 0x2c, 0xf2, 0xb5, 0x88, 0x60, 0x39, 0x6b, 0x5c, 0x06, 0x70, 0x37}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0xb8, 0xdb, 0x2c, 0x2e, 0xf3, 0x12, 0x77, 0x14, 0xf9, 0x34, 0x2d, 0xfa, 0xda, 0x42, 0xbe, 0xfe, 0x67, 0x3a, 0x8a, 0xf6, 0x71, 0x36, 0x00, 0xff, 0x77, 0xa5, 0x83, 0x14, 0x55, 0x2a, 0x05, 0xaf}}, { { {66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66}, 110}, /* 'B' x 110 times */ {0xc8, 0x9e, 0x0d, 0x8f, 0x7b, 0x35, 0xfd, 0x3e, 0xdc, 0x90, 0x87, 0x64, 0x45, 0x94, 0x94, 0x21, 0xb3, 0x8e, 0xb5, 0xc7, 0x54, 0xc8, 0xee, 0xde, 0xfc, 0x77, 0xd6, 0xe3, 0x9f, 0x81, 0x8e, 0x78}}, { { {67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67}, 111}, /* 'C' x 111 times */ {0x86, 0xca, 0x6d, 0x2a, 0x72, 0xe2, 0x8c, 0x17, 0x89, 0x86, 0x89, 0x1b, 0x36, 0xf9, 0x6d, 0xda, 0x8c, 0xd6, 0x30, 0xb2, 0xd3, 0x60, 0x39, 0xfb, 0xc9, 0x04, 0xc5, 0x11, 0xcd, 0x2d, 0xe3, 0x62}}, { { {68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68}, 112}, /* 'D' x 112 times */ {0xdf, 0x9d, 0x4a, 0xcf, 0x81, 0x0d, 0x3a, 0xd4, 0x8e, 0xa4, 0x65, 0x9e, 0x1e, 0x15, 0xe4, 0x15, 0x1b, 0x37, 0xb6, 0xeb, 0x17, 0xab, 0xf6, 0xb1, 0xbc, 0x30, 0x46, 0x34, 0x24, 0x56, 0x1c, 0x06}}, { { {69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69}, 113}, /* 'E' x 113 times */ {0xa5, 0xf1, 0x47, 0x74, 0xf8, 0x2b, 0xed, 0x23, 0xe4, 0x10, 0x59, 0x8f, 0x7e, 0xb1, 0x30, 0xe5, 0x7e, 0xd1, 0x4b, 0xbc, 0x72, 0x58, 0x58, 0x81, 0xbb, 0xa0, 0xa5, 0xb6, 0x15, 0x39, 0x49, 0xa1}}, { { {70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70}, 114}, /* 'F' x 114 times */ {0xe6, 0xa3, 0xc9, 0x63, 0xd5, 0x28, 0x6e, 0x2d, 0xfb, 0x71, 0xdf, 0xd4, 0xff, 0xc2, 0xd4, 0x2b, 0x5d, 0x9b, 0x76, 0x28, 0xd2, 0xcb, 0x15, 0xc8, 0x81, 0x57, 0x14, 0x09, 0xc3, 0x8e, 0x92, 0xce}}, { { {76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76}, 127}, /* 'L' x 127 times */ {0x5d, 0x18, 0xff, 0xd7, 0xbe, 0x23, 0xb2, 0xb2, 0xbd, 0xe3, 0x13, 0x12, 0x1c, 0x16, 0x89, 0x14, 0x4a, 0x42, 0xb4, 0x3f, 0xab, 0xc8, 0x41, 0x14, 0x62, 0x00, 0xb5, 0x53, 0xa7, 0xd6, 0xd5, 0x35}}, { { {77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77}, 128}, /* 'M' x 128 times */ {0x6e, 0xf0, 0xda, 0x81, 0x3d, 0x50, 0x1d, 0x31, 0xf1, 0x4a, 0xf8, 0xd9, 0x7d, 0xd2, 0x13, 0xdd, 0xa4, 0x46, 0x15, 0x0b, 0xb8, 0x5a, 0x8a, 0xc6, 0x1e, 0x3a, 0x1f, 0x21, 0x35, 0xa2, 0xbb, 0x4f}}, { { {78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78}, 129}, /* 'N' x 129 times */ {0xee, 0xce, 0xd5, 0x34, 0xab, 0x14, 0x13, 0x9e, 0x8f, 0x5c, 0xb4, 0xef, 0xac, 0xaf, 0xc5, 0xeb, 0x1d, 0x2f, 0xe3, 0xc5, 0xca, 0x09, 0x29, 0x96, 0xfa, 0x84, 0xff, 0x12, 0x26, 0x6a, 0x50, 0x49}}, { { {97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97}, 238}, /* 'a' x 238 times */ {0xb4, 0x24, 0xe5, 0x7b, 0xa7, 0x37, 0xe3, 0xc4, 0xac, 0x35, 0x21, 0x17, 0x98, 0xec, 0xb9, 0xae, 0x45, 0x13, 0x24, 0xa4, 0x2c, 0x76, 0xae, 0x7d, 0x17, 0x75, 0x27, 0x8a, 0xaa, 0x4a, 0x48, 0x60}}, { { {98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98}, 239}, /* 'b' x 239 times */ {0xcd, 0x93, 0xb8, 0xab, 0x6a, 0x74, 0xbd, 0x34, 0x8c, 0x43, 0x76, 0x0c, 0x2a, 0xd0, 0x6e, 0xd8, 0x76, 0xcf, 0xdf, 0x2a, 0x21, 0x04, 0xfb, 0xf6, 0x16, 0x53, 0x68, 0xf6, 0x10, 0xc3, 0xa1, 0xac}}, { { {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}, 240}, /* 'c' x 240 times */ {0x5f, 0x60, 0xea, 0x44, 0xb6, 0xc6, 0x9e, 0xfe, 0xfc, 0x0e, 0x6a, 0x0a, 0x99, 0x40, 0x1b, 0x61, 0x43, 0x58, 0xba, 0x4a, 0x0a, 0xee, 0x6b, 0x52, 0x10, 0xdb, 0x32, 0xd9, 0x7f, 0x12, 0xba, 0x70}}, { { {48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48}, 241}, /* '0' x 241 times */ {0x3c, 0xcb, 0xcf, 0x50, 0x79, 0xd5, 0xb6, 0xf5, 0xbf, 0x25, 0x07, 0xfb, 0x4d, 0x1f, 0xa3, 0x77, 0xc3, 0x6f, 0xe8, 0xe3, 0xc4, 0x4b, 0xf8, 0xcd, 0x90, 0x93, 0xf1, 0x3e, 0x08, 0x09, 0xa7, 0x69}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA512_256_DIGEST_SIZE], const uint8_t expected[SHA512_256_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA512_256_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; char expc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str); bin2hex (expected, SHA512_256_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s matches " \ "expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-512/256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units1_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units1[i].digest); } return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units2_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units2[i].digest); } return num_failed; } /* Calculated SHA-512/256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units1_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units1[i].digest); } return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units2_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units2[i].digest); } return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 63 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Sha512_256Ctx ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA512_256_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA512_256_DIGEST_SIZE); MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA512_256_finish (&ctx, unaligned_digest); num_failed += check_result (__FUNCTION__, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/test_response_entries.c0000644000175000017500000006354614760713574021071 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021 Karlson2k (Evgeny Grin) This test_response_entries.c file is in the public domain */ /** * @file test_response_entries.c * @brief Test adding and removing response headers * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include static int expect_str (const char *actual, const char *expected) { if (expected == actual) return ! 0; if (NULL == actual) { fprintf (stderr, "FAILED: result: NULL\n" \ " expected: \"%s\"\n", expected); return 0; } if (NULL == expected) { fprintf (stderr, "FAILED: result: \"%s\"\n" \ " expected: NULL\n", actual); return 0; } if (0 != strcmp (actual, expected)) { fprintf (stderr, "FAILED: result: \"%s\"\n" \ " expected: \"%s\"\n", actual, expected); return 0; } return ! 0; } int main (int argc, char *const *argv) { struct MHD_Response *r; (void) argc; (void) argv; /* Unused. Silence compiler warning. */ r = MHD_create_response_empty (MHD_RF_NONE); if (NULL == r) { fprintf (stderr, "Cannot create a response.\n"); return 1; } /* ** Test basic header functions ** */ /* Add first header */ if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a1")) { fprintf (stderr, "Cannot add header A1.\n"); MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1")) { MHD_destroy_response (r); return 2; } /* Add second header with the same name */ if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a2")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } /* Value of the first header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1")) { MHD_destroy_response (r); return 2; } /* Remove the first header */ if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a1")) { fprintf (stderr, "Cannot remove header A1.\n"); MHD_destroy_response (r); return 2; } /* Value of the ex-second header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a3")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } /* Value of the ex-second header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } /* Remove the last header */ if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a3")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-B"), NULL)) { MHD_destroy_response (r); return 2; } if (MHD_NO != MHD_del_response_header (r, "Header-Type-C", "value-a3")) { fprintf (stderr, "Removed non-existing header.\n"); MHD_destroy_response (r); return 2; } if (MHD_NO != MHD_del_response_header (r, "Header-Type-A", "value-c")) { fprintf (stderr, "Removed non-existing header value.\n"); MHD_destroy_response (r); return 2; } /* ** Test "Connection:" header ** */ if (MHD_YES != MHD_add_response_header (r, "Connection", "a,b,c,d,e")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "a, b, c, d, e")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "e,b,c,d,a")) { fprintf (stderr, "Cannot remove \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "i,k,l,m,n,o,p,close")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, i, k, l, m, n, o, p")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "i,k,l,m,n,o,p,close")) { fprintf (stderr, "Cannot remove \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "1,2,3,4,5,6,7,close")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 1, 2, 3, 4, 5, 6, 7")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "8,9,close")) { fprintf (stderr, "Cannot add second \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 1, 2, 3, 4, 5, 6, 7, 8, 9")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "1,3,5,7,9")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6, 8")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "10,12")) { fprintf (stderr, "Cannot add third \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6, 8, 10, 12")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "12 ,10 ,8 ,close")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "2, 4, 6")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "4 ,5,6,7 8,")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, 10, 12, 22, nothing")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with \"close\" and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "2")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close,other-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, other-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, new-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, other-token, new-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, new-token")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "other-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "other-token")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, one-long-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, one-long-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, one-long-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "one-long-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, additional-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "additional-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "token-1,token-2")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "token-3")) { fprintf (stderr, "Cannot add \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-4")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3, token-4")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-5")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4, token-5")) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_del_response_header (r, "Connection", "non-existing, token-9")) { fprintf (stderr, "Non-existing tokens successfully removed from \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4, token-5")) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", ",,,,,,,,,,,, ,\t\t\t, , , ")) { fprintf (stderr, "Empty token was added successfully to \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, token-1, token-2, token-3, token-4, token-5")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", ",,,,,,,,,,,, ,\t\t\t, , , ")) { fprintf (stderr, "Empty token was added successfully to \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 4; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, additional-token")) { fprintf (stderr, "Cannot add \"Connection\" header with " "\"close, additional-token\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 4; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "additional-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-1")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-1\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-2")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-2\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-3, close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, token-1, Keep-Alive, token-2, token-3")) { fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Date", "Wed, 01 Apr 2015 00:00:00 GMT")) { fprintf (stderr, "Cannot add \"Date\" header with \"Wed, 01 Apr 2015 00:00:00 GMT\".\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), "Wed, 01 Apr 2015 00:00:00 GMT")) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_add_response_header (r, "Date", "Thu, 01 Apr 2021 00:00:00 GMT")) { fprintf (stderr, "Cannot add \"Date\" header with \"Thu, 01 Apr 2021 00:00:00 GMT\".\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), "Thu, 01 Apr 2021 00:00:00 GMT")) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_del_response_header (r, "Date", "Thu, 01 Apr 2021 00:00:00 GMT")) { fprintf (stderr, "Cannot remove \"Date\" header.\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), NULL)) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header with \"chunked\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" second header with \"chunked\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_NO != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "identity")) { fprintf (stderr, "Successfully added \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header with \"identity\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_YES != MHD_del_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot remove \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header.\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), NULL)) { MHD_destroy_response (r); return 6; } MHD_destroy_response (r); printf ("All tests has been successfully passed.\n"); return 0; } libmicrohttpd-1.0.2/src/microhttpd/mhd_str.c0000644000175000017500000020035015035214301016041 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2024 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str.c * @brief Functions implementations for string manipulating * @author Karlson2k (Evgeny Grin) */ #include "mhd_str.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include #include "mhd_assert.h" #include "mhd_limits.h" #include "mhd_assert.h" #ifdef MHD_FAVOR_SMALL_CODE #ifdef _MHD_static_inline #undef _MHD_static_inline #endif /* _MHD_static_inline */ /* Do not force inlining and do not use macro functions, use normal static functions instead. This may give more flexibility for size optimizations. */ #define _MHD_static_inline static #ifndef HAVE_INLINE_FUNCS #define HAVE_INLINE_FUNCS 1 #endif /* !INLINE_FUNC */ #endif /* MHD_FAVOR_SMALL_CODE */ /* * Block of functions/macros that use US-ASCII charset as required by HTTP * standards. Not affected by current locale settings. */ #ifdef HAVE_INLINE_FUNCS #if 0 /* Disable unused functions. */ /** * Check whether character is lower case letter in US-ASCII * * @param c character to check * @return non-zero if character is lower case letter, zero otherwise */ _MHD_static_inline bool isasciilower (char c) { return (c >= 'a') && (c <= 'z'); } #endif /* Disable unused functions. */ /** * Check whether character is upper case letter in US-ASCII * * @param c character to check * @return non-zero if character is upper case letter, zero otherwise */ _MHD_static_inline bool isasciiupper (char c) { return (c >= 'A') && (c <= 'Z'); } #if 0 /* Disable unused functions. */ /** * Check whether character is letter in US-ASCII * * @param c character to check * @return non-zero if character is letter in US-ASCII, zero otherwise */ _MHD_static_inline bool isasciialpha (char c) { return isasciilower (c) || isasciiupper (c); } #endif /* Disable unused functions. */ /** * Check whether character is decimal digit in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit, zero otherwise */ _MHD_static_inline bool isasciidigit (char c) { return (c >= '0') && (c <= '9'); } #if 0 /* Disable unused functions. */ /** * Check whether character is hexadecimal digit in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit, zero otherwise */ _MHD_static_inline bool isasciixdigit (char c) { return isasciidigit (c) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') ); } /** * Check whether character is decimal digit or letter in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit or letter, zero otherwise */ _MHD_static_inline bool isasciialnum (char c) { return isasciialpha (c) || isasciidigit (c); } #endif /* Disable unused functions. */ #if 0 /* Disable unused functions. */ /** * Convert US-ASCII character to lower case. * If character is upper case letter in US-ASCII than it's converted to lower * case analog. If character is NOT upper case letter than it's returned * unmodified. * * @param c character to convert * @return converted to lower case character */ _MHD_static_inline char toasciilower (char c) { return isasciiupper (c) ? (c - 'A' + 'a') : c; } /** * Convert US-ASCII character to upper case. * If character is lower case letter in US-ASCII than it's converted to upper * case analog. If character is NOT lower case letter than it's returned * unmodified. * * @param c character to convert * @return converted to upper case character */ _MHD_static_inline char toasciiupper (char c) { return isasciilower (c) ? (c - 'a' + 'A') : c; } #endif /* Disable unused functions. */ #if defined(MHD_FAVOR_SMALL_CODE) /* Used only in MHD_str_to_uvalue_n_() */ /** * Convert US-ASCII decimal digit to its value. * * @param c character to convert * @return value of decimal digit or -1 if @ c is not decimal digit */ _MHD_static_inline int todigitvalue (char c) { if (isasciidigit (c)) return (unsigned char) (c - '0'); return -1; } #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert US-ASCII hexadecimal digit to its value. * * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ _MHD_static_inline int toxdigitvalue (char c) { #if ! defined(MHD_FAVOR_SMALL_CODE) switch ((unsigned char) c) { #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x00U: /* NUL */ case 0x01U: /* SOH */ case 0x02U: /* STX */ case 0x03U: /* ETX */ case 0x04U: /* EOT */ case 0x05U: /* ENQ */ case 0x06U: /* ACK */ case 0x07U: /* BEL */ case 0x08U: /* BS */ case 0x09U: /* HT */ case 0x0AU: /* LF */ case 0x0BU: /* VT */ case 0x0CU: /* FF */ case 0x0DU: /* CR */ case 0x0EU: /* SO */ case 0x0FU: /* SI */ case 0x10U: /* DLE */ case 0x11U: /* DC1 */ case 0x12U: /* DC2 */ case 0x13U: /* DC3 */ case 0x14U: /* DC4 */ case 0x15U: /* NAK */ case 0x16U: /* SYN */ case 0x17U: /* ETB */ case 0x18U: /* CAN */ case 0x19U: /* EM */ case 0x1AU: /* SUB */ case 0x1BU: /* ESC */ case 0x1CU: /* FS */ case 0x1DU: /* GS */ case 0x1EU: /* RS */ case 0x1FU: /* US */ case 0x20U: /* ' ' */ case 0x21U: /* '!' */ case 0x22U: /* '"' */ case 0x23U: /* '#' */ case 0x24U: /* '$' */ case 0x25U: /* '%' */ case 0x26U: /* '&' */ case 0x27U: /* '\'' */ case 0x28U: /* '(' */ case 0x29U: /* ')' */ case 0x2AU: /* '*' */ case 0x2BU: /* '+' */ case 0x2CU: /* ',' */ case 0x2DU: /* '-' */ case 0x2EU: /* '.' */ case 0x2FU: /* '/' */ return -1; #endif case 0x30U: /* '0' */ return 0; case 0x31U: /* '1' */ return 1; case 0x32U: /* '2' */ return 2; case 0x33U: /* '3' */ return 3; case 0x34U: /* '4' */ return 4; case 0x35U: /* '5' */ return 5; case 0x36U: /* '6' */ return 6; case 0x37U: /* '7' */ return 7; case 0x38U: /* '8' */ return 8; case 0x39U: /* '9' */ return 9; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x3AU: /* ':' */ case 0x3BU: /* ';' */ case 0x3CU: /* '<' */ case 0x3DU: /* '=' */ case 0x3EU: /* '>' */ case 0x3FU: /* '?' */ case 0x40U: /* '@' */ return -1; #endif case 0x41U: /* 'A' */ return 0xAU; case 0x42U: /* 'B' */ return 0xBU; case 0x43U: /* 'C' */ return 0xCU; case 0x44U: /* 'D' */ return 0xDU; case 0x45U: /* 'E' */ return 0xEU; case 0x46U: /* 'F' */ return 0xFU; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x47U: /* 'G' */ case 0x48U: /* 'H' */ case 0x49U: /* 'I' */ case 0x4AU: /* 'J' */ case 0x4BU: /* 'K' */ case 0x4CU: /* 'L' */ case 0x4DU: /* 'M' */ case 0x4EU: /* 'N' */ case 0x4FU: /* 'O' */ case 0x50U: /* 'P' */ case 0x51U: /* 'Q' */ case 0x52U: /* 'R' */ case 0x53U: /* 'S' */ case 0x54U: /* 'T' */ case 0x55U: /* 'U' */ case 0x56U: /* 'V' */ case 0x57U: /* 'W' */ case 0x58U: /* 'X' */ case 0x59U: /* 'Y' */ case 0x5AU: /* 'Z' */ case 0x5BU: /* '[' */ case 0x5CU: /* '\' */ case 0x5DU: /* ']' */ case 0x5EU: /* '^' */ case 0x5FU: /* '_' */ case 0x60U: /* '`' */ return -1; #endif case 0x61U: /* 'a' */ return 0xAU; case 0x62U: /* 'b' */ return 0xBU; case 0x63U: /* 'c' */ return 0xCU; case 0x64U: /* 'd' */ return 0xDU; case 0x65U: /* 'e' */ return 0xEU; case 0x66U: /* 'f' */ return 0xFU; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x67U: /* 'g' */ case 0x68U: /* 'h' */ case 0x69U: /* 'i' */ case 0x6AU: /* 'j' */ case 0x6BU: /* 'k' */ case 0x6CU: /* 'l' */ case 0x6DU: /* 'm' */ case 0x6EU: /* 'n' */ case 0x6FU: /* 'o' */ case 0x70U: /* 'p' */ case 0x71U: /* 'q' */ case 0x72U: /* 'r' */ case 0x73U: /* 's' */ case 0x74U: /* 't' */ case 0x75U: /* 'u' */ case 0x76U: /* 'v' */ case 0x77U: /* 'w' */ case 0x78U: /* 'x' */ case 0x79U: /* 'y' */ case 0x7AU: /* 'z' */ case 0x7BU: /* '{' */ case 0x7CU: /* '|' */ case 0x7DU: /* '}' */ case 0x7EU: /* '~' */ case 0x7FU: /* DEL */ case 0x80U: /* EXT */ case 0x81U: /* EXT */ case 0x82U: /* EXT */ case 0x83U: /* EXT */ case 0x84U: /* EXT */ case 0x85U: /* EXT */ case 0x86U: /* EXT */ case 0x87U: /* EXT */ case 0x88U: /* EXT */ case 0x89U: /* EXT */ case 0x8AU: /* EXT */ case 0x8BU: /* EXT */ case 0x8CU: /* EXT */ case 0x8DU: /* EXT */ case 0x8EU: /* EXT */ case 0x8FU: /* EXT */ case 0x90U: /* EXT */ case 0x91U: /* EXT */ case 0x92U: /* EXT */ case 0x93U: /* EXT */ case 0x94U: /* EXT */ case 0x95U: /* EXT */ case 0x96U: /* EXT */ case 0x97U: /* EXT */ case 0x98U: /* EXT */ case 0x99U: /* EXT */ case 0x9AU: /* EXT */ case 0x9BU: /* EXT */ case 0x9CU: /* EXT */ case 0x9DU: /* EXT */ case 0x9EU: /* EXT */ case 0x9FU: /* EXT */ case 0xA0U: /* EXT */ case 0xA1U: /* EXT */ case 0xA2U: /* EXT */ case 0xA3U: /* EXT */ case 0xA4U: /* EXT */ case 0xA5U: /* EXT */ case 0xA6U: /* EXT */ case 0xA7U: /* EXT */ case 0xA8U: /* EXT */ case 0xA9U: /* EXT */ case 0xAAU: /* EXT */ case 0xABU: /* EXT */ case 0xACU: /* EXT */ case 0xADU: /* EXT */ case 0xAEU: /* EXT */ case 0xAFU: /* EXT */ case 0xB0U: /* EXT */ case 0xB1U: /* EXT */ case 0xB2U: /* EXT */ case 0xB3U: /* EXT */ case 0xB4U: /* EXT */ case 0xB5U: /* EXT */ case 0xB6U: /* EXT */ case 0xB7U: /* EXT */ case 0xB8U: /* EXT */ case 0xB9U: /* EXT */ case 0xBAU: /* EXT */ case 0xBBU: /* EXT */ case 0xBCU: /* EXT */ case 0xBDU: /* EXT */ case 0xBEU: /* EXT */ case 0xBFU: /* EXT */ case 0xC0U: /* EXT */ case 0xC1U: /* EXT */ case 0xC2U: /* EXT */ case 0xC3U: /* EXT */ case 0xC4U: /* EXT */ case 0xC5U: /* EXT */ case 0xC6U: /* EXT */ case 0xC7U: /* EXT */ case 0xC8U: /* EXT */ case 0xC9U: /* EXT */ case 0xCAU: /* EXT */ case 0xCBU: /* EXT */ case 0xCCU: /* EXT */ case 0xCDU: /* EXT */ case 0xCEU: /* EXT */ case 0xCFU: /* EXT */ case 0xD0U: /* EXT */ case 0xD1U: /* EXT */ case 0xD2U: /* EXT */ case 0xD3U: /* EXT */ case 0xD4U: /* EXT */ case 0xD5U: /* EXT */ case 0xD6U: /* EXT */ case 0xD7U: /* EXT */ case 0xD8U: /* EXT */ case 0xD9U: /* EXT */ case 0xDAU: /* EXT */ case 0xDBU: /* EXT */ case 0xDCU: /* EXT */ case 0xDDU: /* EXT */ case 0xDEU: /* EXT */ case 0xDFU: /* EXT */ case 0xE0U: /* EXT */ case 0xE1U: /* EXT */ case 0xE2U: /* EXT */ case 0xE3U: /* EXT */ case 0xE4U: /* EXT */ case 0xE5U: /* EXT */ case 0xE6U: /* EXT */ case 0xE7U: /* EXT */ case 0xE8U: /* EXT */ case 0xE9U: /* EXT */ case 0xEAU: /* EXT */ case 0xEBU: /* EXT */ case 0xECU: /* EXT */ case 0xEDU: /* EXT */ case 0xEEU: /* EXT */ case 0xEFU: /* EXT */ case 0xF0U: /* EXT */ case 0xF1U: /* EXT */ case 0xF2U: /* EXT */ case 0xF3U: /* EXT */ case 0xF4U: /* EXT */ case 0xF5U: /* EXT */ case 0xF6U: /* EXT */ case 0xF7U: /* EXT */ case 0xF8U: /* EXT */ case 0xF9U: /* EXT */ case 0xFAU: /* EXT */ case 0xFBU: /* EXT */ case 0xFCU: /* EXT */ case 0xFDU: /* EXT */ case 0xFEU: /* EXT */ case 0xFFU: /* EXT */ return -1; default: mhd_assert (0); break; /* Should be unreachable */ #else default: break; #endif } return -1; #else /* MHD_FAVOR_SMALL_CODE */ if (isasciidigit (c)) return (unsigned char) (c - '0'); if ( (c >= 'A') && (c <= 'F') ) return (unsigned char) (c - 'A' + 10); if ( (c >= 'a') && (c <= 'f') ) return (unsigned char) (c - 'a' + 10); return -1; #endif /* MHD_FAVOR_SMALL_CODE */ } /** * Caseless compare two characters. * * @param c1 the first char to compare * @param c2 the second char to compare * @return boolean 'true' if chars are caseless equal, false otherwise */ _MHD_static_inline bool charsequalcaseless (const char c1, const char c2) { return ( (c1 == c2) || (isasciiupper (c1) ? ((c1 - 'A' + 'a') == c2) : ((c1 == (c2 - 'A' + 'a')) && isasciiupper (c2))) ); } #else /* !INLINE_FUNC */ /** * Checks whether character is lower case letter in US-ASCII * * @param c character to check * @return boolean true if character is lower case letter, * boolean false otherwise */ #define isasciilower(c) (((char) (c)) >= 'a' && ((char) (c)) <= 'z') /** * Checks whether character is upper case letter in US-ASCII * * @param c character to check * @return boolean true if character is upper case letter, * boolean false otherwise */ #define isasciiupper(c) (((char) (c)) >= 'A' && ((char) (c)) <= 'Z') /** * Checks whether character is letter in US-ASCII * * @param c character to check * @return boolean true if character is letter, boolean false * otherwise */ #define isasciialpha(c) (isasciilower (c) || isasciiupper (c)) /** * Check whether character is decimal digit in US-ASCII * * @param c character to check * @return boolean true if character is decimal digit, boolean false * otherwise */ #define isasciidigit(c) (((char) (c)) >= '0' && ((char) (c)) <= '9') /** * Check whether character is hexadecimal digit in US-ASCII * * @param c character to check * @return boolean true if character is hexadecimal digit, * boolean false otherwise */ #define isasciixdigit(c) (isasciidigit ((c)) || \ (((char) (c)) >= 'A' && ((char) (c)) <= 'F') || \ (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ) /** * Check whether character is decimal digit or letter in US-ASCII * * @param c character to check * @return boolean true if character is decimal digit or letter, * boolean false otherwise */ #define isasciialnum(c) (isasciialpha (c) || isasciidigit (c)) /** * Convert US-ASCII character to lower case. * If character is upper case letter in US-ASCII than it's converted to lower * case analog. If character is NOT upper case letter than it's returned * unmodified. * * @param c character to convert * @return converted to lower case character */ #define toasciilower(c) ((isasciiupper (c)) ? (((char) (c)) - 'A' + 'a') : \ ((char) (c))) /** * Convert US-ASCII character to upper case. * If character is lower case letter in US-ASCII than it's converted to upper * case analog. If character is NOT lower case letter than it's returned * unmodified. * * @param c character to convert * @return converted to upper case character */ #define toasciiupper(c) ((isasciilower (c)) ? (((char) (c)) - 'a' + 'A') : \ ((char) (c))) /** * Convert US-ASCII decimal digit to its value. * * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ #define todigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \ (int) (-1)) /** * Convert US-ASCII hexadecimal digit to its value. * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ #define toxdigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \ ( (((char) (c)) >= 'A' && ((char) (c)) <= 'F') ? \ (int) (((unsigned char) (c)) - 'A' + 10) : \ ( (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ? \ (int) (((unsigned char) (c)) - 'a' + 10) : \ (int) (-1) ))) /** * Caseless compare two characters. * * @param c1 the first char to compare * @param c2 the second char to compare * @return boolean 'true' if chars are caseless equal, false otherwise */ #define charsequalcaseless(c1, c2) \ ( ((c1) == (c2)) || \ (isasciiupper (c1) ? \ (((c1) - 'A' + 'a') == (c2)) : \ (((c1) == ((c2) - 'A' + 'a')) && isasciiupper (c2))) ) #endif /* !HAVE_INLINE_FUNCS */ #ifndef MHD_FAVOR_SMALL_CODE /** * Check two strings for equality, ignoring case of US-ASCII letters. * * @param str1 first string to compare * @param str2 second string to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_ (const char *str1, const char *str2) { while (0 != (*str1)) { const char c1 = *str1; const char c2 = *str2; if (charsequalcaseless (c1, c2)) { str1++; str2++; } else return 0; } return 0 == (*str2); } #endif /* ! MHD_FAVOR_SMALL_CODE */ /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a maxlen characters. * Compares up to first terminating null character, but not more than * first @a maxlen characters. * * @param str1 first string to compare * @param str2 second string to compare * @param maxlen maximum number of characters to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_n_ (const char *const str1, const char *const str2, size_t maxlen) { size_t i; for (i = 0; i < maxlen; ++i) { const char c1 = str1[i]; const char c2 = str2[i]; if (0 == c2) return 0 == c1; if (charsequalcaseless (c1, c2)) continue; else return 0; } return ! 0; } /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a len bytes. * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param str1 first string to compare * @param str2 second string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ bool MHD_str_equal_caseless_bin_n_ (const char *const str1, const char *const str2, size_t len) { size_t i; for (i = 0; i < len; ++i) { const char c1 = str1[i]; const char c2 = str2[i]; if (charsequalcaseless (c1, c2)) continue; else return 0; } return ! 0; } /** * Check whether @a str has case-insensitive @a token. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end (of string) or comma * contains only case-insensitive token and optional spaces and tabs. * @warning token must not contain null-characters except optional * terminating null-character. * @param str the string to check * @param token the token to find * @param token_len length of token, not including optional terminating * null-character. * @return non-zero if two strings are equal, zero otherwise. */ bool MHD_str_has_token_caseless_ (const char *str, const char *const token, size_t token_len) { if (0 == token_len) return false; while (0 != *str) { size_t i; /* Skip all whitespaces and empty tokens. */ while (' ' == *str || '\t' == *str || ',' == *str) str++; /* Check for token match. */ i = 0; while (1) { const char sc = *(str++); const char tc = token[i++]; if (0 == sc) return false; if (! charsequalcaseless (sc, tc)) break; if (i >= token_len) { /* Check whether substring match token fully or * has additional unmatched chars at tail. */ while (' ' == *str || '\t' == *str) str++; /* End of (sub)string? */ if ((0 == *str) || (',' == *str) ) return true; /* Unmatched chars at end of substring. */ break; } } /* Find next substring. */ while (0 != *str && ',' != *str) str++; } return false; } /** * Remove case-insensitive @a token from the @a str and put result * to the output @a buf. * * Tokens in @a str could be surrounded by spaces and tabs and delimited by * comma. The token match succeed if substring between start, end (of string) * or comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The output string is normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. * * @param str the string to process * @param str_len the length of the @a str, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @param[out] buf the output buffer, not null-terminated. * @param[in,out] buf_size pointer to the size variable, at input it * is the size of allocated buffer, at output * it is the size of the resulting string (can * be up to 50% larger than input) or negative value * if there is not enough space for the result * @return 'true' if token has been removed, * 'false' otherwise. */ bool MHD_str_remove_token_caseless_ (const char *str, size_t str_len, const char *const token, const size_t token_len, char *buf, ssize_t *buf_size) { const char *s1; /**< the "input" string / character */ char *s2; /**< the "output" string / character */ size_t t_pos; /**< position of matched character in the token */ bool token_removed; mhd_assert (NULL == memchr (token, 0, token_len)); mhd_assert (NULL == memchr (token, ' ', token_len)); mhd_assert (NULL == memchr (token, '\t', token_len)); mhd_assert (NULL == memchr (token, ',', token_len)); mhd_assert (0 <= *buf_size); if (SSIZE_MAX <= ((str_len / 2) * 3 + 3)) { /* The return value may overflow, refuse */ *buf_size = (ssize_t) -1; return false; } s1 = str; s2 = buf; token_removed = false; while ((size_t) (s1 - str) < str_len) { const char *cur_token; /**< the first char of current token */ size_t copy_size; /* Skip any initial whitespaces and empty tokens */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1) || (',' == *s1)) ) s1++; /* 's1' points to the first char of token in the input string or * points just beyond the end of the input string */ if ((size_t) (s1 - str) >= str_len) break; /* Nothing to copy, end of the input string */ /* 's1' points to the first char of token in the input string */ cur_token = s1; /* the first char of input token */ /* Check the token with case-insensetive match */ t_pos = 0; while ( ((size_t) (s1 - str) < str_len) && (token_len > t_pos) && (charsequalcaseless (*s1, token[t_pos])) ) { s1++; t_pos++; } /* s1 may point just beyond the end of the input string */ if ( (token_len == t_pos) && (0 != token_len) ) { /* 'token' matched, check that current input token does not have * any suffixes */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1)) ) s1++; /* 's1' points to the first non-whitespace char after the token matched * requested token or points just beyond the end of the input string after * the requested token */ if (((size_t) (s1 - str) == str_len) || (',' == *s1)) {/* full token match, do not copy current token to the output */ token_removed = true; continue; } } /* 's1' points to first non-whitespace char, to some char after * first non-whitespace char in the token in the input string, to * the ',', or just beyond the end of the input string */ /* The current token in the input string does not match the token * to exclude, it must be copied to the output string */ /* the current token size excluding leading whitespaces and current char */ copy_size = (size_t) (s1 - cur_token); if (buf == s2) { /* The first token to copy to the output */ if ((size_t) *buf_size < copy_size) { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } } else { /* Some token was already copied to the output buffer */ mhd_assert (s2 > buf); if ((size_t) *buf_size < ((size_t) (s2 - buf)) + copy_size + 2) { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = ','; *(s2++) = ' '; } /* Copy non-matched token to the output */ if (0 != copy_size) { memcpy (s2, cur_token, copy_size); s2 += copy_size; } while ( ((size_t) (s1 - str) < str_len) && (',' != *s1)) { /* 's1' points to first non-whitespace char, to some char after * first non-whitespace char in the token in the input string */ /* Copy all non-whitespace chars from the current token in * the input string */ while ( ((size_t) (s1 - str) < str_len) && (',' != *s1) && (' ' != *s1) && ('\t' != *s1) ) { mhd_assert (s2 >= buf); if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */ { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = *(s1++); } /* 's1' points to some whitespace char in the token in the input * string, to the ',', or just beyond the end of the input string */ /* Skip all whitespaces */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1)) ) s1++; /* 's1' points to the first non-whitespace char in the input string * after whitespace chars, to the ',', or just beyond the end of * the input string */ if (((size_t) (s1 - str) < str_len) && (',' != *s1)) { /* Not the end of the current token */ mhd_assert (s2 >= buf); if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */ { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = ' '; } } } mhd_assert (((ssize_t) (s2 - buf)) <= *buf_size); *buf_size = (ssize_t) (s2 - buf); return token_removed; } /** * Perform in-place case-insensitive removal of @a tokens from the @a str. * * Token could be surrounded by spaces and tabs and delimited by comma. * The token match succeed if substring between start, end (of the string), or * comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The input string must be normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. The string is updated in-place. * * Behavior is undefined is the input string in not normalised. * * @param[in,out] str the string to update * @param[in,out] str_len the length of the @a str, not including optional * terminating null-character, not null-terminated * @param tokens the token to find * @param tokens_len the length of @a tokens, not including optional * terminating null-character. * @return 'true' if any token has been removed, * 'false' otherwise. */ bool MHD_str_remove_tokens_caseless_ (char *str, size_t *str_len, const char *const tokens, const size_t tokens_len) { const char *const t = tokens; /**< a short alias for @a tokens */ size_t pt; /**< position in @a tokens */ bool token_removed; mhd_assert (NULL == memchr (tokens, 0, tokens_len)); token_removed = false; pt = 0; while (pt < tokens_len && *str_len != 0) { const char *tkn; /**< the current token */ size_t tkn_len; /* Skip any initial whitespaces and empty tokens in 'tokens' */ while ( (pt < tokens_len) && ((' ' == t[pt]) || ('\t' == t[pt]) || (',' == t[pt])) ) pt++; if (pt >= tokens_len) break; /* No more tokens, nothing to remove */ /* Found non-whitespace char which is not a comma */ tkn = t + pt; do { do { pt++; } while (pt < tokens_len && (' ' != t[pt] && '\t' != t[pt] && ',' != t[pt])); /* Found end of the token string, space, tab, or comma */ tkn_len = pt - (size_t) (tkn - t); /* Skip all spaces and tabs */ while (pt < tokens_len && (' ' == t[pt] || '\t' == t[pt])) pt++; /* Found end of the token string or non-whitespace char */ } while (pt < tokens_len && ',' != t[pt]); /* 'tkn' is the input token with 'tkn_len' chars */ mhd_assert (0 != tkn_len); if (*str_len == tkn_len) { if (MHD_str_equal_caseless_bin_n_ (str, tkn, tkn_len)) { *str_len = 0; token_removed = true; } continue; } /* 'tkn' cannot match part of 'str' if length of 'tkn' is larger * than length of 'str'. * It's know that 'tkn' is not equal to the 'str' (was checked previously). * As 'str' is normalized when 'tkn' is not equal to the 'str' * it is required that 'str' to be at least 3 chars larger then 'tkn' * (the comma, the space and at least one additional character for the next * token) to remove 'tkn' from the 'str'. */ if (*str_len > tkn_len + 2) { /* Remove 'tkn' from the input string */ size_t pr; /**< the 'read' position in the @a str */ size_t pw; /**< the 'write' position in the @a str */ pr = 0; pw = 0; do { mhd_assert (pr >= pw); mhd_assert ((*str_len) >= (pr + tkn_len)); if ( ( ((*str_len) == (pr + tkn_len)) || (',' == str[pr + tkn_len]) ) && MHD_str_equal_caseless_bin_n_ (str + pr, tkn, tkn_len) ) { /* current token in the input string matches the 'tkn', skip it */ mhd_assert ((*str_len == pr + tkn_len) || \ (' ' == str[pr + tkn_len + 1])); /* 'str' must be normalized */ token_removed = true; /* Advance to the next token in the input string or beyond * the end of the input string. */ pr += tkn_len + 2; } else { /* current token in the input string does not match the 'tkn', * copy to the output */ if (0 != pw) { /* not the first output token, add ", " to separate */ if (pr != pw + 2) { str[pw++] = ','; str[pw++] = ' '; } else pw += 2; /* 'str' is not yet modified in this round */ } do { if (pr != pw) str[pw] = str[pr]; pr++; pw++; } while (pr < *str_len && ',' != str[pr]); /* Advance to the next token in the input string or beyond * the end of the input string. */ pr += 2; } /* 'pr' should point to the next token in the input string or beyond * the end of the input string */ if ((*str_len) < (pr + tkn_len)) { /* The rest of the 'str + pr' is too small to match 'tkn' */ if ((*str_len) > pr) { /* Copy the rest of the string */ size_t copy_size; copy_size = *str_len - pr; if (0 != pw) { /* not the first output token, add ", " to separate */ if (pr != pw + 2) { str[pw++] = ','; str[pw++] = ' '; } else pw += 2; /* 'str' is not yet modified in this round */ } if (pr != pw) memmove (str + pw, str + pr, copy_size); pw += copy_size; } *str_len = pw; break; } mhd_assert ((' ' != str[0]) && ('\t' != str[0])); mhd_assert ((0 == pr) || (3 <= pr)); mhd_assert ((0 == pr) || (' ' == str[pr - 1])); mhd_assert ((0 == pr) || (',' == str[pr - 2])); } while (1); } } return token_removed; } #ifndef MHD_FAVOR_SMALL_CODE /* Use individual function for each case */ /** * Convert decimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_ (const char *str, uint64_t *out_val) { const char *const start = str; uint64_t res; if (! str || ! out_val || ! isasciidigit (str[0])) return 0; res = 0; do { const int digit = (unsigned char) (*str) - '0'; if ( (res > (UINT64_MAX / 10)) || ( (res == (UINT64_MAX / 10)) && ((uint64_t) digit > (UINT64_MAX % 10)) ) ) return 0; res *= 10; res += (unsigned int) digit; str++; } while (isasciidigit (*str)); *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen decimal US-ASCII digits in string to * number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val) { uint64_t res; size_t i; if (! str || ! maxlen || ! out_val || ! isasciidigit (str[0])) return 0; res = 0; i = 0; do { const int digit = (unsigned char) str[i] - '0'; if ( (res > (UINT64_MAX / 10)) || ( (res == (UINT64_MAX / 10)) && ((uint64_t) digit > (UINT64_MAX % 10)) ) ) return 0; res *= 10; res += (unsigned int) digit; i++; } while ( (i < maxlen) && isasciidigit (str[i]) ); *out_val = res; return i; } /** * Convert hexadecimal US-ASCII digits in string to number in uint32_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_ (const char *str, uint32_t *out_val) { const char *const start = str; uint32_t res; int digit; if (! str || ! out_val) return 0; res = 0; digit = toxdigitvalue (*str); while (digit >= 0) { if ( (res < (UINT32_MAX / 16)) || ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit <= (UINT32_MAX % 16)) ) ) { res *= 16; res += (unsigned int) digit; } else return 0; str++; digit = toxdigitvalue (*str); } if (str - start > 0) *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint32_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_n_ (const char *str, size_t maxlen, uint32_t *out_val) { size_t i; uint32_t res; int digit; if (! str || ! out_val) return 0; res = 0; i = 0; while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0) { if ( (res > (UINT32_MAX / 16)) || ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit > (UINT32_MAX % 16)) ) ) return 0; res *= 16; res += (unsigned int) digit; i++; } if (i) *out_val = res; return i; } /** * Convert hexadecimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_ (const char *str, uint64_t *out_val) { const char *const start = str; uint64_t res; int digit; if (! str || ! out_val) return 0; res = 0; digit = toxdigitvalue (*str); while (digit >= 0) { if ( (res < (UINT64_MAX / 16)) || ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit <= (UINT64_MAX % 16)) ) ) { res *= 16; res += (unsigned int) digit; } else return 0; str++; digit = toxdigitvalue (*str); } if (str - start > 0) *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val) { size_t i; uint64_t res; int digit; if (! str || ! out_val) return 0; res = 0; i = 0; while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0) { if ( (res > (UINT64_MAX / 16)) || ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit > (UINT64_MAX % 16)) ) ) return 0; res *= 16; res += (unsigned int) digit; i++; } if (i) *out_val = res; return i; } #else /* MHD_FAVOR_SMALL_CODE */ /** * Generic function for converting not more then @a maxlen * hexadecimal or decimal US-ASCII digits in string to number. * Conversion stopped at first non-digit character or after @a maxlen * digits. * To be used only within macro. * * @param str the string to convert * @param maxlen the maximum number of characters to process * @param out_val the pointer to variable to store result of conversion * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8 * @param max_val the maximum decoded number * @param base the numeric base, 10 or 16 * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then @a max_val, @a val_size is not 4/8 or @a out_val is NULL */ size_t MHD_str_to_uvalue_n_ (const char *str, size_t maxlen, void *out_val, size_t val_size, uint64_t max_val, unsigned int base) { size_t i; uint64_t res; const uint64_t max_v_div_b = max_val / base; const uint64_t max_v_mod_b = max_val % base; if (! str || ! out_val || ((base != 16) && (base != 10)) ) return 0; res = 0; i = 0; while (maxlen > i) { const int digit = (base == 16) ? toxdigitvalue (str[i]) : todigitvalue (str[i]); if (0 > digit) break; if ( ((max_v_div_b) < res) || (( (max_v_div_b) == res) && ( (max_v_mod_b) < (uint64_t) digit) ) ) return 0; res *= base; res += (unsigned int) digit; i++; } if (i) { if (8 == val_size) *(uint64_t *) out_val = res; else if (4 == val_size) *(uint32_t *) out_val = (uint32_t) res; else return 0; } return i; } #endif /* MHD_FAVOR_SMALL_CODE */ size_t MHD_uint32_to_strx (uint32_t val, char *buf, size_t buf_size) { size_t o_pos = 0; /**< position of the output character */ int digit_pos = 8; /** zero-based, digit position in @a 'val' */ int digit; /* Skip leading zeros */ do { digit_pos--; digit = (int) (val >> 28); val <<= 4; } while ((0 == digit) && (0 != digit_pos)); while (o_pos < buf_size) { buf[o_pos++] = (char) ((digit <= 9) ? ('0' + (char) digit) : ('A' + (char) digit - 10)); if (0 == digit_pos) return o_pos; digit_pos--; digit = (int) (val >> 28); val <<= 4; } return 0; /* The buffer is too small */ } #ifndef MHD_FAVOR_SMALL_CODE size_t MHD_uint16_to_str (uint16_t val, char *buf, size_t buf_size) { char *chr; /**< pointer to the current printed digit */ /* The biggest printable number is 65535 */ uint16_t divisor = UINT16_C (10000); int digit; chr = buf; digit = (int) (val / divisor); mhd_assert (digit < 10); /* Do not print leading zeros */ while ((0 == digit) && (1 < divisor)) { divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } while (0 != buf_size) { *chr = (char) ((char) digit + '0'); chr++; buf_size--; if (1 == divisor) return (size_t) (chr - buf); val = (uint16_t) (val % divisor); divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } return 0; /* The buffer is too small */ } #endif /* !MHD_FAVOR_SMALL_CODE */ size_t MHD_uint64_to_str (uint64_t val, char *buf, size_t buf_size) { char *chr; /**< pointer to the current printed digit */ /* The biggest printable number is 18446744073709551615 */ uint64_t divisor = UINT64_C (10000000000000000000); int digit; chr = buf; digit = (int) (val / divisor); mhd_assert (digit < 10); /* Do not print leading zeros */ while ((0 == digit) && (1 < divisor)) { divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } while (0 != buf_size) { *chr = (char) ((char) digit + '0'); chr++; buf_size--; if (1 == divisor) return (size_t) (chr - buf); val %= divisor; divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } return 0; /* The buffer is too small */ } size_t MHD_uint8_to_str_pad (uint8_t val, uint8_t min_digits, char *buf, size_t buf_size) { size_t pos; /**< the position of the current printed digit */ int digit; mhd_assert (3 >= min_digits); if (0 == buf_size) return 0; pos = 0; digit = val / 100; if (0 == digit) { if (3 <= min_digits) buf[pos++] = '0'; } else { buf[pos++] = (char) ('0' + (char) digit); val %= 100; min_digits = 2; } if (buf_size <= pos) return 0; digit = val / 10; if (0 == digit) { if (2 <= min_digits) buf[pos++] = '0'; } else { buf[pos++] = (char) ('0' + (char) digit); val %= 10; } if (buf_size <= pos) return 0; buf[pos++] = (char) ('0' + (char) val); return pos; } size_t MHD_bin_to_hex (const void *bin, size_t size, char *hex) { size_t i; for (i = 0; i < size; ++i) { uint8_t j; const uint8_t b = ((const uint8_t *) bin)[i]; j = b >> 4; hex[i * 2] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a')); j = b & 0x0f; hex[i * 2 + 1] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a')); } return i * 2; } size_t MHD_bin_to_hex_z (const void *bin, size_t size, char *hex) { size_t res; res = MHD_bin_to_hex (bin, size, hex); hex[res] = 0; return res; } size_t MHD_hex_to_bin (const char *hex, size_t len, void *bin) { uint8_t *const out = (uint8_t *) bin; size_t r; size_t w; if (0 == len) return 0; r = 0; w = 0; if (0 != len % 2) { /* Assume the first byte is encoded with single digit */ const char c2 = hex[r++]; const int l = toxdigitvalue (c2); if (0 > l) return 0; out[w++] = (uint8_t) ((unsigned int) l); } while (r < len) { const char c1 = hex[r++]; const char c2 = hex[r++]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); if ((0 > h) || (0 > l)) return 0; out[w++] = (uint8_t) ( ((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l)) ); } mhd_assert (len == r); mhd_assert ((len + 1) / 2 == w); return w; } size_t MHD_str_pct_decode_strict_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size) { #ifdef MHD_FAVOR_SMALL_CODE bool broken; size_t res; res = MHD_str_pct_decode_lenient_n_ (pct_encoded, pct_encoded_len, decoded, buf_size, &broken); if (broken) return 0; return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; r = 0; w = 0; if (buf_size >= pct_encoded_len) { while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if ('%' == chr) { if (2 > pct_encoded_len - r) return 0; else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } else decoded[w] = chr; ++r; ++w; } return w; } while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if (w >= buf_size) return 0; if ('%' == chr) { if (2 > pct_encoded_len - r) return 0; else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } else decoded[w] = chr; ++r; ++w; } return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } size_t MHD_str_pct_decode_lenient_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size, bool *broken_encoding) { size_t r; size_t w; r = 0; w = 0; if (NULL != broken_encoding) *broken_encoding = false; #ifndef MHD_FAVOR_SMALL_CODE if (buf_size >= pct_encoded_len) { while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if ('%' == chr) { if (2 > pct_encoded_len - r) { if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) { r -= 2; if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } } else decoded[w] = chr; ++r; ++w; } return w; } #endif /* ! MHD_FAVOR_SMALL_CODE */ while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if (w >= buf_size) return 0; if ('%' == chr) { if (2 > pct_encoded_len - r) { if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); if ((0 > h) || (0 > l)) { r -= 2; if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { unsigned char out; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } } else decoded[w] = chr; ++r; ++w; } return w; } size_t MHD_str_pct_decode_in_place_strict_ (char *str) { #ifdef MHD_FAVOR_SMALL_CODE size_t res; bool broken; res = MHD_str_pct_decode_in_place_lenient_ (str, &broken); if (broken) { res = 0; str[0] = 0; } return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; r = 0; w = 0; while (0 != str[r]) { const char chr = str[r++]; if ('%' == chr) { const char d1 = str[r++]; if (0 == d1) return 0; else { const char d2 = str[r++]; if (0 == d2) return 0; else { const int h = toxdigitvalue (d1); const int l = toxdigitvalue (d2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); str[w++] = (char) out; } } } else str[w++] = chr; } str[w] = 0; return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } size_t MHD_str_pct_decode_in_place_lenient_ (char *str, bool *broken_encoding) { #ifdef MHD_FAVOR_SMALL_CODE size_t len; size_t res; len = strlen (str); res = MHD_str_pct_decode_lenient_n_ (str, len, str, len, broken_encoding); str[res] = 0; return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; if (NULL != broken_encoding) *broken_encoding = false; r = 0; w = 0; while (0 != str[r]) { const char chr = str[r++]; if ('%' == chr) { const char d1 = str[r++]; if (0 == d1) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w] = 0; return w; } else { const char d2 = str[r++]; if (0 == d2) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w++] = d1; /* Copy "as is" */ str[w] = 0; return w; } else { const int h = toxdigitvalue (d1); const int l = toxdigitvalue (d2); unsigned char out; if ((0 > h) || (0 > l)) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w++] = d1; str[w++] = d2; continue; } out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); str[w++] = (char) out; continue; } } } str[w++] = chr; } str[w] = 0; return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } #ifdef DAUTH_SUPPORT bool MHD_str_equal_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len) { size_t i; size_t j; if (unquoted_len < quoted_len / 2) return false; j = 0; for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j) { if ('\\' == quoted[i]) { i++; /* Advance to the next character */ if (quoted_len == i) return false; /* No character after escaping backslash */ } if (quoted[i] != unquoted[j]) return false; /* Different characters */ } if ((quoted_len != i) || (unquoted_len != j)) return false; /* The strings have different length */ return true; } bool MHD_str_equal_caseless_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len) { size_t i; size_t j; if (unquoted_len < quoted_len / 2) return false; j = 0; for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j) { if ('\\' == quoted[i]) { i++; /* Advance to the next character */ if (quoted_len == i) return false; /* No character after escaping backslash */ } if (! charsequalcaseless (quoted[i], unquoted[j])) return false; /* Different characters */ } if ((quoted_len != i) || (unquoted_len != j)) return false; /* The strings have different length */ return true; } size_t MHD_str_unquote (const char *quoted, size_t quoted_len, char *result) { size_t r; size_t w; r = 0; w = 0; while (quoted_len > r) { if ('\\' == quoted[r]) { ++r; if (quoted_len == r) return 0; /* Last backslash is not followed by char to unescape */ } result[w++] = quoted[r++]; } return w; } #endif /* DAUTH_SUPPORT */ #if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT) size_t MHD_str_quote (const char *unquoted, size_t unquoted_len, char *result, size_t buf_size) { size_t r; size_t w; r = 0; w = 0; #ifndef MHD_FAVOR_SMALL_CODE if (unquoted_len * 2 <= buf_size) { /* Fast loop: the output will fit the buffer with any input string content */ while (unquoted_len > r) { const char chr = unquoted[r++]; if (('\\' == chr) || ('\"' == chr)) result[w++] = '\\'; /* Escape current char */ result[w++] = chr; } } else { if (unquoted_len > buf_size) return 0; /* Quick fail: the output buffer is too small */ #else /* MHD_FAVOR_SMALL_CODE */ if (1) { #endif /* MHD_FAVOR_SMALL_CODE */ while (unquoted_len > r) { if (buf_size <= w) return 0; /* The output buffer is too small */ else { const char chr = unquoted[r++]; if (('\\' == chr) || ('\"' == chr)) { result[w++] = '\\'; /* Escape current char */ if (buf_size <= w) return 0; /* The output buffer is too small */ } result[w++] = chr; } } } mhd_assert (w >= r); mhd_assert (w <= r * 2); return w; } #endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT /* * MHD_BASE64_FUNC_VERSION * 1 = smallest, * 2 = medium, * 3 = fastest */ #ifndef MHD_BASE64_FUNC_VERSION #ifdef MHD_FAVOR_SMALL_CODE #define MHD_BASE64_FUNC_VERSION 1 #else /* ! MHD_FAVOR_SMALL_CODE */ #define MHD_BASE64_FUNC_VERSION 3 #endif /* ! MHD_FAVOR_SMALL_CODE */ #endif /* ! MHD_BASE64_FUNC_VERSION */ #if MHD_BASE64_FUNC_VERSION < 1 || MHD_BASE64_FUNC_VERSION > 3 #error Wrong MHD_BASE64_FUNC_VERSION value #endif /* MHD_BASE64_FUNC_VERSION < 1 || MHD_BASE64_FUNC_VERSION > 3 */ #if MHD_BASE64_FUNC_VERSION == 3 #define MHD_base64_map_type_ int #else /* MHD_BASE64_FUNC_VERSION < 3 */ #define MHD_base64_map_type_ int8_t #endif /* MHD_BASE64_FUNC_VERSION < 3 */ #if MHD_BASE64_FUNC_VERSION == 1 static MHD_base64_map_type_ base64_char_to_value_ (uint8_t c) { if ('Z' >= c) { if ('A' <= c) return (MHD_base64_map_type_) ((c - 'A') + 0); if ('0' <= c) { if ('9' >= c) return (MHD_base64_map_type_) ((c - '0') + 52); if ('=' == c) return -2; return -1; } if ('+' == c) return 62; if ('/' == c) return 63; return -1; } if (('z' >= c) && ('a' <= c)) return (MHD_base64_map_type_) ((c - 'a') + 26); return -1; } #endif /* MHD_BASE64_FUNC_VERSION == 1 */ MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ size_t MHD_base64_to_bin_n (const char *base64, size_t base64_len, void *bin, size_t bin_size) { #if MHD_BASE64_FUNC_VERSION >= 2 static const MHD_base64_map_type_ map[] = { /* -1 = invalid char, -2 = padding 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, BS, HT, LF, VT, FF, CR, SO, SI, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, CAN, EM, SUB, ESC, FS, GS, RS, US, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, ' ', '!', '"', '#', '$', '%', '&', '\'', */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, '(', ')', '*', '+', ',', '-', '.', '/', */ -1, -1, -1, 62, -1, -1, -1, 63, /* 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, '0', '1', '2', '3', '4', '5', '6', '7', */ 52, 53, 54, 55, 56, 57, 58, 59, /* 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, '8', '9', ':', ';', '<', '=', '>', '?', */ 60, 61, -1, -1, -1, -2, -1, -1, /* 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', */ -1, 0, 1, 2, 3, 4, 5, 6, /* 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', */ 7, 8, 9, 10, 11, 12, 13, 14, /* 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', */ 15, 16, 17, 18, 19, 20, 21, 22, /* 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 'X', 'Y', 'Z', '[', '\', ']', '^', '_', */ 23, 24, 25, -1, -1, -1, -1, -1, /* 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', */ -1, 26, 27, 28, 29, 30, 31, 32, /* 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', */ 33, 34, 35, 36, 37, 38, 39, 40, /* 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', */ 41, 42, 43, 44, 45, 46, 47, 48, /* 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 'x', 'y', 'z', '{', '|', '}', '~', DEL, */ 49, 50, 51, -1, -1, -1, -1, -1 #if MHD_BASE64_FUNC_VERSION == 3 , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80..8F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90..9F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0..AF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0..BF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0..CF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0..DF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0..EF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* F0..FF */ #endif /* ! MHD_BASE64_FUNC_VERSION == 3 */ }; #define base64_char_to_value_(c) map[(c)] #endif /* MHD_BASE64_FUNC_VERSION >= 2 */ const uint8_t *const in = (const uint8_t *) base64; uint8_t *const out = (uint8_t *) bin; size_t i; size_t j; if (0 == base64_len) return 0; /* Nothing to decode */ if (0 != base64_len % 4) return 0; /* Wrong input length */ if (base64_len / 4 * 3 - 2 > bin_size) return 0; j = 0; for (i = 0; i < (base64_len - 4); i += 4) { #if MHD_BASE64_FUNC_VERSION == 2 if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3]))) return 0; #endif /* MHD_BASE64_FUNC_VERSION == 2 */ if (1) { const MHD_base64_map_type_ v1 = base64_char_to_value_ (in[i + 0]); const MHD_base64_map_type_ v2 = base64_char_to_value_ (in[i + 1]); const MHD_base64_map_type_ v3 = base64_char_to_value_ (in[i + 2]); const MHD_base64_map_type_ v4 = base64_char_to_value_ (in[i + 3]); if ((0 > v1) || (0 > v2) || (0 > v3) || (0 > v4)) return 0; out[j + 0] = (uint8_t) (((uint8_t) (((uint8_t) v1) << 2)) | ((uint8_t) (((uint8_t) v2) >> 4))); out[j + 1] = (uint8_t) (((uint8_t) (((uint8_t) v2) << 4)) | ((uint8_t) (((uint8_t) v3) >> 2))); out[j + 2] = (uint8_t) (((uint8_t) (((uint8_t) v3) << 6)) | ((uint8_t) v4)); } j += 3; } #if MHD_BASE64_FUNC_VERSION == 2 if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3]))) return 0; #endif /* MHD_BASE64_FUNC_VERSION == 2 */ if (1) { /* The last four chars block */ const MHD_base64_map_type_ v1 = base64_char_to_value_ (in[i + 0]); const MHD_base64_map_type_ v2 = base64_char_to_value_ (in[i + 1]); const MHD_base64_map_type_ v3 = base64_char_to_value_ (in[i + 2]); const MHD_base64_map_type_ v4 = base64_char_to_value_ (in[i + 3]); if ((0 > v1) || (0 > v2)) return 0; /* Invalid char or padding at first two positions */ mhd_assert (j < bin_size); out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v1) << 2)) | ((uint8_t) (((uint8_t) v2) >> 4))); if (0 > v3) { /* Third char is either padding or invalid */ if ((-2 != v3) || (-2 != v4)) return 0; /* Both two last chars must be padding */ if (0 != (uint8_t) (((uint8_t) v2) << 4)) return 0; /* Wrong last char */ return j; } if (j >= bin_size) return 0; /* Not enough space */ out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v2) << 4)) | ((uint8_t) (((uint8_t) v3) >> 2))); if (0 > v4) { /* Fourth char is either padding or invalid */ if (-2 != v4) return 0; /* The char must be padding */ if (0 != (uint8_t) (((uint8_t) v3) << 6)) return 0; /* Wrong last char */ return j; } if (j >= bin_size) return 0; /* Not enough space */ out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v3) << 6)) | ((uint8_t) v4)); } return j; #if MHD_BASE64_FUNC_VERSION >= 2 #undef base64_char_to_value_ #endif /* MHD_BASE64_FUNC_VERSION >= 2 */ } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ #undef MHD_base64_map_type_ #endif /* BAUTH_SUPPORT */ libmicrohttpd-1.0.2/src/microhttpd/mhd_send.c0000644000175000017500000015225415035214301016173 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2023 Karlson2k (Evgeny Grin), Full re-write of buffering and pushing, many bugs fixes, optimisations, sendfile() porting Copyright (C) 2019 ng0 , Initial version of send() wrappers This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_send.c * @brief Implementation of send() wrappers and helper functions. * @author Karlson2k (Evgeny Grin) * @author ng0 (N. Gillmann) * @author Christian Grothoff */ /* Worth considering for future improvements and additions: * NetBSD has no sendfile or sendfile64. The way to work * with this seems to be to mmap the file and write(2) as * large a chunk as possible to the socket. Alternatively, * use madvise(..., MADV_SEQUENTIAL). */ #include "mhd_send.h" #ifdef MHD_LINUX_SOLARIS_SENDFILE #include #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE) #include #include #include #endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */ #ifdef HAVE_SYS_PARAM_H /* For FreeBSD version identification */ #include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_SYSCONF #include #endif /* HAVE_SYSCONF */ #include "mhd_assert.h" #include "mhd_limits.h" #ifdef MHD_VECT_SEND #if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL)) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \ defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) #define _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED 1 #endif /* (!HAVE_SENDMSG || !MSG_NOSIGNAL) && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #endif /* MHD_VECT_SEND */ /** * sendfile() chuck size */ #define MHD_SENFILE_CHUNK_ (0x20000) /** * sendfile() chuck size for thread-per-connection */ #define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000) #ifdef HAVE_FREEBSD_SENDFILE #ifdef SF_FLAGS /** * FreeBSD sendfile() flags */ static int freebsd_sendfile_flags_; /** * FreeBSD sendfile() flags for thread-per-connection */ static int freebsd_sendfile_flags_thd_p_c_; /** * Initialises variables for FreeBSD's sendfile() */ static void freebsd_sendfile_init_ (void) { long sys_page_size = sysconf (_SC_PAGESIZE); if (0 >= sys_page_size) { /* Failed to get page size. */ freebsd_sendfile_flags_ = SF_NODISKIO; freebsd_sendfile_flags_thd_p_c_ = SF_NODISKIO; } else { freebsd_sendfile_flags_ = SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_ + sys_page_size - 1) / sys_page_size), SF_NODISKIO); freebsd_sendfile_flags_thd_p_c_ = SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_THR_P_C_ + sys_page_size - 1) / sys_page_size), SF_NODISKIO); } } #endif /* SF_FLAGS */ #endif /* HAVE_FREEBSD_SENDFILE */ #if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX) /** * Current IOV_MAX system value */ static unsigned long mhd_iov_max_ = 0; static void iov_max_init_ (void) { long res = sysconf (_SC_IOV_MAX); if (res >= 0) mhd_iov_max_ = (unsigned long) res; else { #if defined(IOV_MAX) mhd_iov_max_ = IOV_MAX; #else /* ! IOV_MAX */ mhd_iov_max_ = 8; /* Should be the safe limit */ #endif /* ! IOV_MAX */ } } /** * IOV_MAX (run-time) value */ #define _MHD_IOV_MAX mhd_iov_max_ #elif defined(IOV_MAX) /** * IOV_MAX (static) value */ #define _MHD_IOV_MAX IOV_MAX #endif /* HAVE_SYSCONF && _SC_IOV_MAX */ /** * Initialises static variables */ void MHD_send_init_static_vars_ (void) { #ifdef HAVE_FREEBSD_SENDFILE /* FreeBSD 11 and later allow to specify read-ahead size * and handles SF_NODISKIO differently. * SF_FLAGS defined only on FreeBSD 11 and later. */ #ifdef SF_FLAGS freebsd_sendfile_init_ (); #endif /* SF_FLAGS */ #endif /* HAVE_FREEBSD_SENDFILE */ #if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX) iov_max_init_ (); #endif /* HAVE_SYSCONF && _SC_IOV_MAX */ } bool MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection, bool nodelay_state) { #ifdef TCP_NODELAY const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; int err_code; if (_MHD_YES == connection->is_nonip) return false; if (0 == setsockopt (connection->socket_fd, IPPROTO_TCP, TCP_NODELAY, (const void *) (nodelay_state ? &on_val : &off_val), sizeof (off_val))) { connection->sk_nodelay = nodelay_state; return true; } err_code = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_)) { if (_MHD_UNKNOWN == connection->is_nonip) connection->is_nonip = _MHD_YES; #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed " "for TCP/IP socket %d: %s\n"), "TCP_NODELAY", nodelay_state ? _ ("ON") : _ ("OFF"), (int) connection->socket_fd, MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed: %s\n"), "TCP_NODELAY", nodelay_state ? _ ("ON") : _ ("OFF"), MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ #else /* ! TCP_NODELAY */ (void) connection; (void) nodelay_state; /* Mute compiler warnings */ #endif /* ! TCP_NODELAY */ return false; } /** * Set required cork state for connection socket * * The function automatically updates sk_corked state. * * @param connection the connection to manipulate * @param cork_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_cork_state_ (struct MHD_Connection *connection, bool cork_state) { #if defined(MHD_TCP_CORK_NOPUSH) const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; int err_code; if (_MHD_YES == connection->is_nonip) return false; if (0 == setsockopt (connection->socket_fd, IPPROTO_TCP, MHD_TCP_CORK_NOPUSH, (const void *) (cork_state ? &on_val : &off_val), sizeof (off_val))) { connection->sk_corked = cork_state; return true; } err_code = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_)) { if (_MHD_UNKNOWN == connection->is_nonip) connection->is_nonip = _MHD_YES; #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed " "for TCP/IP socket %d: %s\n"), #ifdef TCP_CORK "TCP_CORK", #else /* ! TCP_CORK */ "TCP_NOPUSH", #endif /* ! TCP_CORK */ cork_state ? _ ("ON") : _ ("OFF"), (int) connection->socket_fd, MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed: %s\n"), #ifdef TCP_CORK "TCP_CORK", #else /* ! TCP_CORK */ "TCP_NOPUSH", #endif /* ! TCP_CORK */ cork_state ? _ ("ON") : _ ("OFF"), MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ #else /* ! MHD_TCP_CORK_NOPUSH */ (void) connection; (void) cork_state; /* Mute compiler warnings. */ #endif /* ! MHD_TCP_CORK_NOPUSH */ return false; } /** * Handle pre-send setsockopt calls. * * @param connection the MHD_Connection structure * @param plain_send set to true if plain send() or sendmsg() will be called, * set to false if TLS socket send(), sendfile() or * writev() will be called. * @param push_data whether to push data to the network from buffers after * the next call of send function. */ static void pre_send_setopt (struct MHD_Connection *connection, bool plain_send, bool push_data) { /* Try to buffer data if not sending the final piece. * Final piece is indicated by push_data == true. */ const bool buffer_data = (! push_data); if (_MHD_YES == connection->is_nonip) return; /* The goal is to minimise the total number of additional sys-calls * before and after send(). * The following tricky (over-)complicated algorithm typically use zero, * one or two additional sys-calls (depending on OS) for each response. */ if (buffer_data) { /* Need to buffer data if possible. */ #ifdef MHD_USE_MSG_MORE if (plain_send) return; /* Data is buffered by send() with MSG_MORE flag. * No need to check or change anything. */ #else /* ! MHD_USE_MSG_MORE */ (void) plain_send; /* Mute compiler warning. */ #endif /* ! MHD_USE_MSG_MORE */ #ifdef MHD_TCP_CORK_NOPUSH if (_MHD_ON == connection->sk_corked) return; /* The connection was already corked. */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. */ /* Failed to cork the connection. * Really unlikely to happen on TCP connections. */ #endif /* MHD_TCP_CORK_NOPUSH */ if (_MHD_OFF == connection->sk_nodelay) return; /* TCP_NODELAY was not set for the socket. * Nagle's algorithm will buffer some data. */ /* Try to reset TCP_NODELAY state for the socket. * Ignore possible error as no other options exist to * buffer data. */ MHD_connection_set_nodelay_state_ (connection, false); /* TCP_NODELAY has been (hopefully) reset for the socket. * Nagle's algorithm will buffer some data. */ return; } /* Need to push data after send() */ /* If additional sys-call is required prefer to make it after the send() * as the next send() may consume only part of the prepared data and * more send() calls will be used. */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef _MHD_CORK_RESET_PUSH_DATA #ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS /* Data can be pushed immediately by uncorking socket regardless of * cork state before. */ /* This is typical for Linux, no other kernel with * such behavior are known so far. */ /* No need to check the current state of TCP_CORK / TCP_NOPUSH * as reset of cork will push the data anyway. */ return; /* Data may be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ #else /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /* Reset of TCP_CORK / TCP_NOPUSH will push the data * only if socket is corked. */ #ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS /* Data can be pushed immediately by setting TCP_NODELAY regardless * of TCP_NODDELAY or corking state before. */ /* Dead code currently, no known kernels with such behavior. */ return; /* Data may be pushed by setting of TCP_NODELAY after send(). No need to make extra sys-calls before send().*/ #else /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #ifdef _MHD_NODELAY_SET_PUSH_DATA /* Setting of TCP_NODELAY will push the data only if * both TCP_NODELAY and TCP_CORK / TCP_NOPUSH were not set. */ /* Data can be pushed immediately by uncorking socket if * socket was corked before or by setting TCP_NODELAY if * socket was not corked and TCP_NODELAY was not set before. */ /* Dead code currently as Linux is the only kernel that push * data by setting of TCP_NODELAY and Linux push data always. */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* Data can be pushed immediately by uncorking socket or * can be pushed by send() on uncorked socket if * TCP_NODELAY was set *before*. */ /* This is typical FreeBSD behavior. */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA */ if (_MHD_ON == connection->sk_corked) return; /* Socket is corked. Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ else if (_MHD_OFF == connection->sk_corked) { /* The socket is not corked. */ if (_MHD_ON == connection->sk_nodelay) return; /* TCP_NODELAY was already set, * data will be pushed automatically by the next send() */ #ifdef _MHD_NODELAY_SET_PUSH_DATA else if (_MHD_UNKNOWN == connection->sk_nodelay) { /* Setting TCP_NODELAY may push data. * Cork socket here and uncork after send(). */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. * Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ else { /* The socket cannot be corked. * Really unlikely to happen on TCP connections */ /* Have to set TCP_NODELAY. * If TCP_NODELAY real system state was OFF then * already buffered data may be pushed here, but this is unlikely * to happen as it is only a backup solution when corking has failed. * Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_nodelay_state_ (connection, true); /* TCP_NODELAY has been (hopefully) set for the socket. * The data will be pushed by the next send(). */ return; } } #endif /* _MHD_NODELAY_SET_PUSH_DATA */ else { #ifdef _MHD_NODELAY_SET_PUSH_DATA /* TCP_NODELAY was switched off and * the socket is not corked. */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* Socket is not corked and TCP_NODELAY was not set or unknown. */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* At least one additional sys-call is required. */ /* Setting TCP_NODELAY is optimal here as data will be pushed * automatically by the next send() and no additional * sys-call are needed after the send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; else { /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ /* Cork the socket here and make additional sys-call * to uncork the socket after send(). */ /* Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_cork_state_ (connection, true); /* The connection has been (hopefully) corked. * Data can be pushed by resetting of TCP_CORK / TCP_NOPUSH * after send() */ return; } } } /* Corked state is unknown. Need to make sys-call here otherwise * data may not be pushed. */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. * Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ /* The socket cannot be corked. * Really unlikely to happen on TCP connections */ if (_MHD_ON == connection->sk_nodelay) return; /* TCP_NODELAY was already set, * data will be pushed by the next send() */ /* Have to set TCP_NODELAY. */ #ifdef _MHD_NODELAY_SET_PUSH_DATA /* If TCP_NODELAY state was unknown (external connection) then * already buffered data may be pushed here, but this is unlikely * to happen as it is only a backup solution when corking has failed. */ #endif /* _MHD_NODELAY_SET_PUSH_DATA */ /* Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_nodelay_state_ (connection, true); /* TCP_NODELAY has been (hopefully) set for the socket. * The data will be pushed by the next send(). */ return; #endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ #else /* ! _MHD_CORK_RESET_PUSH_DATA */ /* Neither uncorking the socket or setting TCP_NODELAY * push the data immediately. */ /* The only way to push the data is to use send() on uncorked * socket with TCP_NODELAY switched on . */ /* This is a typical *BSD (except FreeBSD) and Darwin behavior. */ /* Uncork socket if socket wasn't uncorked. */ if (_MHD_OFF != connection->sk_corked) MHD_connection_set_cork_state_ (connection, false); /* Set TCP_NODELAY if it wasn't set. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); return; #endif /* ! _MHD_CORK_RESET_PUSH_DATA */ #else /* ! MHD_TCP_CORK_NOPUSH */ /* Buffering of data is controlled only by * Nagel's algorithm. */ /* Set TCP_NODELAY if it wasn't set. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); #endif /* ! MHD_TCP_CORK_NOPUSH */ } #ifndef _MHD_CORK_RESET_PUSH_DATA_ALWAYS /** * Send zero-sized data * * This function use send of zero-sized data to kick data from the socket * buffers to the network. The socket must not be corked and must have * TCP_NODELAY switched on. * Used only as last resort option, when other options are failed due to * some errors. * Should not be called on typical data processing. * @return true if succeed, false if failed */ static bool zero_send_ (struct MHD_Connection *connection) { int dummy; if (_MHD_YES == connection->is_nonip) return false; mhd_assert (_MHD_OFF == connection->sk_corked); mhd_assert (_MHD_ON == connection->sk_nodelay); dummy = 0; /* Mute compiler and analyzer warnings */ if (0 == MHD_send_ (connection->socket_fd, &dummy, 0)) return true; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Zero-send failed: %s\n"), MHD_socket_last_strerr_ () ); #endif /* HAVE_MESSAGES */ return false; } #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /** * Handle post-send setsockopt calls. * * @param connection the MHD_Connection structure * @param plain_send_next set to true if plain send() or sendmsg() will be * called next, * set to false if TLS socket send(), sendfile() or * writev() will be called next. * @param push_data whether to push data to the network from buffers */ static void post_send_setopt (struct MHD_Connection *connection, bool plain_send_next, bool push_data) { /* Try to buffer data if not sending the final piece. * Final piece is indicated by push_data == true. */ const bool buffer_data = (! push_data); if (_MHD_YES == connection->is_nonip) return; if (buffer_data) return; /* Nothing to do after send(). */ #ifndef MHD_USE_MSG_MORE (void) plain_send_next; /* Mute compiler warning */ #endif /* ! MHD_USE_MSG_MORE */ /* Need to push data. */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS #ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS #ifdef MHD_USE_MSG_MORE if (_MHD_OFF == connection->sk_corked) { if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ } /* This is Linux kernel. There are options: * * Push the data by setting of TCP_NODELAY (without change * of the cork on the socket), * * Push the data by resetting of TCP_CORK. * The optimal choice depends on the next final send functions * used on the same socket. If TCP_NODELAY wasn't set then push * data by setting TCP_NODELAY (TCP_NODELAY will not be removed * and is needed to push the data by send() without MSG_MORE). * If send()/sendmsg() will be used next than push data by * resetting of TCP_CORK so next send without MSG_MORE will push * data to the network (without additional sys-call to push data). * If next final send function will not support MSG_MORE (like * sendfile() or TLS-connection) than push data by setting * TCP_NODELAY so socket will remain corked (no additional * sys-call before next send()). */ if ((_MHD_ON != connection->sk_nodelay) || (! plain_send_next)) { if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data has been pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data has been pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ /* The socket cannot be uncorked, no way to push data */ } else { if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data has been pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data has been pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ /* The socket cannot be uncorked, no way to push data */ } #else /* ! MHD_USE_MSG_MORE */ /* Use setting of TCP_NODELAY here to avoid sys-call * for corking the socket during sending of the next response. */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data was pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data was pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ /* The socket remains corked, no way to push data */ #endif /* ! MHD_USE_MSG_MORE */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data was pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ return; /* Socket remains corked, no way to push data */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #else /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /* This is a typical *BSD or Darwin kernel. */ if (_MHD_OFF == connection->sk_corked) { if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ /* Unlikely to reach this code. * TCP_NODELAY should be turned on before send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) { /* TCP_NODELAY has been set on uncorked socket. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } /* Failed to push the data by all means. */ /* There is nothing left to try. */ } else { #ifdef _MHD_CORK_RESET_PUSH_DATA enum MHD_tristate old_cork_state = connection->sk_corked; #endif /* _MHD_CORK_RESET_PUSH_DATA */ /* The socket is corked or cork state is unknown. */ if (MHD_connection_set_cork_state_ (connection, false)) { #ifdef _MHD_CORK_RESET_PUSH_DATA /* FreeBSD kernel */ if (_MHD_OFF == old_cork_state) return; /* Data has been pushed by uncorking the socket. */ #endif /* _MHD_CORK_RESET_PUSH_DATA */ /* Unlikely to reach this code. * The data should be pushed by uncorking (FreeBSD) or * the socket should be uncorked before send(). */ if ((_MHD_ON == connection->sk_nodelay) || (MHD_connection_set_nodelay_state_ (connection, true))) { /* TCP_NODELAY is turned ON on uncorked socket. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } } /* The socket remains corked. Data cannot be pushed. */ } #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ #else /* ! MHD_TCP_CORK_NOPUSH */ /* Corking is not supported. Buffering is controlled * by TCP_NODELAY only. */ mhd_assert (_MHD_ON != connection->sk_corked); if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ /* Unlikely to reach this code. * TCP_NODELAY should be turned on before send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) { /* TCP_NODELAY has been set. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } /* Failed to push the data. */ #endif /* ! MHD_TCP_CORK_NOPUSH */ #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to push the data from buffers to the network. " "Client may experience some delay " "(usually in range 200ms - 5 sec).\n")); #endif /* HAVE_MESSAGES */ return; } ssize_t MHD_send_data_ (struct MHD_Connection *connection, const char *buffer, size_t buffer_size, bool push_data) { MHD_socket s = connection->socket_fd; ssize_t ret; #ifdef HTTPS_SUPPORT const bool tls_conn = (connection->daemon->options & MHD_USE_TLS); #else /* ! HTTPS_SUPPORT */ const bool tls_conn = false; #endif /* ! HTTPS_SUPPORT */ if ( (MHD_INVALID_SOCKET == s) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } if (buffer_size > SSIZE_MAX) { buffer_size = SSIZE_MAX; /* Max return value */ push_data = false; /* Incomplete send */ } if (tls_conn) { #ifdef HTTPS_SUPPORT pre_send_setopt (connection, (! tls_conn), push_data); ret = gnutls_record_send (connection->tls_session, buffer, buffer_size); if (GNUTLS_E_AGAIN == ret) { #ifdef EPOLL_SUPPORT connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif return MHD_ERR_AGAIN_; } if (GNUTLS_E_INTERRUPTED == ret) return MHD_ERR_AGAIN_; if ( (GNUTLS_E_ENCRYPTION_FAILED == ret) || (GNUTLS_E_INVALID_SESSION == ret) || (GNUTLS_E_COMPRESSION_FAILED == ret) || (GNUTLS_E_EXPIRED == ret) || (GNUTLS_E_HASH_FAILED == ret) ) return MHD_ERR_TLS_; if ( (GNUTLS_E_PUSH_ERROR == ret) || (GNUTLS_E_INTERNAL_ERROR == ret) || (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == ret) || (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == ret) ) return MHD_ERR_PIPE_; #if defined(GNUTLS_E_PREMATURE_TERMINATION) if (GNUTLS_E_PREMATURE_TERMINATION == ret) return MHD_ERR_CONNRESET_; #elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH) if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == ret) return MHD_ERR_CONNRESET_; #endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */ if (GNUTLS_E_MEMORY_ERROR == ret) return MHD_ERR_NOMEM_; if (ret < 0) { /* Treat any other error as hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT /* Unlike non-TLS connections, do not reset "write-ready" if * sent amount smaller than provided amount, as TLS * connections may break data into smaller parts for sending. */ #endif /* EPOLL_SUPPORT */ #else /* ! HTTPS_SUPPORT */ ret = MHD_ERR_NOTCONN_; #endif /* ! HTTPS_SUPPORT */ } else { /* plaintext transmission */ if (buffer_size > MHD_SCKT_SEND_MAX_SIZE_) { buffer_size = MHD_SCKT_SEND_MAX_SIZE_; /* send() return value limit */ push_data = false; /* Incomplete send */ } pre_send_setopt (connection, (! tls_conn), push_data); #ifdef MHD_USE_MSG_MORE ret = MHD_send4_ (s, buffer, buffer_size, push_data ? 0 : MSG_MORE); #else ret = MHD_send4_ (s, buffer, buffer_size, 0); #endif if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN, no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if (buffer_size > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ } /* If there is a need to push the data from network buffers * call post_send_setopt(). */ /* If TLS connection is used then next final send() will be * without MSG_MORE support. If non-TLS connection is used * it's unknown whether sendfile() will be used or not so * assume that next call will be the same, like this call. */ if ( (push_data) && (buffer_size == (size_t) ret) ) post_send_setopt (connection, (! tls_conn), push_data); return ret; } ssize_t MHD_send_hdr_and_body_ (struct MHD_Connection *connection, const char *header, size_t header_size, bool never_push_hdr, const char *body, size_t body_size, bool complete_response) { ssize_t ret; bool push_hdr; bool push_body; MHD_socket s = connection->socket_fd; #ifndef _WIN32 #define _MHD_SEND_VEC_MAX MHD_SCKT_SEND_MAX_SIZE_ #else /* ! _WIN32 */ #define _MHD_SEND_VEC_MAX UINT32_MAX #endif /* ! _WIN32 */ #ifdef MHD_VECT_SEND #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) struct iovec vector[2]; #ifdef HAVE_SENDMSG struct msghdr msg; #endif /* HAVE_SENDMSG */ #endif /* HAVE_SENDMSG || HAVE_WRITEV */ #ifdef _WIN32 WSABUF vector[2]; DWORD vec_sent; #endif /* _WIN32 */ bool no_vec; /* Is vector-send() disallowed? */ no_vec = false; #ifdef HTTPS_SUPPORT no_vec = no_vec || (connection->daemon->options & MHD_USE_TLS); #endif /* HTTPS_SUPPORT */ #if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL) ) && \ defined(MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE) && \ defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) no_vec = no_vec || (! connection->daemon->sigpipe_blocked && ! connection->sk_spipe_suppress); #endif /* (!HAVE_SENDMSG || ! MSG_NOSIGNAL) && MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE && MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #endif /* MHD_VECT_SEND */ mhd_assert ( (NULL != body) || (0 == body_size) ); if ( (MHD_INVALID_SOCKET == s) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } push_body = complete_response; if (! never_push_hdr) { if (! complete_response) push_hdr = true; /* Push the header as the client may react * on header alone while the body data is * being prepared. */ else { if (1400 > (header_size + body_size)) push_hdr = false; /* Do not push the header as complete * reply is already ready and the whole * reply most probably will fit into * the single IP packet. */ else push_hdr = true; /* Push header alone so client may react * on it while reply body is being delivered. */ } } else push_hdr = false; if (complete_response && (0 == body_size)) push_hdr = true; /* The header alone is equal to the whole response. */ if ( #ifdef MHD_VECT_SEND (no_vec) || (0 == body_size) || ((size_t) SSIZE_MAX <= header_size) || ((size_t) _MHD_SEND_VEC_MAX < header_size) #ifdef _WIN32 || ((size_t) UINT_MAX < header_size) #endif /* _WIN32 */ #else /* ! MHD_VECT_SEND */ true #endif /* ! MHD_VECT_SEND */ ) { ret = MHD_send_data_ (connection, header, header_size, push_hdr); if ( (header_size == (size_t) ret) && ((size_t) SSIZE_MAX > header_size) && (0 != body_size) && (connection->sk_nonblck) ) { ssize_t ret2; /* The header has been sent completely. * Try to send the reply body without waiting for * the next round. */ /* Make sure that sum of ret + ret2 will not exceed SSIZE_MAX as * function needs to return positive value if succeed. */ if ( (((size_t) SSIZE_MAX) - ((size_t) ret)) < body_size) { body_size = (((size_t) SSIZE_MAX) - ((size_t) ret)); complete_response = false; push_body = complete_response; } ret2 = MHD_send_data_ (connection, body, body_size, push_body); if (0 < ret2) return ret + ret2; /* Total data sent */ if (MHD_ERR_AGAIN_ == ret2) return ret; return ret2; /* Error code */ } return ret; } #ifdef MHD_VECT_SEND if ( ((size_t) SSIZE_MAX <= body_size) || ((size_t) SSIZE_MAX < (header_size + body_size)) ) { /* Return value limit */ body_size = SSIZE_MAX - header_size; complete_response = false; push_body = complete_response; } #if (SSIZE_MAX != _MHD_SEND_VEC_MAX) || (_MHD_SEND_VEC_MAX + 0 == 0) if (((size_t) _MHD_SEND_VEC_MAX <= body_size) || ((size_t) _MHD_SEND_VEC_MAX < (header_size + body_size))) { /* Send total amount limit */ body_size = _MHD_SEND_VEC_MAX - header_size; complete_response = false; push_body = complete_response; } #endif /* SSIZE_MAX != _MHD_SEND_VEC_MAX */ pre_send_setopt (connection, #ifdef HAVE_SENDMSG true, #else /* ! HAVE_SENDMSG */ false, #endif /* ! HAVE_SENDMSG */ push_hdr || push_body); #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) vector[0].iov_base = _MHD_DROP_CONST (header); vector[0].iov_len = header_size; vector[1].iov_base = _MHD_DROP_CONST (body); vector[1].iov_len = body_size; #if defined(HAVE_SENDMSG) memset (&msg, 0, sizeof(msg)); msg.msg_iov = vector; msg.msg_iovlen = 2; ret = sendmsg (s, &msg, MSG_NOSIGNAL_OR_ZERO); #elif defined(HAVE_WRITEV) ret = writev (s, vector, 2); #endif /* HAVE_WRITEV */ #endif /* HAVE_SENDMSG || HAVE_WRITEV */ #ifdef _WIN32 if ((size_t) UINT_MAX < body_size) { /* Send item size limit */ body_size = UINT_MAX; complete_response = false; push_body = complete_response; } vector[0].buf = (char *) _MHD_DROP_CONST (header); vector[0].len = (unsigned long) header_size; vector[1].buf = (char *) _MHD_DROP_CONST (body); vector[1].len = (unsigned long) body_size; ret = WSASend (s, vector, 2, &vec_sent, 0, NULL, NULL); if (0 == ret) ret = (ssize_t) vec_sent; else ret = -1; #endif /* _WIN32 */ if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN, no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if ((header_size + body_size) > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ /* If there is a need to push the data from network buffers * call post_send_setopt(). */ if ( (push_body) && ((header_size + body_size) == (size_t) ret) ) { /* Complete reply has been sent. */ /* If TLS connection is used then next final send() will be * without MSG_MORE support. If non-TLS connection is used * it's unknown whether next 'send' will be plain send() / sendmsg() or * sendfile() will be used so assume that next final send() will be * the same, like for this response. */ post_send_setopt (connection, #ifdef HAVE_SENDMSG true, #else /* ! HAVE_SENDMSG */ false, #endif /* ! HAVE_SENDMSG */ true); } else if ( (push_hdr) && (header_size <= (size_t) ret)) { /* The header has been sent completely and there is a * need to push the header data. */ /* Luckily the type of send function will be used next is known. */ post_send_setopt (connection, #if defined(_MHD_HAVE_SENDFILE) MHD_resp_sender_std == connection->rp.resp_sender, #else /* ! _MHD_HAVE_SENDFILE */ true, #endif /* ! _MHD_HAVE_SENDFILE */ true); } return ret; #else /* ! MHD_VECT_SEND */ mhd_assert (false); return MHD_ERR_CONNRESET_; /* Unreachable. Mute warnings. */ #endif /* ! MHD_VECT_SEND */ } #if defined(_MHD_HAVE_SENDFILE) ssize_t MHD_send_sendfile_ (struct MHD_Connection *connection) { ssize_t ret; const int file_fd = connection->rp.response->fd; uint64_t left; uint64_t offsetu64; #ifndef HAVE_SENDFILE64 const uint64_t max_off_t = (uint64_t) OFF_T_MAX; #else /* HAVE_SENDFILE64 */ const uint64_t max_off_t = (uint64_t) OFF64_T_MAX; #endif /* HAVE_SENDFILE64 */ #ifdef MHD_LINUX_SOLARIS_SENDFILE #ifndef HAVE_SENDFILE64 off_t offset; #else /* HAVE_SENDFILE64 */ off64_t offset; #endif /* HAVE_SENDFILE64 */ #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #ifdef HAVE_FREEBSD_SENDFILE off_t sent_bytes; int flags = 0; #endif #ifdef HAVE_DARWIN_SENDFILE off_t len; #endif /* HAVE_DARWIN_SENDFILE */ const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (connection->daemon); const size_t chunk_size = used_thr_p_c ? MHD_SENFILE_CHUNK_THR_P_C_ : MHD_SENFILE_CHUNK_; size_t send_size = 0; bool push_data; mhd_assert (MHD_resp_sender_sendfile == connection->rp.resp_sender); mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS)); offsetu64 = connection->rp.rsp_write_position + connection->rp.response->fd_off; if (max_off_t < offsetu64) { /* Retry to send with standard 'send()'. */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } left = connection->rp.response->total_size - connection->rp.rsp_write_position; if ( (uint64_t) SSIZE_MAX < left) left = SSIZE_MAX; /* Do not allow system to stick sending on single fast connection: * use 128KiB chunks (2MiB for thread-per-connection). */ if (chunk_size < left) { send_size = chunk_size; push_data = false; /* No need to push data, there is more to send. */ } else { send_size = (size_t) left; push_data = true; /* Final piece of data, need to push to the network. */ } pre_send_setopt (connection, false, push_data); #ifdef MHD_LINUX_SOLARIS_SENDFILE #ifndef HAVE_SENDFILE64 offset = (off_t) offsetu64; ret = sendfile (connection->socket_fd, file_fd, &offset, send_size); #else /* HAVE_SENDFILE64 */ offset = (off64_t) offsetu64; ret = sendfile64 (connection->socket_fd, file_fd, &offset, send_size); #endif /* HAVE_SENDFILE64 */ if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN --- no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; #ifdef HAVE_LINUX_SENDFILE if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* sendfile() failed with EINVAL if mmap()-like operations are not supported for FD or other 'unusual' errors occurred, so we should try to fall back to 'SEND'; see also this thread for info on odd libc/Linux behavior with sendfile: http://lists.gnu.org/archive/html/libmicrohttpd/2011-02/msg00015.html */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; #else /* HAVE_SOLARIS_SENDFILE */ if ( (EAFNOSUPPORT == err) || (EINVAL == err) || (EOPNOTSUPP == err) ) { /* Retry with standard file reader. */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } if ( (ENOTCONN == err) || (EPIPE == err) ) { return MHD_ERR_CONNRESET_; } return MHD_ERR_BADF_; /* Fail hard */ #endif /* HAVE_SOLARIS_SENDFILE */ } #ifdef EPOLL_SUPPORT else if (send_size > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ #elif defined(HAVE_FREEBSD_SENDFILE) #ifdef SF_FLAGS flags = used_thr_p_c ? freebsd_sendfile_flags_thd_p_c_ : freebsd_sendfile_flags_; #endif /* SF_FLAGS */ if (0 != sendfile (file_fd, connection->socket_fd, (off_t) offsetu64, send_size, NULL, &sent_bytes, flags)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err) || MHD_SCKT_ERR_IS_EINTR_ (err) || (EBUSY == err) ) { mhd_assert (SSIZE_MAX >= sent_bytes); if (0 != sent_bytes) return (ssize_t) sent_bytes; return MHD_ERR_AGAIN_; } /* Some unrecoverable error. Possibly file FD is not suitable * for sendfile(). Retry with standard send(). */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } mhd_assert (0 < sent_bytes); mhd_assert (SSIZE_MAX >= sent_bytes); ret = (ssize_t) sent_bytes; #elif defined(HAVE_DARWIN_SENDFILE) len = (off_t) send_size; /* chunk always fit */ if (0 != sendfile (file_fd, connection->socket_fd, (off_t) offsetu64, &len, NULL, 0)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err) || MHD_SCKT_ERR_IS_EINTR_ (err)) { mhd_assert (0 <= len); mhd_assert (SSIZE_MAX >= len); mhd_assert (send_size >= (size_t) len); if (0 != len) return (ssize_t) len; return MHD_ERR_AGAIN_; } if ((ENOTCONN == err) || (EPIPE == err) ) return MHD_ERR_CONNRESET_; if ((ENOTSUP == err) || (EOPNOTSUPP == err) ) { /* This file FD is not suitable for sendfile(). * Retry with standard send(). */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } return MHD_ERR_BADF_; /* Return hard error. */ } mhd_assert (0 <= len); mhd_assert (SSIZE_MAX >= len); mhd_assert (send_size >= (size_t) len); ret = (ssize_t) len; #endif /* HAVE_FREEBSD_SENDFILE */ /* If there is a need to push the data from network buffers * call post_send_setopt(). */ /* It's unknown whether sendfile() will be used in the next * response so assume that next response will be the same. */ if ( (push_data) && (send_size == (size_t) ret) ) post_send_setopt (connection, false, push_data); return ret; } #endif /* _MHD_HAVE_SENDFILE */ #if defined(MHD_VECT_SEND) /** * Function sends iov data by system sendmsg or writev function. * * Connection must be in non-TLS (non-HTTPS) mode. * * @param connection the MHD connection structure * @param r_iov the pointer to iov data structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ static ssize_t send_iov_nontls (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { ssize_t res; size_t items_to_send; #ifdef HAVE_SENDMSG struct msghdr msg; #elif defined(MHD_WINSOCK_SOCKETS) DWORD bytes_sent; DWORD cnt_w; #endif /* MHD_WINSOCK_SOCKETS */ mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS)); if ( (MHD_INVALID_SOCKET == connection->socket_fd) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } items_to_send = r_iov->cnt - r_iov->sent; #ifdef _MHD_IOV_MAX if (_MHD_IOV_MAX < items_to_send) { mhd_assert (0 < _MHD_IOV_MAX); if (0 == _MHD_IOV_MAX) return MHD_ERR_NOTCONN_; /* Should never happen */ items_to_send = _MHD_IOV_MAX; push_data = false; /* Incomplete response */ } #endif /* _MHD_IOV_MAX */ #ifdef HAVE_SENDMSG memset (&msg, 0, sizeof(struct msghdr)); msg.msg_iov = r_iov->iov + r_iov->sent; msg.msg_iovlen = items_to_send; pre_send_setopt (connection, true, push_data); #ifdef MHD_USE_MSG_MORE res = sendmsg (connection->socket_fd, &msg, MSG_NOSIGNAL_OR_ZERO | (push_data ? 0 : MSG_MORE)); #else /* ! MHD_USE_MSG_MORE */ res = sendmsg (connection->socket_fd, &msg, MSG_NOSIGNAL_OR_ZERO); #endif /* ! MHD_USE_MSG_MORE */ #elif defined(HAVE_WRITEV) pre_send_setopt (connection, true, push_data); res = writev (connection->socket_fd, r_iov->iov + r_iov->sent, items_to_send); #elif defined(MHD_WINSOCK_SOCKETS) #ifdef _WIN64 if (items_to_send > UINT32_MAX) { cnt_w = UINT32_MAX; push_data = false; /* Incomplete response */ } else cnt_w = (DWORD) items_to_send; #else /* ! _WIN64 */ cnt_w = (DWORD) items_to_send; #endif /* ! _WIN64 */ pre_send_setopt (connection, true, push_data); if (0 == WSASend (connection->socket_fd, (LPWSABUF) (r_iov->iov + r_iov->sent), cnt_w, &bytes_sent, 0, NULL, NULL)) res = (ssize_t) bytes_sent; else res = -1; #else /* !HAVE_SENDMSG && !HAVE_WRITEV && !MHD_WINSOCK_SOCKETS */ #error No vector-send function available #endif if (0 > res) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN --- no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } /* Some data has been sent */ if (1) { size_t track_sent = (size_t) res; /* Adjust the internal tracking information for the iovec to * take this last send into account. */ while ((0 != track_sent) && (r_iov->iov[r_iov->sent].iov_len <= track_sent)) { track_sent -= r_iov->iov[r_iov->sent].iov_len; r_iov->sent++; /* The iov element has been completely sent */ mhd_assert ((r_iov->cnt > r_iov->sent) || (0 == track_sent)); } if (r_iov->cnt == r_iov->sent) post_send_setopt (connection, true, push_data); else { #ifdef EPOLL_SUPPORT connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ if (0 != track_sent) { mhd_assert (r_iov->cnt > r_iov->sent); /* The last iov element has been partially sent */ r_iov->iov[r_iov->sent].iov_base = (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + track_sent); r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) track_sent; } } } return res; } #endif /* MHD_VECT_SEND */ #if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) /** * Function sends iov data by sending buffers one-by-one by standard * data send function. * * Connection could be in HTTPS or non-HTTPS mode. * * @param connection the MHD connection structure * @param r_iov the pointer to iov data structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ static ssize_t send_iov_emu (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { const bool non_blk = connection->sk_nonblck; size_t total_sent; ssize_t res; mhd_assert (NULL != r_iov->iov); total_sent = 0; do { if ((size_t) SSIZE_MAX - total_sent < r_iov->iov[r_iov->sent].iov_len) return (ssize_t) total_sent; /* return value would overflow */ res = MHD_send_data_ (connection, r_iov->iov[r_iov->sent].iov_base, r_iov->iov[r_iov->sent].iov_len, push_data && (r_iov->cnt == r_iov->sent + 1)); if (0 > res) { /* Result is an error */ if (0 == total_sent) return res; /* Nothing was sent, return result as is */ if (MHD_ERR_AGAIN_ == res) return (ssize_t) total_sent; /* Return the amount of the sent data */ return res; /* Any kind of a hard error */ } total_sent += (size_t) res; if (r_iov->iov[r_iov->sent].iov_len != (size_t) res) { const size_t sent = (size_t) res; /* Incomplete buffer has been sent. * Adjust buffer of the last element. */ r_iov->iov[r_iov->sent].iov_base = (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + sent); r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) sent; return (ssize_t) total_sent; } /* The iov element has been completely sent */ r_iov->sent++; } while ((r_iov->cnt > r_iov->sent) && (non_blk)); return (ssize_t) total_sent; } #endif /* !MHD_VECT_SEND || HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ ssize_t MHD_send_iovec_ (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { #ifdef MHD_VECT_SEND #if defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) bool use_iov_send = true; #endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ #endif /* MHD_VECT_SEND */ mhd_assert (NULL != connection->rp.resp_iov.iov); mhd_assert (NULL != connection->rp.response->data_iov); mhd_assert (connection->rp.resp_iov.cnt > connection->rp.resp_iov.sent); #ifdef MHD_VECT_SEND #if defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) #ifdef HTTPS_SUPPORT use_iov_send = use_iov_send && (0 == (connection->daemon->options & MHD_USE_TLS)); #endif /* HTTPS_SUPPORT */ #ifdef _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED use_iov_send = use_iov_send && (connection->daemon->sigpipe_blocked || connection->sk_spipe_suppress); #endif /* _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ if (use_iov_send) #endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ return send_iov_nontls (connection, r_iov, push_data); #endif /* MHD_VECT_SEND */ #if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) return send_iov_emu (connection, r_iov, push_data); #endif /* !MHD_VECT_SEND || HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ } libmicrohttpd-1.0.2/src/microhttpd/sha256.h0000644000175000017500000000610415035214301015417 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha256.h * @brief Calculation of SHA-256 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_H #define MHD_SHA256_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Digest is kept internally as 8 32-bit words. */ #define SHA256_DIGEST_SIZE_WORDS 8 /** * Number of bits in single SHA-256 word */ #define SHA256_WORD_SIZE_BITS 32 /** * Number of bytes in single SHA-256 word * used to process data */ #define SHA256_BYTES_IN_WORD (SHA256_WORD_SIZE_BITS / 8) /** * Size of SHA-256 digest in bytes */ #define SHA256_DIGEST_SIZE (SHA256_DIGEST_SIZE_WORDS * SHA256_BYTES_IN_WORD) /** * Size of SHA-256 digest string in chars including termination NUL */ #define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1) /** * Size of single processing block in bits */ #define SHA256_BLOCK_SIZE_BITS 512 /** * Size of single processing block in bytes */ #define SHA256_BLOCK_SIZE (SHA256_BLOCK_SIZE_BITS / 8) /** * Size of single processing block in bytes */ #define SHA256_BLOCK_SIZE_WORDS (SHA256_BLOCK_SIZE_BITS / SHA256_WORD_SIZE_BITS) struct Sha256Ctx { uint32_t H[SHA256_DIGEST_SIZE_WORDS]; /**< Intermediate hash value / digest at end of calculation */ uint32_t buffer[SHA256_BLOCK_SIZE_WORDS]; /**< SHA256 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for SHA256 calculation. * * @param ctx must be a `struct Sha256Ctx *` */ void MHD_SHA256_init (struct Sha256Ctx *ctx); /** * Process portion of bytes. * * @param ctx must be a `struct Sha256Ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise SHA256 calculation, return digest. * * @param ctx must be a `struct Sha256Ctx *` * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish (struct Sha256Ctx *ctx, uint8_t digest[SHA256_DIGEST_SIZE]); /** * Indicates that function MHD_SHA256_finish() (without context reset) is available */ #define MHD_SHA256_HAS_FINISH 1 #endif /* MHD_SHA256_H */ libmicrohttpd-1.0.2/src/microhttpd/md5_ext.c0000644000175000017500000000546215035214301015755 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/md5_ext.c * @brief Wrapper for MD5 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #include #include "md5_ext.h" #include "mhd_assert.h" /** * Initialise structure for MD5 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_MD5_init_one_time (struct Md5CtxExt *ctx) { ctx->handle = NULL; ctx->ext_error = gnutls_hash_init (&ctx->handle, GNUTLS_DIG_MD5); if ((0 != ctx->ext_error) && (NULL != ctx->handle)) { /* GnuTLS may return initialisation error and set the handle at the same time. Such handle cannot be used for calculations. Note: GnuTLS may also return an error and NOT set the handle. */ gnutls_free (ctx->handle); ctx->handle = NULL; } /* If handle is NULL, the error must be set */ mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error)); /* If error is set, the handle must be NULL */ mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle)); } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5CtxExt *ctx, const uint8_t *data, size_t length) { if (0 == ctx->ext_error) ctx->ext_error = gnutls_hash (ctx->handle, data, length); } /** * Finalise MD5 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish_reset (struct Md5CtxExt *ctx, uint8_t digest[MD5_DIGEST_SIZE]) { if (0 == ctx->ext_error) gnutls_hash_output (ctx->handle, digest); } /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_MD5_deinit (struct Md5CtxExt *ctx) { if (NULL != ctx->handle) gnutls_hash_deinit (ctx->handle, NULL); } libmicrohttpd-1.0.2/src/microhttpd/mhd_locks.h0000644000175000017500000001375414760713577016412 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_locks.h * @brief Header for platform-independent locks abstraction * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic abstraction for locks/mutex. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. * * @warning Unlike pthread functions, most of functions return * nonzero on success. */ #ifndef MHD_LOCKS_H #define MHD_LOCKS_H 1 #include "mhd_options.h" #ifdef MHD_USE_THREADS #if defined(MHD_USE_W32_THREADS) # define MHD_W32_MUTEX_ 1 # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include #elif defined(HAVE_PTHREAD_H) && defined(MHD_USE_POSIX_THREADS) # define MHD_PTHREAD_MUTEX_ 1 # undef HAVE_CONFIG_H # include # define HAVE_CONFIG_H 1 #else # error No base mutex API is available. #endif #ifndef MHD_PANIC # include # ifdef HAVE_STDLIB_H # include # endif /* HAVE_STDLIB_H */ /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #if defined(MHD_PTHREAD_MUTEX_) typedef pthread_mutex_t MHD_mutex_; #elif defined(MHD_W32_MUTEX_) typedef CRITICAL_SECTION MHD_mutex_; #endif #if defined(MHD_PTHREAD_MUTEX_) /** * Initialise new mutex. * @param pmutex pointer to the mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_init_(pmutex) (! (pthread_mutex_init ((pmutex), NULL))) #elif defined(MHD_W32_MUTEX_) /** * Initialise new mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_init_(pmutex) \ (InitializeCriticalSectionAndSpinCount ((pmutex),16)) #endif #if defined(MHD_PTHREAD_MUTEX_) # if defined(PTHREAD_MUTEX_INITIALIZER) /** * Define static mutex and statically initialise it. */ # define MHD_MUTEX_STATIC_DEFN_INIT_(m) \ static MHD_mutex_ m = PTHREAD_MUTEX_INITIALIZER # endif /* PTHREAD_MUTEX_INITIALIZER */ #endif #if defined(MHD_PTHREAD_MUTEX_) /** * Destroy previously initialised mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_destroy_(pmutex) (! (pthread_mutex_destroy ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Destroy previously initialised mutex. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_destroy_(pmutex) (DeleteCriticalSection ((pmutex)), ! 0) #endif /** * Destroy previously initialised mutex and abort execution * if error is detected. * @param pmutex pointer to mutex */ #define MHD_mutex_destroy_chk_(pmutex) do { \ if (! MHD_mutex_destroy_ (pmutex)) \ MHD_PANIC (_ ("Failed to destroy mutex.\n")); \ } while (0) #if defined(MHD_PTHREAD_MUTEX_) /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_lock_(pmutex) (! (pthread_mutex_lock ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_lock_(pmutex) (EnterCriticalSection ((pmutex)), ! 0) #endif /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * If error is detected, execution will be aborted. * @param pmutex pointer to mutex */ #define MHD_mutex_lock_chk_(pmutex) do { \ if (! MHD_mutex_lock_ (pmutex)) \ MHD_PANIC (_ ("Failed to lock mutex.\n")); \ } while (0) #if defined(MHD_PTHREAD_MUTEX_) /** * Unlock previously initialised and locked mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_unlock_(pmutex) (! (pthread_mutex_unlock ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Unlock previously initialised and locked mutex. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_unlock_(pmutex) (LeaveCriticalSection ((pmutex)), ! 0) #endif /** * Unlock previously initialised and locked mutex. * If error is detected, execution will be aborted. * @param pmutex pointer to mutex */ #define MHD_mutex_unlock_chk_(pmutex) do { \ if (! MHD_mutex_unlock_ (pmutex)) \ MHD_PANIC (_ ("Failed to unlock mutex.\n")); \ } while (0) #else /* ! MHD_USE_THREADS */ #define MHD_mutex_init_(ignore) (! 0) #define MHD_mutex_destroy_(ignore) (! 0) #define MHD_mutex_destroy_chk_(ignore) (void)0 #define MHD_mutex_lock_(ignore) (! 0) #define MHD_mutex_lock_chk_(ignore) (void)0 #define MHD_mutex_unlock_(ignore) (! 0) #define MHD_mutex_unlock_chk_(ignore) (void)0 #endif /* ! MHD_USE_THREADS */ #endif /* ! MHD_LOCKS_H */ libmicrohttpd-1.0.2/src/microhttpd/test_options.c0000644000175000017500000001743414760713574017170 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_options.c * @brief Testcase for libmicrohttpd HTTPS GET operations * @author Sagie Amir */ #include "platform.h" #include "microhttpd.h" #include "mhd_sockets.h" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; (void) req_cls; return 0; } static unsigned int test_wrap_loc (const char *test_name, unsigned int (*test)(void)) { unsigned int ret; fprintf (stdout, "running test: %s ", test_name); ret = test (); if (ret == 0) { fprintf (stdout, "[pass]\n"); } else { fprintf (stdout, "[fail]\n"); } return ret; } /** * Test daemon initialization with the MHD_OPTION_SOCK_ADDR or * the MHD_OPTION_SOCK_ADDR_LEN options */ static unsigned int test_ip_addr_option (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; struct sockaddr_in daemon_ip_addr; uint16_t port4; #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) struct sockaddr_in6 daemon_ip_addr6; uint16_t port6; #endif unsigned int ret; memset (&daemon_ip_addr, 0, sizeof (struct sockaddr_in)); daemon_ip_addr.sin_family = AF_INET; daemon_ip_addr.sin_port = 0; daemon_ip_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); port4 = 0; #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) memset (&daemon_ip_addr6, 0, sizeof (struct sockaddr_in6)); daemon_ip_addr6.sin6_family = AF_INET6; daemon_ip_addr6.sin6_port = 0; daemon_ip_addr6.sin6_addr = in6addr_loopback; port6 = 0; #endif ret = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else port4 = dinfo->port; MHD_stop_daemon (d); daemon_ip_addr.sin_port = htons (port4); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port4 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) (sizeof(daemon_ip_addr) / 2), &daemon_ip_addr, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN daemon_ip_addr.sin_len = (socklen_t) sizeof(daemon_ip_addr); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port4 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); daemon_ip_addr.sin_len = (socklen_t) (sizeof(daemon_ip_addr) / 2); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_IPv6 | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else port6 = dinfo->port; MHD_stop_daemon (d); daemon_ip_addr6.sin6_port = htons (port6); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port6 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) (sizeof(daemon_ip_addr6) / 2), &daemon_ip_addr6, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #if defined(HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN) daemon_ip_addr6.sin6_len = (socklen_t) sizeof(daemon_ip_addr6); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port6 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); daemon_ip_addr6.sin6_len = (socklen_t) (sizeof(daemon_ip_addr6) / 2); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #endif /* HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */ #endif /* HAVE_INET6 && USE_IPV6_TESTING */ return ret; } /* setup a temporary transfer test file */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_wrap_loc ("ip addr option", &test_ip_addr_option); return errorCount != 0; } libmicrohttpd-1.0.2/src/microhttpd/test_str.c0000644000175000017500000046242414760713574016310 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/unit_str_test.h * @brief Unit tests for mhd_str functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #ifdef HAVE_INTTYPES_H #include #else /* ! HAVE_INTTYPES_H */ #define PRIu64 "llu" #define PRIuPTR "u" #define PRIX64 "llX" #endif /* ! HAVE_INTTYPES_H */ #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "mhd_limits.h" #include "mhd_str.h" #include "test_helpers.h" static int verbose = 0; /* verbose level (0-3)*/ /* Locale names to test. * Functions must not depend of current current locale, * so result must be the same in any locale. */ static const char *const locale_names[] = { "C", "", /* System default locale */ #if defined(_WIN32) && ! defined(__CYGWIN__) ".OCP", /* W32 system default OEM code page */ ".ACP", /* W32 system default ANSI code page */ ".65001", /* UTF-8 */ ".437", ".850", ".857", ".866", ".1250", ".1251", ".1252", "en", "english", "French_France", "Turkish_Turkey.1254", "de", "zh-Hans", "ru-RU.1251" #if 0 /* Disabled extra checks */ , ".1254", ".20866", /* number for KOI8-R */ ".28591", /* number for ISO-8859-1 */ ".28595", /* number for ISO-8859-5 */ ".28599", /* number for ISO-8859-9 */ ".28605", /* number for ISO-8859-15 */ "en-US", "English-US", "en-US.437", "English_United States.437", "en-US.1252", "English_United States.1252", "English_United States.28591", "English_United States.65001", "fra", "french", "fr-FR", "fr-FR.850", "french_france.850", "fr-FR.1252", "French_france.1252", "French_france.28605", "French_France.65001", "de-DE", "de-DE.850", "German_Germany.850", "German_Germany.1250", "de-DE.1252", "German_Germany.1252", "German_Germany.28605", "German_Germany.65001", "tr", "trk", "turkish", "tr-TR", "tr-TR.1254", "tr-TR.857", "Turkish_Turkey.857", "Turkish_Turkey.28599", "Turkish_Turkey.65001", "ru", "ru-RU", "Russian", "ru-RU.866", "Russian_Russia.866", "Russian_Russia.1251", "Russian_Russia.20866", "Russian_Russia.28595", "Russian_Russia.65001", "zh-Hans.936", "chinese-simplified" #endif /* Disabled extra checks */ #else /* ! _WIN32 || __CYGWIN__ */ "C.UTF-8", "POSIX", "en", "en_US", "en_US.ISO-8859-1", "en_US.ISO_8859-1", "en_US.ISO8859-1", "en_US.iso88591", "en_US.ISO-8859-15", "en_US.DIS_8859-15", "en_US.ISO8859-15", "en_US.iso885915", "en_US.1252", "en_US.CP1252", "en_US.UTF-8", "en_US.utf8", "fr", "fr_FR", "fr_FR.850", "fr_FR.IBM850", "fr_FR.1252", "fr_FR.CP1252", "fr_FR.ISO-8859-1", "fr_FR.ISO_8859-1", "fr_FR.ISO8859-1", "fr_FR.iso88591", "fr_FR.ISO-8859-15", "fr_FR.DIS_8859-15", "fr_FR.ISO8859-15", "fr_FR.iso8859-15", "fr_FR.UTF-8", "fr_FR.utf8", "de", "de_DE", "de_DE.850", "de_DE.IBM850", "de_DE.1250", "de_DE.CP1250", "de_DE.1252", "de_DE.CP1252", "de_DE.ISO-8859-1", "de_DE.ISO_8859-1", "de_DE.ISO8859-1", "de_DE.iso88591", "de_DE.ISO-8859-15", "de_DE.DIS_8859-15", "de_DE.ISO8859-15", "de_DE.iso885915", "de_DE.UTF-8", "de_DE.utf8", "tr", "tr_TR", "tr_TR.1254", "tr_TR.CP1254", "tr_TR.857", "tr_TR.IBM857", "tr_TR.ISO-8859-9", "tr_TR.ISO8859-9", "tr_TR.iso88599", "tr_TR.UTF-8", "tr_TR.utf8", "ru", "ru_RU", "ru_RU.1251", "ru_RU.CP1251", "ru_RU.866", "ru_RU.IBM866", "ru_RU.KOI8-R", "ru_RU.koi8-r", "ru_RU.KOI8-RU", "ru_RU.ISO-8859-5", "ru_RU.ISO_8859-5", "ru_RU.ISO8859-5", "ru_RU.iso88595", "ru_RU.UTF-8", "zh_CN", "zh_CN.GB2312", "zh_CN.UTF-8", #endif /* ! _WIN32 || __CYGWIN__ */ }; static const unsigned int locale_name_count = sizeof(locale_names) / sizeof(locale_names[0]); /* * Helper functions */ static int set_test_locale (size_t num) { if (num >= locale_name_count) { fprintf (stderr, "Unexpected number of locale.\n"); exit (99); } if (verbose > 2) printf ("Setting locale \"%s\":", locale_names[num]); if (setlocale (LC_ALL, locale_names[num])) { if (verbose > 2) printf (" succeed.\n"); return 1; } if (verbose > 2) printf (" failed.\n"); return 0; } static const char * get_current_locale_str (void) { char const *loc_str = setlocale (LC_ALL, NULL); return loc_str ? loc_str : "unknown"; } static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); const unsigned char *p = (const unsigned char *) str; size_t w_pos = 0; if (++buf_idx > 3) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (*p && w_pos + 1 < buf_size) { const unsigned char c = *p; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } p++; } if (*p) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} /* * String caseless equality functions tests */ struct two_eq_strs { const struct str_with_len s1; const struct str_with_len s2; }; static const struct two_eq_strs eq_strings[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`.")}, {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple string.")}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("SIMPLE STRING.")}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string.")}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("Simple String.")}, {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SiMpLe sTrInG.")}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.")}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz")}, {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), D_STR_W_LEN ("ZYXWVUTSRQPONmlkjihgfedcba")}, {D_STR_W_LEN ("Cha\x8cne pour le test."), D_STR_W_LEN ("Cha\x8cne pour le test.")}, /* "Chaîne pour le test." in CP850 */ {D_STR_W_LEN ("cha\x8cne pOur Le TEst."), D_STR_W_LEN ("Cha\x8cne poUr Le teST.")}, {D_STR_W_LEN ("Cha\xeene pour le test."), D_STR_W_LEN ("Cha\xeene pour le test.")}, /* "Chaîne pour le test." in CP1252/ISO-8859-1/ISO-8859-15 */ {D_STR_W_LEN ("CHa\xeene POUR le test."), D_STR_W_LEN ("Cha\xeeNe pour lE TEST.")}, {D_STR_W_LEN ("Cha\xc3\xaene pour le Test."), D_STR_W_LEN ("Cha\xc3\xaene pour le Test.")}, /* "Chaîne pour le test." in UTF-8 */ {D_STR_W_LEN ("ChA\xc3\xaene pouR lE TesT."), D_STR_W_LEN ("Cha\xc3\xaeNe Pour le teSt.")}, {D_STR_W_LEN (".Beispiel Zeichenfolge"), D_STR_W_LEN (".Beispiel Zeichenfolge")}, {D_STR_W_LEN (".bEisPiel ZEIchenfoLgE"), D_STR_W_LEN (".BEiSpiEl zeIcheNfolge")}, {D_STR_W_LEN ("Do\xa7rulama \x87izgi!"), D_STR_W_LEN ("Do\xa7rulama \x87izgi!")}, /* "DoÄŸrulama çizgi!" in CP857 */ {D_STR_W_LEN ("Do\xa7rulama \x87IzgI!"), /* Spelling intentionally incorrect here */ D_STR_W_LEN ("Do\xa7rulama \x87izgi!")}, /* Note: 'i' is not caseless equal to 'I' in Turkish */ {D_STR_W_LEN ("Do\xf0rulama \xe7izgi!"), D_STR_W_LEN ("Do\xf0rulama \xe7izgi!")}, /* "DoÄŸrulama çizgi!" in CP1254/ISO-8859-9 */ {D_STR_W_LEN ("Do\xf0rulamA \xe7Izgi!"), D_STR_W_LEN ("do\xf0rulama \xe7izgi!")}, {D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!"), D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!")}, /* "DoÄŸrulama çizgi!" in UTF-8 */ {D_STR_W_LEN ("do\xc4\x9fruLAMA \xc3\xa7Izgi!"), /* Spelling intentionally incorrect here */ D_STR_W_LEN ("DO\xc4\x9frulama \xc3\xa7izgI!")}, /* Spelling intentionally incorrect here */ {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."), D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0.")}, /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in CP866 */ {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."), D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0.")}, /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in CP1251 */ {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."), D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1.")}, /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in KOI8-R */ {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."), D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0.")}, /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in ISO-8859-5 */ {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."), D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0.")}, /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in UTF-8 */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]" "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4" "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8" "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc" "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4" "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"), D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]" "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4" "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8" "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc" "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4" "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")}, /* Full sequence without a-z */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83" "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97" "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab" "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7" "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"), D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83" "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97" "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab" "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7" "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff")}, /* Full sequence */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89" "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d" "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1" "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5" "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9" "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed" "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff") , D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ab" "cdefghijklmnopqrstuvwxyz[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89" "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d" "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1" "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5" "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9" "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed" "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff") } /* Full with A/a match */ }; struct two_neq_strs { const struct str_with_len s1; const struct str_with_len s2; const size_t dif_pos; }; static const struct two_neq_strs neq_strings[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 27}, {D_STR_W_LEN (".1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 0}, {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple ctring."), 7}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string"), 13}, {D_STR_W_LEN ("simple strings"), D_STR_W_LEN ("Simple String."), 13}, {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SYMpLe sTrInG."), 1}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.2"), 14}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz,"), D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz."), 26}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz!"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ?"), 26}, {D_STR_W_LEN ("zyxwvutsrqponwMLKJIHGFEDCBA"), D_STR_W_LEN ("ZYXWVUTSRQPON%mlkjihgfedcba"), 13}, {D_STR_W_LEN ("S\xbdur veulent plus d'\xbdufs."), /* "SÅ“ur veulent plus d'Å“ufs." in ISO-8859-15 */ D_STR_W_LEN ("S\xbcUR VEULENT PLUS D'\xbcUFS."), 1}, /* "SÅ’UR VEULENT PLUS D'Å’UFS." in ISO-8859-15 */ {D_STR_W_LEN ("S\x9cur veulent plus d'\x9cufs."), /* "SÅ“ur veulent plus d'Å“ufs." in CP1252 */ D_STR_W_LEN ("S\x8cUR VEULENT PLUS D'\x8cUFS."), 1}, /* "SÅ’UR VEULENT PLUS D'Å’UFS." in CP1252 */ {D_STR_W_LEN ("S\xc5\x93ur veulent plus d'\xc5\x93ufs."), /* "SÅ“ur veulent plus d'Å“ufs." in UTF-8 */ D_STR_W_LEN ("S\xc5\x92UR VEULENT PLUS D'\xc5\x92UFS."), 2}, /* "SÅ’UR VEULENT PLUS D'Å’UFS." in UTF-8 */ {D_STR_W_LEN ("Um ein sch\x94nes M\x84" "dchen zu k\x81ssen."), /* "Um ein schönes Mädchen zu küssen." in CP850 */ D_STR_W_LEN ("UM EIN SCH\x99NES M\x8e" "DCHEN ZU K\x9aSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in CP850 */ {D_STR_W_LEN ("Um ein sch\xf6nes M\xe4" "dchen zu k\xfcssen."), /* "Um ein schönes Mädchen zu küssen." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */ D_STR_W_LEN ("UM EIN SCH\xd6NES M\xc4" "DCHEN ZU K\xdcSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */ {D_STR_W_LEN ("Um ein sch\xc3\xb6nes M\xc3\xa4" "dchen zu k\xc3\xbcssen."), /* "Um ein schönes Mädchen zu küssen." in UTF-8 */ D_STR_W_LEN ("UM EIN SCH\xc3\x96NES M\xc3\x84" "DCHEN ZU K\xc3\x9cSSEN."), 11}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in UTF-8 */ {D_STR_W_LEN ("\x98stanbul"), /* "İstanbul" in CP857 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in CP857 */ {D_STR_W_LEN ("\xddstanbul"), /* "İstanbul" in ISO-8859-9/CP1254 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in ISO-8859-9/CP1254 */ {D_STR_W_LEN ("\xc4\xb0stanbul"), /* "İstanbul" in UTF-8 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in UTF-8 */ {D_STR_W_LEN ("Diyarbak\x8dr"), /* "Diyarbakır" in CP857 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in CP857 */ {D_STR_W_LEN ("Diyarbak\xfdr"), /* "Diyarbakır" in ISO-8859-9/CP1254 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in ISO-8859-9/CP1254 */ {D_STR_W_LEN ("Diyarbak\xc4\xb1r"), /* "Diyarbakır" in UTF-8 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in UTF-8 */ {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."), /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in CP866 */ D_STR_W_LEN ("\x92\x85\x91\x92\x8e\x82\x80\x9f \x91\x92\x90\x8e\x8a\x80."), 1}, /* "ТЕСТОВÐЯ СТРОКÐ." in CP866 */ {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."), /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in CP1251 */ D_STR_W_LEN ("\xd2\xc5\xd1\xd2\xce\xc2\xc0\xdf \xd1\xd2\xd0\xce\xca\xc0."), 1}, /* "ТЕСТОВÐЯ СТРОКÐ." in CP1251 */ {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."), /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in KOI8-R */ D_STR_W_LEN ("\xf4\xe5\xf3\xf4\xef\xf7\xe1\xf1 \xf3\xf4\xf2\xef\xeb\xe1."), 1}, /* "ТЕСТОВÐЯ СТРОКÐ." in KOI8-R */ {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."), /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in ISO-8859-5 */ D_STR_W_LEN ("\xc2\xb5\xc1\xc2\xbe\xb2\xb0\xcf \xc1\xc2\xc0\xbe\xba\xb0."), 1}, /* "ТЕСТОВÐЯ СТРОКÐ." in ISO-8859-5 */ {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."), /* "ТеÑÑ‚Ð¾Ð²Ð°Ñ Ð¡Ñ‚Ñ€Ð¾ÐºÐ°." in UTF-8 */ D_STR_W_LEN ("\xd0\xa2\xd0\x95\xd0\xa1\xd0\xa2\xd0\x9e\xd0\x92\xd0\x90\xd0" "\xaf \xd0\xa1\xd0\xa2\xd0\xa0\xd0\x9e\xd0\x9a\xd0\x90."), 3} /* "ТЕСТОВÐЯ СТРОКÐ." in UTF-8 */ }; static size_t check_eq_strings (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct two_eq_strs *const t = eq_strings + i; if (c_failed[i]) continue; /* skip already failed checks */ if (! MHD_str_equal_caseless_ (t->s1.str, t->s2.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero." " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), get_current_locale_str ()); } else if (! MHD_str_equal_caseless_ (t->s2.str, t->s1.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero." " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") != 0 && \\\n" " MHD_str_equal_caseless_(\"%s\", \"%s\") != 0\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str)); } } return t_failed; } static size_t check_neq_strings (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct two_neq_strs *const t = neq_strings + i; if (c_failed[i]) continue; /* skip already failed checks */ if (MHD_str_equal_caseless_ (t->s1.str, t->s2.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero." " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), get_current_locale_str ()); } else if (MHD_str_equal_caseless_ (t->s2.str, t->s1.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero." " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") == 0 && \\\n" " MHD_str_equal_caseless_(\"%s\", \"%s\") == 0\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str)); } } return t_failed; } static size_t check_eq_strings_n (void) { size_t t_failed = 0; size_t i, j, k; int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t m_len; const struct two_eq_strs *const t = eq_strings + i; m_len = (t->s1.len > t->s2.len) ? t->s1.len : t->s2.len; for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++) { if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \ "!= 0 && \\\n" \ " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \ "!= 0, where N is 0..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) m_len + 1); } } return t_failed; } static size_t check_neq_strings_n (void) { size_t t_failed = 0; size_t i, j, k; int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t m_len; const struct two_neq_strs *const t = neq_strings + i; m_len = t->s1.len > t->s2.len ? t->s1.len : t->s2.len; if (t->dif_pos >= m_len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less than " "s1.len (%u) or s2.len (%u).\n", (unsigned int) i, (unsigned int) t-> dif_pos, (unsigned int) t->s1.len, (unsigned int) t->s2.len); exit (99); } if (t->dif_pos > t->s1.len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or " "equal to s1.len (%u).\n", (unsigned int) i, (unsigned int) t->dif_pos, (unsigned int) t->s1.len); exit (99); } if (t->dif_pos > t->s2.len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or " "equal to s2.len (%u).\n", (unsigned int) i, (unsigned int) t->dif_pos, (unsigned int) t->s2.len); exit (99); } for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++) { if (k <= t->dif_pos) { if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } else { if (MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero," " while expected zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero," " while expected zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) { printf ( "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0 && \\\n" " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0, where N is 0..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) t->dif_pos); printf ( "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0 && \\\n" " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0, where N is %u..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) t->dif_pos + 1, (unsigned int) m_len + 1); } } } return t_failed; } /* * Run eq/neq strings tests */ static int run_eq_neq_str_tests (void) { size_t str_equal_caseless_fails = 0; size_t str_equal_caseless_n_fails = 0; size_t res; res = check_eq_strings (); if (res != 0) { str_equal_caseless_fails += res; fprintf (stderr, "FAILED: testcase check_eq_strings() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_eq_strings() successfully passed.\n\n"); res = check_neq_strings (); if (res != 0) { str_equal_caseless_fails += res; fprintf (stderr, "FAILED: testcase check_neq_strings() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_neq_strings() successfully passed.\n\n"); if (str_equal_caseless_fails) fprintf (stderr, "FAILED: function MHD_str_equal_caseless_() failed %lu time%s.\n\n", (unsigned long) str_equal_caseless_fails, str_equal_caseless_fails == 1 ? "" : "s"); else if (verbose > 0) printf ( "PASSED: function MHD_str_equal_caseless_() successfully passed all checks.\n\n"); res = check_eq_strings_n (); if (res != 0) { str_equal_caseless_n_fails += res; fprintf (stderr, "FAILED: testcase check_eq_strings_n() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_eq_strings_n() successfully passed.\n\n"); res = check_neq_strings_n (); if (res != 0) { str_equal_caseless_n_fails += res; fprintf (stderr, "FAILED: testcase check_neq_strings_n() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_neq_strings_n() successfully passed.\n\n"); if (str_equal_caseless_n_fails) fprintf (stderr, "FAILED: function MHD_str_equal_caseless_n_() failed %lu time%s.\n\n", (unsigned long) str_equal_caseless_n_fails, str_equal_caseless_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ( "PASSED: function MHD_str_equal_caseless_n_() successfully passed all checks.\n\n"); if (str_equal_caseless_fails || str_equal_caseless_n_fails) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } /* * Digits in string -> value tests */ struct str_with_value { const struct str_with_len str; const size_t num_of_digt; const uint64_t val; }; /* valid string for conversion to unsigned integer value */ static const struct str_with_value dstrs_w_values[] = { /* simplest strings */ {D_STR_W_LEN ("1"), 1, 1}, {D_STR_W_LEN ("0"), 1, 0}, {D_STR_W_LEN ("10000"), 5, 10000}, /* all digits */ {D_STR_W_LEN ("1234"), 4, 1234}, {D_STR_W_LEN ("4567"), 4, 4567}, {D_STR_W_LEN ("7890"), 4, 7890}, {D_STR_W_LEN ("8021"), 4, 8021}, {D_STR_W_LEN ("9754"), 4, 9754}, {D_STR_W_LEN ("6392"), 4, 6392}, /* various prefixes */ {D_STR_W_LEN ("00000000"), 8, 0}, {D_STR_W_LEN ("0755"), 4, 755}, /* not to be interpreted as octal value! */ {D_STR_W_LEN ("002"), 3, 2}, {D_STR_W_LEN ("0001"), 4, 1}, {D_STR_W_LEN ("00000000000000000000000031295483"), 32, 31295483}, /* numbers below and above limits */ {D_STR_W_LEN ("127"), 3, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("128"), 3, 128}, /* 0x80, SCHAR_MAX+1 */ {D_STR_W_LEN ("255"), 3, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("256"), 3, 256}, /* 0x100, UCHAR_MAX+1 */ {D_STR_W_LEN ("32767"), 5, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("32768"), 5, 32768}, /* 0x8000, INT16_MAX+1 */ {D_STR_W_LEN ("65535"), 5, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("65536"), 5, 65536}, /* 0x10000, UINT16_MAX+1 */ {D_STR_W_LEN ("2147483647"), 10, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("2147483648"), 10, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */ {D_STR_W_LEN ("4294967295"), 10, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("4294967296"), 10, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */ {D_STR_W_LEN ("9223372036854775807"), 19, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("9223372036854775808"), 19, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */ {D_STR_W_LEN ("18446744073709551615"), 20, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ /* random numbers */ {D_STR_W_LEN ("10186753"), 8, 10186753}, {D_STR_W_LEN ("144402566"), 9, 144402566}, {D_STR_W_LEN ("151903144"), 9, 151903144}, {D_STR_W_LEN ("139264621"), 9, 139264621}, {D_STR_W_LEN ("730348"), 6, 730348}, {D_STR_W_LEN ("21584377"), 8, 21584377}, {D_STR_W_LEN ("709"), 3, 709}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("8452"), 4, 8452}, {D_STR_W_LEN ("17745098750013624977"), 20, UINT64_C (17745098750013624977)}, {D_STR_W_LEN ("06786878769931678000"), 20, UINT64_C (6786878769931678000)}, /* non-digit suffixes */ {D_STR_W_LEN ("1234oa"), 4, 1234}, {D_STR_W_LEN ("20h"), 2, 20}, /* not to be interpreted as hex value! */ {D_STR_W_LEN ("0x1F"), 1, 0}, /* not to be interpreted as hex value! */ {D_STR_W_LEN ("0564`~}"), 4, 564}, {D_STR_W_LEN ("7240146.724"), 7, 7240146}, {D_STR_W_LEN ("2,9"), 1, 2}, {D_STR_W_LEN ("200+1"), 3, 200}, {D_STR_W_LEN ("1a"), 1, 1}, {D_STR_W_LEN ("2E"), 1, 2}, {D_STR_W_LEN ("6c"), 1, 6}, {D_STR_W_LEN ("8F"), 1, 8}, {D_STR_W_LEN ("287416997! And the not too long string."), 9, 287416997} }; /* strings that should overflow uint64_t */ static const struct str_with_len str_ovflw[] = { D_STR_W_LEN ("18446744073709551616"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("18446744073709551620"), D_STR_W_LEN ("18446744083709551615"), D_STR_W_LEN ("19234761020556472143"), D_STR_W_LEN ("184467440737095516150"), D_STR_W_LEN ("1844674407370955161500"), D_STR_W_LEN ("000018446744073709551616"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000"), D_STR_W_LEN ("020000000000000000000"), D_STR_W_LEN ("0020000000000000000000"), D_STR_W_LEN ("100000000000000000000"), D_STR_W_LEN ("434532891232591226417"), D_STR_W_LEN ("99999999999999999999"), D_STR_W_LEN ("18446744073709551616abcd"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000 suffix"), D_STR_W_LEN ("020000000000000000000x") }; /* strings that should not be convertible to numeric value */ static const struct str_with_len str_no_num[] = { D_STR_W_LEN ("zero"), D_STR_W_LEN ("one"), D_STR_W_LEN ("\xb9\xb2\xb3"), /* superscript "123" in ISO-8859-1/CP1252 */ D_STR_W_LEN ("\xc2\xb9\xc2\xb2\xc2\xb3"), /* superscript "123" in UTF-8 */ D_STR_W_LEN ("\xd9\xa1\xd9\xa2\xd9\xa3"), /* Arabic-Indic "١٢٣" in UTF-8 */ D_STR_W_LEN ("\xdb\xb1\xdb\xb2\xdb\xb3"), /* Ext Arabic-Indic "Û±Û²Û³" in UTF-8 */ D_STR_W_LEN ("\xe0\xa5\xa7\xe0\xa5\xa8\xe0\xa5\xa9"), /* Devanagari "१२३" in UTF-8 */ D_STR_W_LEN ("\xe4\xb8\x80\xe4\xba\x8c\xe4\xb8\x89"), /* Chinese "一二三" in UTF-8 */ D_STR_W_LEN ("\xd2\xbb\xb6\xfe\xc8\xfd"), /* Chinese "一二三" in GB2312/CP936 */ D_STR_W_LEN ("\x1B\x24\x29\x41\x0E\x52\x3B\x36\x7E\x48\x7D\x0F") /* Chinese "一二三" in ISO-2022-CN */ }; /* valid hex string for conversion to unsigned integer value */ static const struct str_with_value xdstrs_w_values[] = { /* simplest strings */ {D_STR_W_LEN ("1"), 1, 0x1}, {D_STR_W_LEN ("0"), 1, 0x0}, {D_STR_W_LEN ("10000"), 5, 0x10000}, /* all digits */ {D_STR_W_LEN ("1234"), 4, 0x1234}, {D_STR_W_LEN ("4567"), 4, 0x4567}, {D_STR_W_LEN ("7890"), 4, 0x7890}, {D_STR_W_LEN ("8021"), 4, 0x8021}, {D_STR_W_LEN ("9754"), 4, 0x9754}, {D_STR_W_LEN ("6392"), 4, 0x6392}, {D_STR_W_LEN ("abcd"), 4, 0xABCD}, {D_STR_W_LEN ("cdef"), 4, 0xCDEF}, {D_STR_W_LEN ("FEAB"), 4, 0xFEAB}, {D_STR_W_LEN ("BCED"), 4, 0xBCED}, {D_STR_W_LEN ("bCeD"), 4, 0xBCED}, {D_STR_W_LEN ("1A5F"), 4, 0x1A5F}, {D_STR_W_LEN ("12AB"), 4, 0x12AB}, {D_STR_W_LEN ("CD34"), 4, 0xCD34}, {D_STR_W_LEN ("56EF"), 4, 0x56EF}, {D_STR_W_LEN ("7a9f"), 4, 0x7A9F}, /* various prefixes */ {D_STR_W_LEN ("00000000"), 8, 0x0}, {D_STR_W_LEN ("0755"), 4, 0x755}, /* not to be interpreted as octal value! */ {D_STR_W_LEN ("002"), 3, 0x2}, {D_STR_W_LEN ("0001"), 4, 0x1}, {D_STR_W_LEN ("00a"), 3, 0xA}, {D_STR_W_LEN ("0F"), 2, 0xF}, {D_STR_W_LEN ("0000000000000000000000003A29e4C3"), 32, 0x3A29E4C3}, /* numbers below and above limits */ {D_STR_W_LEN ("7F"), 2, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("7f"), 2, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("80"), 2, 128}, /* 0x80, SCHAR_MAX+1 */ {D_STR_W_LEN ("fF"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("Ff"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("FF"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("ff"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("100"), 3, 256}, /* 0x100, UCHAR_MAX+1 */ {D_STR_W_LEN ("7fff"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("7FFF"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("7Fff"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("8000"), 4, 32768}, /* 0x8000, INT16_MAX+1 */ {D_STR_W_LEN ("ffff"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("FFFF"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("FffF"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("10000"), 5, 65536}, /* 0x10000, UINT16_MAX+1 */ {D_STR_W_LEN ("7FFFFFFF"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("7fffffff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("7FFffFff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("80000000"), 8, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */ {D_STR_W_LEN ("FFFFFFFF"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("ffffffff"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("FfFfFfFf"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("100000000"), 9, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */ {D_STR_W_LEN ("7fffffffffffffff"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("7FFFFFFFFFFFFFFF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("7FfffFFFFffFFffF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("8000000000000000"), 16, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */ {D_STR_W_LEN ("ffffffffffffffff"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ {D_STR_W_LEN ("FFFFFFFFFFFFFFFF"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ {D_STR_W_LEN ("FffFffFFffFFfFFF"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ /* random numbers */ {D_STR_W_LEN ("10186753"), 8, 0x10186753}, {D_STR_W_LEN ("144402566"), 9, 0x144402566}, {D_STR_W_LEN ("151903144"), 9, 0x151903144}, {D_STR_W_LEN ("139264621"), 9, 0x139264621}, {D_STR_W_LEN ("730348"), 6, 0x730348}, {D_STR_W_LEN ("21584377"), 8, 0x21584377}, {D_STR_W_LEN ("709"), 3, 0x709}, {D_STR_W_LEN ("54"), 2, 0x54}, {D_STR_W_LEN ("8452"), 4, 0x8452}, {D_STR_W_LEN ("22353EC6"), 8, 0x22353EC6}, {D_STR_W_LEN ("307F1655"), 8, 0x307F1655}, {D_STR_W_LEN ("1FCB7226"), 8, 0x1FCB7226}, {D_STR_W_LEN ("82480560"), 8, 0x82480560}, {D_STR_W_LEN ("7386D95"), 7, 0x7386D95}, {D_STR_W_LEN ("EC3AB"), 5, 0xEC3AB}, {D_STR_W_LEN ("6DD05"), 5, 0x6DD05}, {D_STR_W_LEN ("C5DF"), 4, 0xC5DF}, {D_STR_W_LEN ("6CE"), 3, 0x6CE}, {D_STR_W_LEN ("CE6"), 3, 0xCE6}, {D_STR_W_LEN ("ce6"), 3, 0xCE6}, {D_STR_W_LEN ("F27"), 3, 0xF27}, {D_STR_W_LEN ("8497D54277D7E1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8497d54277d7e1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8497d54277d7E1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8C8112D0A06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("8c8112d0a06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("8c8112d0A06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("1774509875001362"), 16, UINT64_C (1690064375898968930)}, {D_STR_W_LEN ("0678687876998000"), 16, UINT64_C (466237428027981824)}, /* non-digit suffixes */ {D_STR_W_LEN ("1234oa"), 4, 0x1234}, {D_STR_W_LEN ("20h"), 2, 0x20}, {D_STR_W_LEN ("2CH"), 2, 0x2C}, {D_STR_W_LEN ("2ch"), 2, 0x2C}, {D_STR_W_LEN ("0x1F"), 1, 0x0}, /* not to be interpreted as hex prefix! */ {D_STR_W_LEN ("0564`~}"), 4, 0x564}, {D_STR_W_LEN ("0A64`~}"), 4, 0xA64}, {D_STR_W_LEN ("056c`~}"), 4, 0X56C}, {D_STR_W_LEN ("7240146.724"), 7, 0x7240146}, {D_STR_W_LEN ("7E4c1AB.724"), 7, 0X7E4C1AB}, {D_STR_W_LEN ("F24B1B6.724"), 7, 0xF24B1B6}, {D_STR_W_LEN ("2,9"), 1, 0x2}, {D_STR_W_LEN ("a,9"), 1, 0xA}, {D_STR_W_LEN ("200+1"), 3, 0x200}, {D_STR_W_LEN ("2cc+1"), 3, 0x2CC}, {D_STR_W_LEN ("2cC+1"), 3, 0x2CC}, {D_STR_W_LEN ("27416997! And the not too long string."), 8, 0x27416997}, {D_STR_W_LEN ("27555416997! And the not too long string."), 11, 0x27555416997}, {D_STR_W_LEN ("416997And the not too long string."), 7, 0x416997A}, {D_STR_W_LEN ("0F4C3Dabstract addition to make string even longer"), 8, 0xF4C3DAB} }; /* hex strings that should overflow uint64_t */ static const struct str_with_len strx_ovflw[] = { D_STR_W_LEN ("10000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("10000000000000001"), D_STR_W_LEN ("10000000000000002"), D_STR_W_LEN ("1000000000000000A"), D_STR_W_LEN ("11000000000000000"), D_STR_W_LEN ("010000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("000010000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000"), D_STR_W_LEN ("020000000000000000000"), D_STR_W_LEN ("0020000000000000000000"), D_STR_W_LEN ("20000000000000000"), D_STR_W_LEN ("A0000000000000000"), D_STR_W_LEN ("F0000000000000000"), D_STR_W_LEN ("a0000000000000000"), D_STR_W_LEN ("11111111111111111"), D_STR_W_LEN ("CcCcCCccCCccCCccC"), D_STR_W_LEN ("f0000000000000000"), D_STR_W_LEN ("100000000000000000000"), D_STR_W_LEN ("434532891232591226417"), D_STR_W_LEN ("10000000000000000a"), D_STR_W_LEN ("10000000000000000E"), D_STR_W_LEN ("100000000000000000 and nothing"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("100000000000000000xx"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("99999999999999999999"), D_STR_W_LEN ("18446744073709551616abcd"), D_STR_W_LEN ("20000000000000000000 suffix"), D_STR_W_LEN ("020000000000000000000x") }; static size_t check_str_to_uint64_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv; size_t rs; const struct str_with_value *const t = dstrs_w_values + i; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 9435223; /* some random value */ rs = MHD_str_to_uint64_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") converted string to value %" PRIu64 "," " while expecting result %" PRIu64 ". Locale: %s\n", n_prnt (t->str.str), rv, rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") == %" \ PRIuPTR "\n", n_prnt (t->str.str), rv, rs); } } return t_failed; } static size_t check_str_to_uint64_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 24941852; size_t rs; if ((c >= '0') && (c <= '9') ) continue; /* skip digits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_str_to_uint64_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (test_str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_str_to_uint64_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_ovflw + i; static const uint64_t rnd_val = 2; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_str_to_uint64_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_str_to_uint64_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv = 1235572; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = dstrs_w_values + i; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_str_to_uint64_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " converted string to value %" PRIu64 ", while expecting result %" PRIu64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->%" PRIu64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, rv, rs); } } return t_failed; } static size_t check_str_to_uint64_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 98372558; size_t rs; size_t len; if ((c >= '0') && (c <= '9') ) continue; /* skip digits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_str_to_uint64_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_str_to_uint64_n_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_ovflw + i; static const uint64_t rnd_val = 3; size_t len; for (len = t->len; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len, (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_str_to_uint64_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 43255654342; size_t len; for (len = 0; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint32_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint32_t rv; size_t rs; const struct str_with_value *const t = xdstrs_w_values + i; if (t->val > UINT32_MAX) continue; /* number is too high for this function */ if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 1458532; /* some random value */ rs = MHD_strx_to_uint32_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), (uint64_t) rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") converted string to value 0x%" PRIX64 "," " while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uint64_t) rv, (uint64_t) rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") == %" PRIuPTR "\n", n_prnt (t->str.str), (uint64_t) rv, rs); } } return t_failed; } static size_t check_strx_to_uint32_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint32_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint32_t rnd_val = 234234; size_t rs; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint32_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint32_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (test_str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint32_overflow (void) { size_t t_failed = 0; size_t i, j; static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]); int c_failed[(sizeof(strx_ovflw) / sizeof(strx_ovflw[0])) + (sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0]))]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; static const uint32_t rnd_val = 74218431; uint32_t test_val; const char *str; if (i < n_checks1) { const struct str_with_len *const t = strx_ovflw + i; str = t->str; } else { const struct str_with_value *const t = xdstrs_w_values + (i - n_checks1); if (t->val <= UINT32_MAX) continue; /* check only strings that should overflow uint32_t */ str = t->str.str; } for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_ (str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (str)); } } return t_failed; } static size_t check_strx_to_uint32_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint32_t rnd_val = 74218431; uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint32_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint32_t rv = 2352932; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = xdstrs_w_values + i; if (t->val > UINT32_MAX) continue; /* number is too high for this function */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_strx_to_uint32_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " converted string to value 0x%" PRIX64 ", while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, (uint64_t) rv, (uint64_t) rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ( "PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->0x%" PRIX64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, (uint64_t) rv, rs); } } return t_failed; } static size_t check_strx_to_uint32_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint32_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint32_t rnd_val = 98372558; size_t rs; size_t len; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint32_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint32_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint32_n_overflow (void) { size_t t_failed = 0; size_t i, j; static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]); int c_failed[(sizeof(strx_ovflw) / sizeof(strx_ovflw[0])) + (sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0]))]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; static const uint32_t rnd_val = 4; size_t len; const char *str; size_t min_len, max_len; if (i < n_checks1) { const struct str_with_len *const t = strx_ovflw + i; str = t->str; min_len = t->len; max_len = t->len + 1; } else { const struct str_with_value *const t = xdstrs_w_values + (i - n_checks1); if (t->val <= UINT32_MAX) continue; /* check only strings that should overflow uint32_t */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) (i - n_checks1), (unsigned int) t->num_of_digt, (unsigned int) t->str.len); exit (99); } str = t->str.str; min_len = t->num_of_digt; max_len = t->str.len + 1; } for (len = min_len; len <= max_len; len++) { uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_n_ (str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (str), (uintptr_t) min_len, (uintptr_t) max_len); } } return t_failed; } static size_t check_strx_to_uint32_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint32_t rnd_val = 3214314212UL; size_t len; for (len = 0; len <= t->len + 1; len++) { uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint64_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv; size_t rs; const struct str_with_value *const t = xdstrs_w_values + i; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 1458532; /* some random value */ rs = MHD_strx_to_uint64_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") converted string to value 0x%" PRIX64 "," " while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), rv, rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") == %" PRIuPTR "\n", n_prnt (t->str.str), rv, rs); } } return t_failed; } static size_t check_strx_to_uint64_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 234234; size_t rs; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint64_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (test_str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint64_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = strx_ovflw + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint64_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint64_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv = 2352932; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = xdstrs_w_values + i; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_strx_to_uint64_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " converted string to value 0x%" PRIX64 ", while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->0x%" PRIX64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, rv, rs); } } return t_failed; } static size_t check_strx_to_uint64_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 98372558; size_t rs; size_t len; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint64_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint64_n_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = strx_ovflw + i; static const uint64_t rnd_val = 4; size_t len; for (len = t->len; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len, (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint64_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 3214314212UL; size_t len; for (len = 0; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static int run_str_to_X_tests (void) { size_t str_to_uint64_fails = 0; size_t str_to_uint64_n_fails = 0; size_t strx_to_uint32_fails = 0; size_t strx_to_uint32_n_fails = 0; size_t strx_to_uint64_fails = 0; size_t strx_to_uint64_n_fails = 0; size_t res; res = check_str_to_uint64_valid (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_valid() failed.\n\n"); } else if (verbose > 1) printf ( "PASSED: testcase check_str_to_uint64_valid() successfully passed.\n\n"); res = check_str_to_uint64_all_chars (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_all_chars() " "successfully passed.\n\n"); res = check_str_to_uint64_overflow (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_overflow() " "successfully passed.\n\n"); res = check_str_to_uint64_no_val (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_no_val() " "successfully passed.\n\n"); if (str_to_uint64_fails) fprintf (stderr, "FAILED: function MHD_str_to_uint64_() failed %lu time%s.\n\n", (unsigned long) str_to_uint64_fails, str_to_uint64_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_str_to_uint64_() successfully " "passed all checks.\n\n"); res = check_str_to_uint64_n_valid (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_valid() " "successfully passed.\n\n"); res = check_str_to_uint64_n_all_chars (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_all_chars() " "successfully passed.\n\n"); res = check_str_to_uint64_n_overflow (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_overflow() " "successfully passed.\n\n"); res = check_str_to_uint64_n_no_val (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_no_val() " "successfully passed.\n\n"); if (str_to_uint64_n_fails) fprintf (stderr, "FAILED: function MHD_str_to_uint64_n_() failed %lu time%s.\n\n", (unsigned long) str_to_uint64_n_fails, str_to_uint64_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_str_to_uint64_n_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint32_valid (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_valid() " "successfully passed.\n\n"); res = check_strx_to_uint32_all_chars (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint32_overflow (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint32_no_val (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_no_val() " "successfully passed.\n\n"); if (strx_to_uint32_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint32_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint32_fails, strx_to_uint32_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint32_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint32_n_valid (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_valid() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_all_chars (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_overflow (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_no_val (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_no_val() " "successfully passed.\n\n"); if (strx_to_uint32_n_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint32_n_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint32_n_fails, strx_to_uint32_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint32_n_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint64_valid (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_valid() " "successfully passed.\n\n"); res = check_strx_to_uint64_all_chars (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint64_overflow (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint64_no_val (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_no_val() " "successfully passed.\n\n"); if (strx_to_uint64_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint64_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint64_fails, strx_to_uint64_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint64_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint64_n_valid (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_valid() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_all_chars (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_overflow (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_no_val (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_no_val() " "successfully passed.\n\n"); if (strx_to_uint64_n_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint64_n_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint64_n_fails, strx_to_uint64_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint64_n_() successfully " "passed all checks.\n\n"); if (str_to_uint64_fails || str_to_uint64_n_fails || strx_to_uint32_fails || strx_to_uint32_n_fails || strx_to_uint64_fails || strx_to_uint64_n_fails) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } static size_t check_str_from_uint16 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "-@=sd#+&(pdiren456qwe#@C3S!DAS45AOIPUQWESAdFzxcv1s*()&#$%34`" "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()द`" "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()ӌ`"; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = dstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (UINT16_MAX < t->val) continue; /* Too large value to convert */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint16_to_str ((uint16_t) t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static size_t check_str_from_uint64 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "-@=sd#+&(pdirenDSFGSe#@C&S!DAS*!AOIPUQWESAdFzxcvSs*()&#$%KH`" "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()द`" "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()ӌ`"; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = dstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint64_to_str (t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static size_t check_strx_from_uint32 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "jrlkjssfhjfvrjntJHLJ$@%$#adsfdkj;k$##$%#$%FGDF%$#^FDFG%$#$D`" ";skjdhjflsdkjhdjfalskdjhdfalkjdhf$%##%$$#%FSDGFSDDGDFSSDSDF`" "#5#$%#$#$DFSFDDFSGSDFSDF354FDDSGFDFfdssfddfswqemn,.zxih,.sx`"; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = xdstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (UINT32_MAX < t->val) continue; /* Too large value to convert */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint32_to_strx ((uint32_t) t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 == MHD_str_equal_caseless_bin_n_ (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (sizeof(buf) <= rs) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has string with too many" "(%u) digits, size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) rs); exit (99); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static const struct str_with_value duint8_w_values_p1[] = { {D_STR_W_LEN ("0"), 1, 0}, {D_STR_W_LEN ("1"), 1, 1}, {D_STR_W_LEN ("2"), 1, 2}, {D_STR_W_LEN ("3"), 1, 3}, {D_STR_W_LEN ("4"), 1, 4}, {D_STR_W_LEN ("5"), 1, 5}, {D_STR_W_LEN ("6"), 1, 6}, {D_STR_W_LEN ("7"), 1, 7}, {D_STR_W_LEN ("8"), 1, 8}, {D_STR_W_LEN ("9"), 1, 9}, {D_STR_W_LEN ("10"), 2, 10}, {D_STR_W_LEN ("11"), 2, 11}, {D_STR_W_LEN ("12"), 2, 12}, {D_STR_W_LEN ("13"), 2, 13}, {D_STR_W_LEN ("14"), 2, 14}, {D_STR_W_LEN ("15"), 2, 15}, {D_STR_W_LEN ("16"), 2, 16}, {D_STR_W_LEN ("17"), 2, 17}, {D_STR_W_LEN ("18"), 2, 18}, {D_STR_W_LEN ("19"), 2, 19}, {D_STR_W_LEN ("20"), 2, 20}, {D_STR_W_LEN ("21"), 2, 21}, {D_STR_W_LEN ("22"), 2, 22}, {D_STR_W_LEN ("23"), 2, 23}, {D_STR_W_LEN ("24"), 2, 24}, {D_STR_W_LEN ("25"), 2, 25}, {D_STR_W_LEN ("26"), 2, 26}, {D_STR_W_LEN ("27"), 2, 27}, {D_STR_W_LEN ("28"), 2, 28}, {D_STR_W_LEN ("29"), 2, 29}, {D_STR_W_LEN ("30"), 2, 30}, {D_STR_W_LEN ("31"), 2, 31}, {D_STR_W_LEN ("32"), 2, 32}, {D_STR_W_LEN ("33"), 2, 33}, {D_STR_W_LEN ("34"), 2, 34}, {D_STR_W_LEN ("35"), 2, 35}, {D_STR_W_LEN ("36"), 2, 36}, {D_STR_W_LEN ("37"), 2, 37}, {D_STR_W_LEN ("38"), 2, 38}, {D_STR_W_LEN ("39"), 2, 39}, {D_STR_W_LEN ("40"), 2, 40}, {D_STR_W_LEN ("41"), 2, 41}, {D_STR_W_LEN ("42"), 2, 42}, {D_STR_W_LEN ("43"), 2, 43}, {D_STR_W_LEN ("44"), 2, 44}, {D_STR_W_LEN ("45"), 2, 45}, {D_STR_W_LEN ("46"), 2, 46}, {D_STR_W_LEN ("47"), 2, 47}, {D_STR_W_LEN ("48"), 2, 48}, {D_STR_W_LEN ("49"), 2, 49}, {D_STR_W_LEN ("50"), 2, 50}, {D_STR_W_LEN ("51"), 2, 51}, {D_STR_W_LEN ("52"), 2, 52}, {D_STR_W_LEN ("53"), 2, 53}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("55"), 2, 55}, {D_STR_W_LEN ("56"), 2, 56}, {D_STR_W_LEN ("57"), 2, 57}, {D_STR_W_LEN ("58"), 2, 58}, {D_STR_W_LEN ("59"), 2, 59}, {D_STR_W_LEN ("60"), 2, 60}, {D_STR_W_LEN ("61"), 2, 61}, {D_STR_W_LEN ("62"), 2, 62}, {D_STR_W_LEN ("63"), 2, 63}, {D_STR_W_LEN ("64"), 2, 64}, {D_STR_W_LEN ("65"), 2, 65}, {D_STR_W_LEN ("66"), 2, 66}, {D_STR_W_LEN ("67"), 2, 67}, {D_STR_W_LEN ("68"), 2, 68}, {D_STR_W_LEN ("69"), 2, 69}, {D_STR_W_LEN ("70"), 2, 70}, {D_STR_W_LEN ("71"), 2, 71}, {D_STR_W_LEN ("72"), 2, 72}, {D_STR_W_LEN ("73"), 2, 73}, {D_STR_W_LEN ("74"), 2, 74}, {D_STR_W_LEN ("75"), 2, 75}, {D_STR_W_LEN ("76"), 2, 76}, {D_STR_W_LEN ("77"), 2, 77}, {D_STR_W_LEN ("78"), 2, 78}, {D_STR_W_LEN ("79"), 2, 79}, {D_STR_W_LEN ("80"), 2, 80}, {D_STR_W_LEN ("81"), 2, 81}, {D_STR_W_LEN ("82"), 2, 82}, {D_STR_W_LEN ("83"), 2, 83}, {D_STR_W_LEN ("84"), 2, 84}, {D_STR_W_LEN ("85"), 2, 85}, {D_STR_W_LEN ("86"), 2, 86}, {D_STR_W_LEN ("87"), 2, 87}, {D_STR_W_LEN ("88"), 2, 88}, {D_STR_W_LEN ("89"), 2, 89}, {D_STR_W_LEN ("90"), 2, 90}, {D_STR_W_LEN ("91"), 2, 91}, {D_STR_W_LEN ("92"), 2, 92}, {D_STR_W_LEN ("93"), 2, 93}, {D_STR_W_LEN ("94"), 2, 94}, {D_STR_W_LEN ("95"), 2, 95}, {D_STR_W_LEN ("96"), 2, 96}, {D_STR_W_LEN ("97"), 2, 97}, {D_STR_W_LEN ("98"), 2, 98}, {D_STR_W_LEN ("99"), 2, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255}, }; static const struct str_with_value duint8_w_values_p2[] = { {D_STR_W_LEN ("00"), 2, 0}, {D_STR_W_LEN ("01"), 2, 1}, {D_STR_W_LEN ("02"), 2, 2}, {D_STR_W_LEN ("03"), 2, 3}, {D_STR_W_LEN ("04"), 2, 4}, {D_STR_W_LEN ("05"), 2, 5}, {D_STR_W_LEN ("06"), 2, 6}, {D_STR_W_LEN ("07"), 2, 7}, {D_STR_W_LEN ("08"), 2, 8}, {D_STR_W_LEN ("09"), 2, 9}, {D_STR_W_LEN ("10"), 2, 10}, {D_STR_W_LEN ("11"), 2, 11}, {D_STR_W_LEN ("12"), 2, 12}, {D_STR_W_LEN ("13"), 2, 13}, {D_STR_W_LEN ("14"), 2, 14}, {D_STR_W_LEN ("15"), 2, 15}, {D_STR_W_LEN ("16"), 2, 16}, {D_STR_W_LEN ("17"), 2, 17}, {D_STR_W_LEN ("18"), 2, 18}, {D_STR_W_LEN ("19"), 2, 19}, {D_STR_W_LEN ("20"), 2, 20}, {D_STR_W_LEN ("21"), 2, 21}, {D_STR_W_LEN ("22"), 2, 22}, {D_STR_W_LEN ("23"), 2, 23}, {D_STR_W_LEN ("24"), 2, 24}, {D_STR_W_LEN ("25"), 2, 25}, {D_STR_W_LEN ("26"), 2, 26}, {D_STR_W_LEN ("27"), 2, 27}, {D_STR_W_LEN ("28"), 2, 28}, {D_STR_W_LEN ("29"), 2, 29}, {D_STR_W_LEN ("30"), 2, 30}, {D_STR_W_LEN ("31"), 2, 31}, {D_STR_W_LEN ("32"), 2, 32}, {D_STR_W_LEN ("33"), 2, 33}, {D_STR_W_LEN ("34"), 2, 34}, {D_STR_W_LEN ("35"), 2, 35}, {D_STR_W_LEN ("36"), 2, 36}, {D_STR_W_LEN ("37"), 2, 37}, {D_STR_W_LEN ("38"), 2, 38}, {D_STR_W_LEN ("39"), 2, 39}, {D_STR_W_LEN ("40"), 2, 40}, {D_STR_W_LEN ("41"), 2, 41}, {D_STR_W_LEN ("42"), 2, 42}, {D_STR_W_LEN ("43"), 2, 43}, {D_STR_W_LEN ("44"), 2, 44}, {D_STR_W_LEN ("45"), 2, 45}, {D_STR_W_LEN ("46"), 2, 46}, {D_STR_W_LEN ("47"), 2, 47}, {D_STR_W_LEN ("48"), 2, 48}, {D_STR_W_LEN ("49"), 2, 49}, {D_STR_W_LEN ("50"), 2, 50}, {D_STR_W_LEN ("51"), 2, 51}, {D_STR_W_LEN ("52"), 2, 52}, {D_STR_W_LEN ("53"), 2, 53}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("55"), 2, 55}, {D_STR_W_LEN ("56"), 2, 56}, {D_STR_W_LEN ("57"), 2, 57}, {D_STR_W_LEN ("58"), 2, 58}, {D_STR_W_LEN ("59"), 2, 59}, {D_STR_W_LEN ("60"), 2, 60}, {D_STR_W_LEN ("61"), 2, 61}, {D_STR_W_LEN ("62"), 2, 62}, {D_STR_W_LEN ("63"), 2, 63}, {D_STR_W_LEN ("64"), 2, 64}, {D_STR_W_LEN ("65"), 2, 65}, {D_STR_W_LEN ("66"), 2, 66}, {D_STR_W_LEN ("67"), 2, 67}, {D_STR_W_LEN ("68"), 2, 68}, {D_STR_W_LEN ("69"), 2, 69}, {D_STR_W_LEN ("70"), 2, 70}, {D_STR_W_LEN ("71"), 2, 71}, {D_STR_W_LEN ("72"), 2, 72}, {D_STR_W_LEN ("73"), 2, 73}, {D_STR_W_LEN ("74"), 2, 74}, {D_STR_W_LEN ("75"), 2, 75}, {D_STR_W_LEN ("76"), 2, 76}, {D_STR_W_LEN ("77"), 2, 77}, {D_STR_W_LEN ("78"), 2, 78}, {D_STR_W_LEN ("79"), 2, 79}, {D_STR_W_LEN ("80"), 2, 80}, {D_STR_W_LEN ("81"), 2, 81}, {D_STR_W_LEN ("82"), 2, 82}, {D_STR_W_LEN ("83"), 2, 83}, {D_STR_W_LEN ("84"), 2, 84}, {D_STR_W_LEN ("85"), 2, 85}, {D_STR_W_LEN ("86"), 2, 86}, {D_STR_W_LEN ("87"), 2, 87}, {D_STR_W_LEN ("88"), 2, 88}, {D_STR_W_LEN ("89"), 2, 89}, {D_STR_W_LEN ("90"), 2, 90}, {D_STR_W_LEN ("91"), 2, 91}, {D_STR_W_LEN ("92"), 2, 92}, {D_STR_W_LEN ("93"), 2, 93}, {D_STR_W_LEN ("94"), 2, 94}, {D_STR_W_LEN ("95"), 2, 95}, {D_STR_W_LEN ("96"), 2, 96}, {D_STR_W_LEN ("97"), 2, 97}, {D_STR_W_LEN ("98"), 2, 98}, {D_STR_W_LEN ("99"), 2, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255} }; static const struct str_with_value duint8_w_values_p3[] = { {D_STR_W_LEN ("000"), 3, 0}, {D_STR_W_LEN ("001"), 3, 1}, {D_STR_W_LEN ("002"), 3, 2}, {D_STR_W_LEN ("003"), 3, 3}, {D_STR_W_LEN ("004"), 3, 4}, {D_STR_W_LEN ("005"), 3, 5}, {D_STR_W_LEN ("006"), 3, 6}, {D_STR_W_LEN ("007"), 3, 7}, {D_STR_W_LEN ("008"), 3, 8}, {D_STR_W_LEN ("009"), 3, 9}, {D_STR_W_LEN ("010"), 3, 10}, {D_STR_W_LEN ("011"), 3, 11}, {D_STR_W_LEN ("012"), 3, 12}, {D_STR_W_LEN ("013"), 3, 13}, {D_STR_W_LEN ("014"), 3, 14}, {D_STR_W_LEN ("015"), 3, 15}, {D_STR_W_LEN ("016"), 3, 16}, {D_STR_W_LEN ("017"), 3, 17}, {D_STR_W_LEN ("018"), 3, 18}, {D_STR_W_LEN ("019"), 3, 19}, {D_STR_W_LEN ("020"), 3, 20}, {D_STR_W_LEN ("021"), 3, 21}, {D_STR_W_LEN ("022"), 3, 22}, {D_STR_W_LEN ("023"), 3, 23}, {D_STR_W_LEN ("024"), 3, 24}, {D_STR_W_LEN ("025"), 3, 25}, {D_STR_W_LEN ("026"), 3, 26}, {D_STR_W_LEN ("027"), 3, 27}, {D_STR_W_LEN ("028"), 3, 28}, {D_STR_W_LEN ("029"), 3, 29}, {D_STR_W_LEN ("030"), 3, 30}, {D_STR_W_LEN ("031"), 3, 31}, {D_STR_W_LEN ("032"), 3, 32}, {D_STR_W_LEN ("033"), 3, 33}, {D_STR_W_LEN ("034"), 3, 34}, {D_STR_W_LEN ("035"), 3, 35}, {D_STR_W_LEN ("036"), 3, 36}, {D_STR_W_LEN ("037"), 3, 37}, {D_STR_W_LEN ("038"), 3, 38}, {D_STR_W_LEN ("039"), 3, 39}, {D_STR_W_LEN ("040"), 3, 40}, {D_STR_W_LEN ("041"), 3, 41}, {D_STR_W_LEN ("042"), 3, 42}, {D_STR_W_LEN ("043"), 3, 43}, {D_STR_W_LEN ("044"), 3, 44}, {D_STR_W_LEN ("045"), 3, 45}, {D_STR_W_LEN ("046"), 3, 46}, {D_STR_W_LEN ("047"), 3, 47}, {D_STR_W_LEN ("048"), 3, 48}, {D_STR_W_LEN ("049"), 3, 49}, {D_STR_W_LEN ("050"), 3, 50}, {D_STR_W_LEN ("051"), 3, 51}, {D_STR_W_LEN ("052"), 3, 52}, {D_STR_W_LEN ("053"), 3, 53}, {D_STR_W_LEN ("054"), 3, 54}, {D_STR_W_LEN ("055"), 3, 55}, {D_STR_W_LEN ("056"), 3, 56}, {D_STR_W_LEN ("057"), 3, 57}, {D_STR_W_LEN ("058"), 3, 58}, {D_STR_W_LEN ("059"), 3, 59}, {D_STR_W_LEN ("060"), 3, 60}, {D_STR_W_LEN ("061"), 3, 61}, {D_STR_W_LEN ("062"), 3, 62}, {D_STR_W_LEN ("063"), 3, 63}, {D_STR_W_LEN ("064"), 3, 64}, {D_STR_W_LEN ("065"), 3, 65}, {D_STR_W_LEN ("066"), 3, 66}, {D_STR_W_LEN ("067"), 3, 67}, {D_STR_W_LEN ("068"), 3, 68}, {D_STR_W_LEN ("069"), 3, 69}, {D_STR_W_LEN ("070"), 3, 70}, {D_STR_W_LEN ("071"), 3, 71}, {D_STR_W_LEN ("072"), 3, 72}, {D_STR_W_LEN ("073"), 3, 73}, {D_STR_W_LEN ("074"), 3, 74}, {D_STR_W_LEN ("075"), 3, 75}, {D_STR_W_LEN ("076"), 3, 76}, {D_STR_W_LEN ("077"), 3, 77}, {D_STR_W_LEN ("078"), 3, 78}, {D_STR_W_LEN ("079"), 3, 79}, {D_STR_W_LEN ("080"), 3, 80}, {D_STR_W_LEN ("081"), 3, 81}, {D_STR_W_LEN ("082"), 3, 82}, {D_STR_W_LEN ("083"), 3, 83}, {D_STR_W_LEN ("084"), 3, 84}, {D_STR_W_LEN ("085"), 3, 85}, {D_STR_W_LEN ("086"), 3, 86}, {D_STR_W_LEN ("087"), 3, 87}, {D_STR_W_LEN ("088"), 3, 88}, {D_STR_W_LEN ("089"), 3, 89}, {D_STR_W_LEN ("090"), 3, 90}, {D_STR_W_LEN ("091"), 3, 91}, {D_STR_W_LEN ("092"), 3, 92}, {D_STR_W_LEN ("093"), 3, 93}, {D_STR_W_LEN ("094"), 3, 94}, {D_STR_W_LEN ("095"), 3, 95}, {D_STR_W_LEN ("096"), 3, 96}, {D_STR_W_LEN ("097"), 3, 97}, {D_STR_W_LEN ("098"), 3, 98}, {D_STR_W_LEN ("099"), 3, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255} }; static const struct str_with_value *duint8_w_values_p[3] = {duint8_w_values_p1, duint8_w_values_p2, duint8_w_values_p3}; static size_t check_str_from_uint8_pad (void) { int i; uint8_t pad; size_t t_failed = 0; if ((256 != sizeof(duint8_w_values_p1) / sizeof(duint8_w_values_p1[0])) || (256 != sizeof(duint8_w_values_p2) / sizeof(duint8_w_values_p2[0])) || (256 != sizeof(duint8_w_values_p3) / sizeof(duint8_w_values_p3[0]))) { fprintf (stderr, "ERROR: wrong number of items in duint8_w_values_p*.\n"); exit (99); } for (pad = 0; pad <= 3; pad++) { size_t table_num; if (0 != pad) table_num = pad - 1; else table_num = 0; for (i = 0; i <= 255; i++) { const struct str_with_value *const t = duint8_w_values_p[table_num] + i; size_t b_size; size_t rs; char buf[8]; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memset (buf, '#', sizeof(buf)); rs = MHD_uint8_to_str_pad ((uint8_t) t->val, pad, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf," " %d) returned %" PRIuPTR ", while expecting 0.\n", t->val, (int) pad, (int) b_size, (uintptr_t) rs); } } else { if (t->num_of_digt != rs) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf," " %d) returned %" PRIuPTR ", while expecting %d.\n", t->val, (int) pad, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, " "-> \"%.*s\", %d) returned %" PRIuPTR ".\n", t->val, (int) pad, (int) rs, buf, (int) b_size, (uintptr_t) rs); } else if (0 != memcmp (buf + rs, "########", sizeof(buf) - rs)) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d," " -> \"%.*s\", %d) returned %" PRIuPTR " and touched data after the resulting string.\n", t->val, (int) pad, (int) rs, buf, (int) b_size, (uintptr_t) rs); } } } } } if ((verbose > 1) && (0 == t_failed)) printf ("PASSED: MHD_uint8_to_str_pad.\n"); return t_failed; } static int run_str_from_X_tests (void) { size_t str_from_uint16; size_t str_from_uint64; size_t strx_from_uint32; size_t str_from_uint8_pad; size_t failures; failures = 0; str_from_uint16 = check_str_from_uint16 (); if (str_from_uint16 != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint16() failed.\n\n"); failures += str_from_uint16; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint16() successfully " "passed.\n\n"); str_from_uint64 = check_str_from_uint64 (); if (str_from_uint64 != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint16() failed.\n\n"); failures += str_from_uint64; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint16() successfully " "passed.\n\n"); strx_from_uint32 = check_strx_from_uint32 (); if (strx_from_uint32 != 0) { fprintf (stderr, "FAILED: testcase check_strx_from_uint32() failed.\n\n"); failures += strx_from_uint32; } else if (verbose > 1) printf ("PASSED: testcase check_strx_from_uint32() successfully " "passed.\n\n"); str_from_uint8_pad = check_str_from_uint8_pad (); if (str_from_uint8_pad != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint8_pad() failed.\n\n"); failures += str_from_uint8_pad; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint8_pad() successfully " "passed.\n\n"); if (failures) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } int main (int argc, char *argv[]) { if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose") || has_param (argc, argv, "--verbose1")) verbose = 1; if (has_param (argc, argv, "-vv") || has_param (argc, argv, "--verbose2")) verbose = 2; if (has_param (argc, argv, "-vvv") || has_param (argc, argv, "--verbose3")) verbose = 3; if (has_in_name (argv[0], "_to_value")) return run_str_to_X_tests (); if (has_in_name (argv[0], "_from_value")) return run_str_from_X_tests (); return run_eq_neq_str_tests (); } libmicrohttpd-1.0.2/src/microhttpd/test_md5.c0000644000175000017500000004415414760713574016161 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_md5.h * @brief Unit tests for md5 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_md5_wrap.h" #include "test_helpers.h" #include #include #if defined(MHD_MD5_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_MD5_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */ static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[MD5_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0x1c, 0x68, 0xc2, 0xe5, 0x1f, 0x63, 0xc9, 0x5f, 0x17, 0xab, 0x1f, 0x20, 0x8b, 0x86, 0x39, 0x57}}, {D_STR_W_LEN ("Simple string."), {0xf1, 0x2b, 0x7c, 0xad, 0xa0, 0x41, 0xfe, 0xde, 0x4e, 0x68, 0x16, 0x63, 0xb4, 0x60, 0x5d, 0x78}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0x05, 0x61, 0x3a, 0x6b, 0xde, 0x75, 0x3a, 0x45, 0x91, 0xa8, 0x81, 0xb0, 0xa7, 0xe2, 0xe2, 0x0e}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xaf, 0xab, 0xc7, 0xe9, 0xe7, 0x17, 0xbe, 0xd6, 0xc0, 0x0f, 0x78, 0x8c, 0xde, 0xdd, 0x11, 0xd1}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0x7e, 0xe6, 0xdb, 0xe2, 0x76, 0x49, 0x1a, 0xd8, 0xaf, 0xf3, 0x52, 0x2d, 0xd8, 0xfc, 0x89, 0x1e}}, {D_STR_W_LEN (""), {0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e}}, {D_STR_W_LEN ("a"), {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61}}, {D_STR_W_LEN ("abc"), {0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72}}, {D_STR_W_LEN ("message digest"), {0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0}}, {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" \ "0123456789"), {0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f}}, {D_STR_W_LEN ("12345678901234567890123456789012345678901234567890" \ "123456789012345678901234567890"), {0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[MD5_DIGEST_SIZE]; }; static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */ {0x24, 0xa5, 0xef, 0x36, 0x82, 0x80, 0x3a, 0x06, 0x2f, 0xea, 0xad, 0xad, 0x76, 0xda, 0xbd, 0xa8}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0x6d, 0x2e, 0x6e, 0xde, 0x5d, 0x64, 0x6a, 0x17, 0xf1, 0x09, 0x2c, 0xac, 0x19, 0x10, 0xe3, 0xd6}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x88, 0x13, 0x48, 0x47, 0x73, 0xaa, 0x92, 0xf2, 0xc9, 0xdd, 0x69, 0xb3, 0xac, 0xf4, 0xba, 0x6e}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x80, 0xf0, 0x05, 0x7e, 0xa2, 0xf7, 0xc8, 0x43, 0x12, 0xd3, 0xb1, 0x61, 0xab, 0x52, 0x3b, 0xaf}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72},/* 1..72 sequence */ {0xc3, 0x28, 0xc5, 0xad, 0xc9, 0x26, 0xa9, 0x99, 0x95, 0x4a, 0x5e, 0x25, 0x50, 0x34, 0x51, 0x73}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0xe2, 0xc8, 0x65, 0xdb, 0x41, 0x62, 0xbe, 0xd9, 0x63, 0xbf, 0xaa, 0x9e, 0xf6, 0xac, 0x18, 0xf0}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0xbb, 0x3f, 0xdb, 0x4a, 0x96, 0x03, 0x36, 0x37, 0x38, 0x78, 0x5e, 0x44, 0xbf, 0x3a, 0x85, 0x51}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x52, 0x21, 0xa5, 0x83, 0x4f, 0x38, 0x7c, 0x73, 0xba, 0x18, 0x22, 0xb1, 0xf9, 0x7e, 0xae, 0x8b}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x55, 0x61, 0x2c, 0xeb, 0x29, 0xee, 0xa8, 0xb2, 0xf6, 0x10, 0x7b, 0xc1, 0x5b, 0x0f, 0x01, 0x95}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[MD5_DIGEST_SIZE], const uint8_t expected[MD5_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, MD5_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[MD5_DIGEST_STRING_SIZE]; char expc_str[MD5_DIGEST_STRING_SIZE]; bin2hex (calculated, MD5_DIGEST_SIZE, calc_str); bin2hex (expected, MD5_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[MD5_DIGEST_STRING_SIZE]; bin2hex (calculated, MD5_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s " "matches expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated MD5 as one pass for whole data */ static int test1_str (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } static int test1_bin (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } /* Calculated MD5 as two iterations for whole data */ static int test2_str (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } static int test2_bin (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Md5CtxWr ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (MD5_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); MHD_MD5_init_one_time (&ctx); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, MD5_DIGEST_SIZE); MHD_MD5_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_MD5_finish_reset (&ctx, unaligned_digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } MHD_MD5_deinit (&ctx); free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/connection_https.h0000644000175000017500000000444214760713577020022 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2008 Daniel Pittman and Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection_https.h * @brief Methods for managing connections * @author Christian Grothoff */ #ifndef CONNECTION_HTTPS_H #define CONNECTION_HTTPS_H #include "internal.h" #ifdef HTTPS_SUPPORT /** * Set connection callback function to be used through out * the processing of this secure connection. * * @param connection which callbacks should be modified */ void MHD_set_https_callbacks (struct MHD_Connection *connection); /** * Give gnuTLS chance to work on the TLS handshake. * * @param connection connection to handshake on * @return true if the handshake has completed successfully * and we should start to read/write data, * false is handshake in progress or in case * of error */ bool MHD_run_tls_handshake_ (struct MHD_Connection *connection); /** * Initiate shutdown of TLS layer of connection. * * @param connection to use * @return true if succeed, false otherwise. */ bool MHD_tls_connection_shutdown (struct MHD_Connection *connection); /** * Callback for writing data to the socket. * * @param connection the MHD connection structure * @param other data to write * @param i number of bytes to write * @return positive value for number of bytes actually sent or * negative value for error number MHD_ERR_xxx_ */ ssize_t send_tls_adapter (struct MHD_Connection *connection, const void *other, size_t i); #endif /* HTTPS_SUPPORT */ #endif libmicrohttpd-1.0.2/src/microhttpd/mhd_mono_clock.c0000644000175000017500000003447615035214301017372 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_mono_clock.h * @brief internal monotonic clock functions implementations * @author Karlson2k (Evgeny Grin) */ #include "mhd_mono_clock.h" #if defined(_WIN32) && ! defined(__CYGWIN__) /* Prefer native clock source over wrappers */ #ifdef HAVE_CLOCK_GETTIME #undef HAVE_CLOCK_GETTIME #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_GETTIMEOFDAY #undef HAVE_GETTIMEOFDAY #endif /* HAVE_GETTIMEOFDAY */ #endif /* _WIN32 && ! __CYGWIN__ */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #ifdef HAVE_SYS_TIME_H #include #endif /* HAVE_SYS_TIME_H */ #ifdef HAVE_CLOCK_GET_TIME #include /* for host_get_clock_service(), mach_host_self(), mach_task_self() */ #include /* for clock_get_time() */ #define _MHD_INVALID_CLOCK_SERV ((clock_serv_t) -2) static clock_serv_t mono_clock_service = _MHD_INVALID_CLOCK_SERV; #endif /* HAVE_CLOCK_GET_TIME */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #include #endif /* _WIN32 */ #ifndef NULL #define NULL ((void*)0) #endif /* ! NULL */ #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_REALTIME #define _MHD_UNWANTED_CLOCK CLOCK_REALTIME #else /* !CLOCK_REALTIME */ #define _MHD_UNWANTED_CLOCK ((clockid_t) -2) #endif /* !CLOCK_REALTIME */ static clockid_t mono_clock_id = _MHD_UNWANTED_CLOCK; #endif /* HAVE_CLOCK_GETTIME */ /* sync clocks; reduce chance of value wrap */ #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GET_TIME) || \ defined(HAVE_GETHRTIME) static time_t mono_clock_start; #endif /* HAVE_CLOCK_GETTIME || HAVE_CLOCK_GET_TIME || HAVE_GETHRTIME */ #if defined(HAVE_TIMESPEC_GET) || defined(HAVE_GETTIMEOFDAY) /* The start value shared for timespec_get() and gettimeofday () */ static time_t gettime_start; #endif /* HAVE_TIMESPEC_GET || HAVE_GETTIMEOFDAY */ static time_t sys_clock_start; #ifdef HAVE_GETHRTIME static hrtime_t hrtime_start; #endif /* HAVE_GETHRTIME */ #ifdef _WIN32 #if _WIN32_WINNT >= 0x0600 static uint64_t tick_start; #else /* _WIN32_WINNT < 0x0600 */ static uint64_t perf_freq; static uint64_t perf_start; #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ /** * Type of monotonic clock source */ enum _MHD_mono_clock_source { /** * No monotonic clock */ _MHD_CLOCK_NO_SOURCE = 0, /** * clock_gettime() with specific clock */ _MHD_CLOCK_GETTIME, /** * clock_get_time() with specific clock service */ _MHD_CLOCK_GET_TIME, /** * gethrtime() / 1000000000 */ _MHD_CLOCK_GETHRTIME, /** * GetTickCount64() / 1000 */ _MHD_CLOCK_GETTICKCOUNT64, /** * QueryPerformanceCounter() / QueryPerformanceFrequency() */ _MHD_CLOCK_PERFCOUNTER }; /** * Initialise monotonic seconds and milliseconds counters. */ void MHD_monotonic_sec_counter_init (void) { #ifdef HAVE_CLOCK_GET_TIME mach_timespec_t cur_time; #endif /* HAVE_CLOCK_GET_TIME */ enum _MHD_mono_clock_source mono_clock_source = _MHD_CLOCK_NO_SOURCE; #ifdef HAVE_CLOCK_GETTIME struct timespec ts; mono_clock_id = _MHD_UNWANTED_CLOCK; #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME mono_clock_service = _MHD_INVALID_CLOCK_SERV; #endif /* HAVE_CLOCK_GET_TIME */ /* just a little syntactic trick to get the various following ifdef's to work out nicely */ if (0) { (void) 0; /* Mute possible compiler warning */ } else #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_MONOTONIC_COARSE /* Linux-specific fast value-getting clock */ /* Can be affected by frequency adjustment and don't count time in suspend, */ /* but preferred since it's fast */ if (0 == clock_gettime (CLOCK_MONOTONIC_COARSE, &ts)) { mono_clock_id = CLOCK_MONOTONIC_COARSE; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_COARSE */ #ifdef CLOCK_MONOTONIC_FAST /* FreeBSD/DragonFly fast value-getting clock */ /* Can be affected by frequency adjustment, but preferred since it's fast */ if (0 == clock_gettime (CLOCK_MONOTONIC_FAST, &ts)) { mono_clock_id = CLOCK_MONOTONIC_FAST; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_COARSE */ #ifdef CLOCK_MONOTONIC_RAW_APPROX /* Darwin-specific clock */ /* Not affected by frequency adjustment, returns clock value cached at * context switch. Can be "milliseconds old", but it's fast. */ if (0 == clock_gettime (CLOCK_MONOTONIC_RAW_APPROX, &ts)) { mono_clock_id = CLOCK_MONOTONIC_RAW_APPROX; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_RAW */ #ifdef CLOCK_MONOTONIC_RAW /* Linux and Darwin clock */ /* Not affected by frequency adjustment, * on Linux don't count time in suspend */ if (0 == clock_gettime (CLOCK_MONOTONIC_RAW, &ts)) { mono_clock_id = CLOCK_MONOTONIC_RAW; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_RAW */ #ifdef CLOCK_BOOTTIME /* Count time in suspend on Linux so it's real monotonic, */ /* but can be slower value-getting than other clocks */ if (0 == clock_gettime (CLOCK_BOOTTIME, &ts)) { mono_clock_id = CLOCK_BOOTTIME; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_BOOTTIME */ #ifdef CLOCK_MONOTONIC /* Monotonic clock */ /* Widely supported, may be affected by frequency adjustment */ /* On Linux it's not truly monotonic as it doesn't count time in suspend */ if (0 == clock_gettime (CLOCK_MONOTONIC, &ts)) { mono_clock_id = CLOCK_MONOTONIC; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC */ #ifdef CLOCK_UPTIME /* non-Linux clock */ /* Doesn't count time in suspend */ if (0 == clock_gettime (CLOCK_UPTIME, &ts)) { mono_clock_id = CLOCK_UPTIME; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_BOOTTIME */ #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME /* Darwin-specific monotonic clock */ /* Should be monotonic as clock_set_time function always unconditionally */ /* failed on latest kernels */ if ( (KERN_SUCCESS == host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &mono_clock_service)) && (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) ) { mono_clock_start = cur_time.tv_sec; mono_clock_source = _MHD_CLOCK_GET_TIME; } else #endif /* HAVE_CLOCK_GET_TIME */ #ifdef _WIN32 #if _WIN32_WINNT >= 0x0600 /* W32 Vista or later specific monotonic clock */ /* Available since Vista, ~15ms accuracy */ if (1) { tick_start = GetTickCount64 (); mono_clock_source = _MHD_CLOCK_GETTICKCOUNT64; } else #else /* _WIN32_WINNT < 0x0600 */ /* W32 specific monotonic clock */ /* Available on Windows 2000 and later */ if (1) { LARGE_INTEGER freq; LARGE_INTEGER perf_counter; QueryPerformanceFrequency (&freq); /* never fail on XP and later */ QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ perf_freq = (uint64_t) freq.QuadPart; perf_start = (uint64_t) perf_counter.QuadPart; mono_clock_source = _MHD_CLOCK_PERFCOUNTER; } else #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_HIGHRES /* Solaris-specific monotonic high-resolution clock */ /* Not preferred due to be potentially resource-hungry */ if (0 == clock_gettime (CLOCK_HIGHRES, &ts)) { mono_clock_id = CLOCK_HIGHRES; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_HIGHRES */ #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_GETHRTIME /* HP-UX and Solaris monotonic clock */ /* Not preferred due to be potentially resource-hungry */ if (1) { hrtime_start = gethrtime (); mono_clock_source = _MHD_CLOCK_GETHRTIME; } else #endif /* HAVE_GETHRTIME */ { /* no suitable clock source was found */ mono_clock_source = _MHD_CLOCK_NO_SOURCE; } #ifdef HAVE_CLOCK_GET_TIME if ( (_MHD_CLOCK_GET_TIME != mono_clock_source) && (_MHD_INVALID_CLOCK_SERV != mono_clock_service) ) { /* clock service was initialised but clock_get_time failed */ mach_port_deallocate (mach_task_self (), mono_clock_service); mono_clock_service = _MHD_INVALID_CLOCK_SERV; } #else (void) mono_clock_source; /* avoid compiler warning */ #endif /* HAVE_CLOCK_GET_TIME */ #ifdef HAVE_TIMESPEC_GET if (1) { struct timespec tsg; if (TIME_UTC == timespec_get (&tsg, TIME_UTC)) gettime_start = tsg.tv_sec; else gettime_start = 0; } #elif defined(HAVE_GETTIMEOFDAY) if (1) { struct timeval tv; if (0 == gettimeofday (&tv, NULL)) gettime_start = tv.tv_sec; else gettime_start = 0; } #endif /* HAVE_GETTIMEOFDAY */ sys_clock_start = time (NULL); } /** * Deinitialise monotonic seconds and milliseconds counters by freeing * any allocated resources */ void MHD_monotonic_sec_counter_finish (void) { #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_port_deallocate (mach_task_self (), mono_clock_service); mono_clock_service = _MHD_INVALID_CLOCK_SERV; } #endif /* HAVE_CLOCK_GET_TIME */ } /** * Monotonic seconds counter. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of seconds from some fixed moment */ time_t MHD_monotonic_sec_counter (void) { #ifdef HAVE_CLOCK_GETTIME struct timespec ts; if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) && (0 == clock_gettime (mono_clock_id, &ts)) ) return ts.tv_sec - mono_clock_start; #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_timespec_t cur_time; if (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) return cur_time.tv_sec - mono_clock_start; } #endif /* HAVE_CLOCK_GET_TIME */ #if defined(_WIN32) #if _WIN32_WINNT >= 0x0600 if (1) return (time_t) (((uint64_t) (GetTickCount64 () - tick_start)) / 1000); #else /* _WIN32_WINNT < 0x0600 */ if (0 != perf_freq) { LARGE_INTEGER perf_counter; QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ return (time_t) (((uint64_t) perf_counter.QuadPart - perf_start) / perf_freq); } #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_GETHRTIME if (1) return (time_t) (((uint64_t) (gethrtime () - hrtime_start)) / 1000000000); #endif /* HAVE_GETHRTIME */ return time (NULL) - sys_clock_start; } /** * Monotonic milliseconds counter, useful for timeout calculation. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of microseconds from some fixed moment */ uint64_t MHD_monotonic_msec_counter (void) { #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_TIMESPEC_GET) struct timespec ts; #endif /* HAVE_CLOCK_GETTIME || HAVE_TIMESPEC_GET */ #ifdef HAVE_CLOCK_GETTIME if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) && (0 == clock_gettime (mono_clock_id, &ts)) ) return (uint64_t) (((uint64_t) (ts.tv_sec - mono_clock_start)) * 1000 + (uint64_t) (ts.tv_nsec / 1000000)); #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_timespec_t cur_time; if (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) return (uint64_t) (((uint64_t) (cur_time.tv_sec - mono_clock_start)) * 1000 + (uint64_t) (cur_time.tv_nsec / 1000000)); } #endif /* HAVE_CLOCK_GET_TIME */ #if defined(_WIN32) #if _WIN32_WINNT >= 0x0600 if (1) return (uint64_t) (GetTickCount64 () - tick_start); #else /* _WIN32_WINNT < 0x0600 */ if (0 != perf_freq) { LARGE_INTEGER perf_counter; uint64_t num_ticks; QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ num_ticks = (uint64_t) (perf_counter.QuadPart - perf_start); return ((num_ticks / perf_freq) * 1000) + ((num_ticks % perf_freq) / (perf_freq / 1000)); } #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_GETHRTIME if (1) return ((uint64_t) (gethrtime () - hrtime_start)) / 1000000; #endif /* HAVE_GETHRTIME */ /* Fallbacks, affected by system time change */ #ifdef HAVE_TIMESPEC_GET if (TIME_UTC == timespec_get (&ts, TIME_UTC)) return (uint64_t) (((uint64_t) (ts.tv_sec - gettime_start)) * 1000 + (uint64_t) (ts.tv_nsec / 1000000)); #elif defined(HAVE_GETTIMEOFDAY) if (1) { struct timeval tv; if (0 == gettimeofday (&tv, NULL)) return (uint64_t) (((uint64_t) (tv.tv_sec - gettime_start)) * 1000 + (uint64_t) (tv.tv_usec / 1000)); } #endif /* HAVE_GETTIMEOFDAY */ /* The last resort fallback with very low resolution */ return (uint64_t) (time (NULL) - sys_clock_start) * 1000; } libmicrohttpd-1.0.2/src/microhttpd/sha1.c0000644000175000017500000003757714760713574015304 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2022 Karlson2k (Evgeny Grin) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.c * @brief Calculation of SHA-1 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha1.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA-1 calculation. * * @param ctx_ must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_) { struct sha1_ctx *const ctx = ctx_; /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.1 */ /* Just some "magic" numbers defined by standard */ ctx->H[0] = UINT32_C (0x67452301); ctx->H[1] = UINT32_C (0xefcdab89); ctx->H[2] = UINT32_C (0x98badcfe); ctx->H[3] = UINT32_C (0x10325476); ctx->H[4] = UINT32_C (0xc3d2e1f0); /* Initialise number of bytes. */ ctx->count = 0; } /** * Base of SHA-1 transformation. * Gets full 512 bits / 64 bytes block of data and updates hash values; * @param H hash values * @param data data, must be exactly 64 bytes long */ static void sha1_transform (uint32_t H[_SHA1_DIGEST_LENGTH], const uint8_t data[SHA1_BLOCK_SIZE]) { /* Working variables, see FIPS PUB 180-4 paragraph 6.1.3 */ uint32_t a = H[0]; uint32_t b = H[1]; uint32_t c = H[2]; uint32_t d = H[3]; uint32_t e = H[4]; /* Data buffer, used as cyclic buffer. See FIPS PUB 180-4 paragraphs 5.2.1, 6.1.3 */ uint32_t W[16]; /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. See FIPS PUB 180-4 formulae 4.1. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ #define Par(x,y,z) ( (x) ^ (y) ^ (z) ) /* Single step of SHA-1 computation, see FIPS PUB 180-4 paragraph 6.1.3 step 3. * Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA1STEP32 (a, b, c, d, e, func, K00, W[0]); SHA1STEP32 (e, a, b, c, d, func, K00, W[1]); so current 'vC' will be used as 'vD' on the next step, current 'vE' will be used as 'vA' on the next step. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA1STEP32(vA,vB,vC,vD,vE,ft,kt,wt) do { \ (vE) += _MHD_ROTL32 ((vA), 5) + ft ((vB), (vC), (vD)) + (kt) + (wt); \ (vB) = _MHD_ROTL32 ((vB), 30); } while (0) /* Get value of W(t) from input data buffer, See FIPS PUB 180-4 paragraph 6.1.3. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 paragraph 3.1.2. */ /* Use cast to (void*) to mute compiler alignment warning, * data was already aligned in previous step */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_32BIT_BE ((const void *)(((const uint8_t*) (buf)) + \ (t) * SHA1_BYTES_IN_WORD)) #ifndef _MHD_GET_32BIT_BE_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN)) { /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, SHA1_BLOCK_SIZE); /* The W[] buffer itself will be used as the source of the data, * but data will be reloaded in correct bytes order during * the next steps */ data = (uint8_t *) W; } #endif /* _MHD_GET_32BIT_BE_UNALIGNED */ /* SHA-1 values of Kt for t=0..19, see FIPS PUB 180-4 paragraph 4.2.1. */ #define K00 UINT32_C(0x5a827999) /* SHA-1 values of Kt for t=20..39, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K20 UINT32_C(0x6ed9eba1) /* SHA-1 values of Kt for t=40..59, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K40 UINT32_C(0x8f1bbcdc) /* SHA-1 values of Kt for t=60..79, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K60 UINT32_C(0xca62c1d6) /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ /* Note: instead of using K constants as array, all K values are specified individually for each step. */ SHA1STEP32 (a, b, c, d, e, Ch, K00, W[0] = GET_W_FROM_DATA (data, 0)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[1] = GET_W_FROM_DATA (data, 1)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[2] = GET_W_FROM_DATA (data, 2)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[3] = GET_W_FROM_DATA (data, 3)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[4] = GET_W_FROM_DATA (data, 4)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[5] = GET_W_FROM_DATA (data, 5)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[6] = GET_W_FROM_DATA (data, 6)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[7] = GET_W_FROM_DATA (data, 7)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[8] = GET_W_FROM_DATA (data, 8)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[9] = GET_W_FROM_DATA (data, 9)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[10] = GET_W_FROM_DATA (data, 10)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[11] = GET_W_FROM_DATA (data, 11)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[12] = GET_W_FROM_DATA (data, 12)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[13] = GET_W_FROM_DATA (data, 13)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[14] = GET_W_FROM_DATA (data, 14)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[15] = GET_W_FROM_DATA (data, 15)); /* 'W' generation and assignment for 16 <= t <= 79. See FIPS PUB 180-4 paragraph 6.1.3. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as cyclic buffer. */ #define Wgen(w,t) _MHD_ROTL32((w)[(t + 13) & 0xf] ^ (w)[(t + 8) & 0xf] \ ^ (w)[(t + 2) & 0xf] ^ (w)[t & 0xf], 1) /* During last 60 steps, before making any calculations on each step, W element is generated from W elements of cyclic buffer and generated value stored back in cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.1. */ SHA1STEP32 (e, a, b, c, d, Ch, K00, W[16 & 0xf] = Wgen (W, 16)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[17 & 0xf] = Wgen (W, 17)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[18 & 0xf] = Wgen (W, 18)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[19 & 0xf] = Wgen (W, 19)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[20 & 0xf] = Wgen (W, 20)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[21 & 0xf] = Wgen (W, 21)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[22 & 0xf] = Wgen (W, 22)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[23 & 0xf] = Wgen (W, 23)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[24 & 0xf] = Wgen (W, 24)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[25 & 0xf] = Wgen (W, 25)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[26 & 0xf] = Wgen (W, 26)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[27 & 0xf] = Wgen (W, 27)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[28 & 0xf] = Wgen (W, 28)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[29 & 0xf] = Wgen (W, 29)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[30 & 0xf] = Wgen (W, 30)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[31 & 0xf] = Wgen (W, 31)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[32 & 0xf] = Wgen (W, 32)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[33 & 0xf] = Wgen (W, 33)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[34 & 0xf] = Wgen (W, 34)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[35 & 0xf] = Wgen (W, 35)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[36 & 0xf] = Wgen (W, 36)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[37 & 0xf] = Wgen (W, 37)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[38 & 0xf] = Wgen (W, 38)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[39 & 0xf] = Wgen (W, 39)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[40 & 0xf] = Wgen (W, 40)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[41 & 0xf] = Wgen (W, 41)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[42 & 0xf] = Wgen (W, 42)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[43 & 0xf] = Wgen (W, 43)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[44 & 0xf] = Wgen (W, 44)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[45 & 0xf] = Wgen (W, 45)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[46 & 0xf] = Wgen (W, 46)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[47 & 0xf] = Wgen (W, 47)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[48 & 0xf] = Wgen (W, 48)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[49 & 0xf] = Wgen (W, 49)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[50 & 0xf] = Wgen (W, 50)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[51 & 0xf] = Wgen (W, 51)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[52 & 0xf] = Wgen (W, 52)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[53 & 0xf] = Wgen (W, 53)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[54 & 0xf] = Wgen (W, 54)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[55 & 0xf] = Wgen (W, 55)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[56 & 0xf] = Wgen (W, 56)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[57 & 0xf] = Wgen (W, 57)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[58 & 0xf] = Wgen (W, 58)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[59 & 0xf] = Wgen (W, 59)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[60 & 0xf] = Wgen (W, 60)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[61 & 0xf] = Wgen (W, 61)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[62 & 0xf] = Wgen (W, 62)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[63 & 0xf] = Wgen (W, 63)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[64 & 0xf] = Wgen (W, 64)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[65 & 0xf] = Wgen (W, 65)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[66 & 0xf] = Wgen (W, 66)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[67 & 0xf] = Wgen (W, 67)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[68 & 0xf] = Wgen (W, 68)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[69 & 0xf] = Wgen (W, 69)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[70 & 0xf] = Wgen (W, 70)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[71 & 0xf] = Wgen (W, 71)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[72 & 0xf] = Wgen (W, 72)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[73 & 0xf] = Wgen (W, 73)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[74 & 0xf] = Wgen (W, 74)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[75 & 0xf] = Wgen (W, 75)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[76 & 0xf] = Wgen (W, 76)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[77 & 0xf] = Wgen (W, 77)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[78 & 0xf] = Wgen (W, 78)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[79 & 0xf] = Wgen (W, 79)); /* Compute intermediate hash. See FIPS PUB 180-4 paragraph 6.1.3 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; } /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length) { struct sha1_ctx *const ctx = ctx_; unsigned bytes_have; /**< Number of bytes in buffer */ mhd_assert ((data != NULL) || (length == 0)); if (0 == length) return; /* Do nothing */ /* Note: (count & (SHA1_BLOCK_SIZE-1)) equal (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned bytes_left = SHA1_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with the data in the buffer and process the full block. */ memcpy (ctx->buffer + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha1_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA1_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha1_transform (ctx->H, data); data += SHA1_BLOCK_SIZE; length -= SHA1_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (ctx->buffer + bytes_have, data, length); } } /** * Size of "length" padding addition in bytes. * See FIPS PUB 180-4 paragraph 5.1.1. */ #define SHA1_SIZE_OF_LEN_ADD (64 / 8) /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]) { struct sha1_ctx *const ctx = ctx_; uint64_t num_bits; /**< Number of processed bits */ unsigned bytes_have; /**< Number of bytes in buffer */ num_bits = ctx->count << 3; /* Note: (count & (SHA1_BLOCK_SIZE-1)) equals (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); /* Input data must be padded with bit "1" and with length of data in bits. See FIPS PUB 180-4 paragraph 5.1.1. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of first padding bit in byte is always predefined (0x80). */ /* Buffer always have space at least for one byte (as full buffers are processed immediately). */ ctx->buffer[bytes_have++] = 0x80; if (SHA1_BLOCK_SIZE - bytes_have < SHA1_SIZE_OF_LEN_ADD) { /* No space in current block to put total length of message. Pad current block with zeros and process it. */ if (SHA1_BLOCK_SIZE > bytes_have) memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - bytes_have); /* Process full block. */ sha1_transform (ctx->H, ctx->buffer); /* Start new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in the processed message as a big-endian value. */ _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD, num_bits); /* Process the full final block. */ sha1_transform (ctx->H, ctx->buffer); /* Put final hash/digest in BE mode */ #ifndef _MHD_PUT_32BIT_BE_UNALIGNED if (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) { uint32_t alig_dgst[_SHA1_DIGEST_LENGTH]; _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]); _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]); /* Copy result to unaligned destination address */ memcpy (digest, alig_dgst, SHA1_DIGEST_SIZE); } else #else /* _MHD_PUT_32BIT_BE_UNALIGNED */ if (1) #endif /* _MHD_PUT_32BIT_BE_UNALIGNED */ { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA1_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA1_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA1_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA1_BYTES_IN_WORD), ctx->H[3]); _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA1_BYTES_IN_WORD), ctx->H[4]); } /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct sha1_ctx)); } libmicrohttpd-1.0.2/src/microhttpd/test_str_token_remove.c0000644000175000017500000002755714760713574021071 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for MHD_str_remove_token_caseless_() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" static int expect_result_n (const char *str, size_t str_len, const char *token, size_t token_len, const char *expected, size_t expected_len, const bool expected_removed) { char buf_in[1024]; char buf_token[256]; char buf_out[1024]; size_t buf_len; mhd_assert (sizeof(buf_in) > str_len + 2); mhd_assert (sizeof(buf_token) > token_len + 2); mhd_assert (sizeof(buf_out) > expected_len + 2); memset (buf_in, '#', sizeof(buf_in)); memset (buf_token, '#', sizeof(buf_token)); memcpy (buf_in, str, str_len); /* Copy without zero-termination */ memcpy (buf_token, token, token_len); /* Copy without zero-termination */ for (buf_len = 0; buf_len <= expected_len + 3; ++buf_len) { bool res; ssize_t result_len; memset (buf_out, '$', sizeof(buf_out)); result_len = (ssize_t) buf_len; mhd_assert (0 <= result_len); res = MHD_str_remove_token_caseless_ (buf_in, str_len, buf_token, token_len, buf_out, &result_len); if (buf_len < expected_len) { /* The result should not fit into the buffer */ if (res || (0 <= result_len)) { fprintf (stderr, "MHD_str_remove_token_caseless_() FAILED:\n" "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu," " \"%.*s\", %lu, buf, &(%ld->%ld)) returned %s\n", (int) str_len + 2, buf_in, (unsigned long) str_len, (int) token_len + 2, buf_token, (unsigned long) token_len, (long) buf_len, (long) result_len, res ? "true" : "false"); return 1; } } else { /* The result should fit into the buffer */ if ( (expected_removed != res) || (result_len < 0) || (expected_len != (size_t) result_len) || ((0 != result_len) && (0 != memcmp (expected, buf_out, (size_t) result_len))) || ('$' != buf_out[result_len])) { fprintf (stderr, "MHD_str_remove_token_caseless_() FAILED:\n" "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu," " \"%.*s\", %lu, \"%.*s\", &(%ld->%ld)) returned %s\n", (int) str_len + 2, buf_in, (unsigned long) str_len, (int) token_len + 2, buf_token, (unsigned long) token_len, (int) expected_len + 2, buf_out, (long) buf_len, (long) result_len, res ? "true" : "false"); return 1; } } } return 0; } #define expect_result(s,t,e,found) \ expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \ (t),MHD_STATICSTR_LEN_ (t), \ (e),MHD_STATICSTR_LEN_ (e), found) static int check_result (void) { int errcount = 0; errcount += expect_result ("string", "string", "", true); errcount += expect_result ("String", "string", "", true); errcount += expect_result ("string", "String", "", true); errcount += expect_result ("strinG", "String", "", true); errcount += expect_result ("\t strinG", "String", "", true); errcount += expect_result ("strinG\t ", "String", "", true); errcount += expect_result (" \t tOkEn ", "toKEN", "", true); errcount += expect_result ("not token\t, tOkEn ", "toKEN", "not token", true); errcount += expect_result ("not token,\t tOkEn, more token", "toKEN", "not token, more token", true); errcount += expect_result ("not token,\t tOkEn\t, more token", "toKEN", "not token, more token", true); errcount += expect_result (",,,,,,test,,,,", "TESt", "", true); errcount += expect_result (",,,,,\t,test,,,,", "TESt", "", true); errcount += expect_result (",,,,,,test, ,,,", "TESt", "", true); errcount += expect_result (",,,,,, test,,,,", "TESt", "", true); errcount += expect_result (",,,,,, test not,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test not,,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test not ,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test", "TESt", "", true); errcount += expect_result (",,,,,, test ", "TESt", "", true); errcount += expect_result ("no test,,,,,, test ", "TESt", "no test", true); errcount += expect_result ("the-token,, the-token , the-token" \ ",the-token ,the-token", "the-token", "", true); errcount += expect_result (" the-token,, the-token , the-token," \ "the-token ,the-token ", "the-token", "", true); errcount += expect_result (" the-token ,, the-token , the-token," \ "the-token , the-token ", "the-token", "", true); errcount += expect_result ("the-token,a, the-token , the-token,b," \ "the-token , c,the-token", "the-token", "a, b, c", true); errcount += expect_result (" the-token, a, the-token , the-token, b," \ "the-token ,c ,the-token ", "the-token", "a, b, c", true); errcount += expect_result (" the-token , a , the-token , the-token, b ," \ "the-token , c , the-token ", "the-token", "a, b, c",true); errcount += expect_result ("the-token,aa, the-token , the-token,bb," \ "the-token , cc,the-token", "the-token", "aa, bb, cc", true); errcount += expect_result (" the-token, aa, the-token , the-token, bb," \ "the-token ,cc ,the-token ", "the-token", "aa, bb, cc", true); errcount += expect_result (" the-token , aa , the-token , the-token, bb ," \ "the-token , cc , the-token ", "the-token", "aa, bb, cc", true); errcount += expect_result ("strin", "string", "strin", false); errcount += expect_result ("Stringer", "string", "Stringer", false); errcount += expect_result ("sstring", "String", "sstring", false); errcount += expect_result ("string", "Strin", "string", false); errcount += expect_result ("\t( strinG", "String", "( strinG", false); errcount += expect_result (")strinG\t ", "String", ")strinG", false); errcount += expect_result (" \t tOkEn t ", "toKEN", "tOkEn t", false); errcount += expect_result ("not token\t, tOkEner ", "toKEN", "not token, tOkEner", false); errcount += expect_result ("not token,\t tOkEns, more token", "toKEN", "not token, tOkEns, more token", false); errcount += expect_result ("not token,\t tOkEns\t, more token", "toKEN", "not token, tOkEns, more token", false); errcount += expect_result (",,,,,,testing,,,,", "TESt", "testing", false); errcount += expect_result (",,,,,\t,test,,,,", "TESting", "test", false); errcount += expect_result ("tests,,,,,,quest, ,,,", "TESt", "tests, quest", false); errcount += expect_result (",,,,,, testÑ‹,,,,", "TESt", "testÑ‹", false); errcount += expect_result (",,,,,, test not,Ñ…test,,", "TESt", "test not, Ñ…test", false); errcount += expect_result ("testing,,,,,, test not,,test2,,", "TESt", "testing, test not, test2", false); errcount += expect_result (",testi,,,,, test not ,test,,", "TESting", "testi, test not, test", false); errcount += expect_result (",,,,,,2 test", "TESt", "2 test", false); errcount += expect_result (",,,,,,test test ", "test", "test test", false); errcount += expect_result ("no test,,,,,,test test", "test", "no test, test test", false); errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "the-token", "", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "the-token", "a, b, c, d, e, f, g", false); errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "", "", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "", "a, b, c, d, e, f, g", false); errcount += expect_result ("a,b,c,d,e,f,g", "", "a, b, c, d, e, f, g", false); errcount += expect_result ("a1,b1,c1,d1,e1,f1,g1", "", "a1, b1, c1, d1, e1, f1, g1", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x", "the-token", "a, b, c, d, e, f, g, x", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x", "the-token", "a, b, c, d, e, f, g, the-token x", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,", "the-token", "a, b, c, d, e, f, g, the-token x", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,x", "the-token", "a, b, c, d, e, f, g," \ " the-token x, x", false); errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result ("the-token ,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x", "the-token", "a, b, c, d, e, f, g, x", true); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x", "the-token", "the-token x, a, b, c, d, e, f, g, the-token x", false); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x,", "the-token", "the-token x, a, b, c, d, e, f, g, the-token x", false); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x,x", "the-token", "the-token x, a, b, c, d, e, f, g, " \ "the-token x, x", false); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_result (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/sysfdsetsize.h0000644000175000017500000000276114760713577017202 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/sysfdsetsize.h * @brief Helper for obtaining FD_SETSIZE system default value * @author Karlson2k (Evgeny Grin) */ #ifndef SYSFDSETSIZE_H #define SYSFDSETSIZE_H 1 #include "mhd_options.h" #ifndef MHD_SYS_FD_SETSIZE_ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ unsigned int get_system_fdsetsize_value (void); #else /* MHD_SYS_FD_SETSIZE_ */ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ _MHD_static_inline unsigned int get_system_fdsetsize_value (void) { return (unsigned int) MHD_SYS_FD_SETSIZE_; } #endif /* MHD_SYS_FD_SETSIZE_ */ #endif /* !SYSFDSETSIZE_H */ libmicrohttpd-1.0.2/src/microhttpd/mhd_sha256_wrap.h0000644000175000017500000000600715035214301017302 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_sha256_wrap.h * @brief Simple wrapper for selection of built-in/external SHA-256 * implementation * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_WRAP_H #define MHD_SHA256_WRAP_H 1 #include "mhd_options.h" #include "mhd_options.h" #ifndef MHD_SHA256_SUPPORT #error This file must be used only when SHA-256 is enabled #endif #ifndef MHD_SHA256_TLSLIB #include "sha256.h" #else /* MHD_SHA256_TLSLIB */ #include "sha256_ext.h" #endif /* MHD_SHA256_TLSLIB */ #ifndef SHA256_DIGEST_SIZE /** * Size of SHA-256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA256_DIGEST_SIZE (32) #endif /* ! SHA256_DIGEST_SIZE */ #ifndef SHA256_DIGEST_STRING_SIZE /** * Size of MD5 digest string in chars including termination NUL. */ #define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1) #endif /* ! SHA256_DIGEST_STRING_SIZE */ #ifndef MHD_SHA256_TLSLIB /** * Universal ctx type mapped for chosen implementation */ #define Sha256CtxWr Sha256Ctx #else /* MHD_SHA256_TLSLIB */ /** * Universal ctx type mapped for chosen implementation */ #define Sha256CtxWr Sha256CtxExt #endif /* MHD_SHA256_TLSLIB */ #ifndef MHD_SHA256_HAS_INIT_ONE_TIME /** * Setup and prepare ctx for hash calculation */ #define MHD_SHA256_init_one_time(ctx) MHD_SHA256_init(ctx) #endif /* ! MHD_SHA256_HAS_INIT_ONE_TIME */ #ifndef MHD_SHA256_HAS_FINISH_RESET /** * Re-use the same ctx for the new hashing after digest calculated */ #define MHD_SHA256_reset(ctx) MHD_SHA256_init(ctx) /** * Finalise MD5 calculation, return digest, reset hash calculation. */ #define MHD_SHA256_finish_reset(ctx,digest) MHD_SHA256_finish(ctx,digest), \ MHD_SHA256_reset(ctx) #else /* MHD_SHA256_HAS_FINISH_RESET */ #define MHD_SHA256_reset(ctx) (void)0 #endif /* MHD_SHA256_HAS_FINISH_RESET */ #ifndef MHD_SHA256_HAS_DEINIT #define MHD_SHA256_deinit(ignore) (void)0 #endif /* HAVE_SHA256_DEINIT */ /* Sanity checks */ #if ! defined(MHD_SHA256_HAS_FINISH_RESET) && ! defined(MHD_SHA256_HAS_FINISH) #error Required MHD_SHA256_finish_reset() or MHD_SHA256_finish_reset() #endif /* ! MHD_SHA256_HAS_FINISH_RESET && ! MHD_SHA256_HAS_FINISH */ #endif /* MHD_SHA256_WRAP_H */ libmicrohttpd-1.0.2/src/microhttpd/test_str_quote.c0000644000175000017500000007504414760713574017523 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_quote.c * @brief Unit tests for quoted strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #define TEST_STR_MAX_LEN 1024 /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_unquote_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret1; unsigned int ret2; unsigned int ret3; unsigned int ret4; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); mhd_assert (quoted_len >= unquoted_len); /* First check: MHD_str_unquote () */ ret1 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_unquote (quoted, quoted_len, buf); if (res_len != unquoted_len) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result size:\n"); } else if ((0 != unquoted_len) && (0 != memcmp (buf, unquoted, unquoted_len))) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result string:\n"); } if (0 != ret1) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n" "\tEXPECTED: MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) res_len, buf, (unsigned) res_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } /* Second check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (! MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* Third check: MHD_str_equal_caseless_quoted_bin_n () */ ret3 = 0; if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } /* Fourth check: MHD_str_unquote () */ ret4 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_quote (unquoted, unquoted_len, buf, quoted_len); if (res_len != quoted_len) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result size:\n"); } else if ((0 != quoted_len) && (0 != memcmp (buf, quoted, quoted_len))) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result string:\n"); } if (0 != ret4) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n" "\tEXPECTED: MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n", (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) res_len, buf, (unsigned) quoted_len, (unsigned) res_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret1 + ret2 + ret3 + ret4; } #define expect_result_unquote(q,u) \ expect_result_unquote_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_match (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_unquote ("", ""); r += expect_result_unquote ("a", "a"); r += expect_result_unquote ("abc", "abc"); r += expect_result_unquote ("abcdef", "abcdef"); r += expect_result_unquote ("a\0" "bc", "a\0" "bc"); r += expect_result_unquote ("abc\\\"", "abc\""); r += expect_result_unquote ("\\\"", "\""); r += expect_result_unquote ("\\\"abc", "\"abc"); r += expect_result_unquote ("abc\\\\", "abc\\"); r += expect_result_unquote ("\\\\", "\\"); r += expect_result_unquote ("\\\\abc", "\\abc"); r += expect_result_unquote ("123\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unquote ("\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unquote ("\\\\\\\\\\\\\\\\123", "\\\\\\\\123"); r += expect_result_unquote ("\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"" \ "\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"", \ "\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\""); return r; } /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_quote_failed_n (const char *const unquoted, const size_t unquoted_len, const size_t buf_size, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret4; mhd_assert (TEST_STR_MAX_LEN > buf_size); /* The check: MHD_str_unquote () */ ret4 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_quote (unquoted, unquoted_len, buf, buf_size); if (0 != res_len) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result size:\n"); } if (0 != ret4) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n" "\tEXPECTED: MHD_str_quote('%.*s', %u, (not checked), %u) -> 0\n", (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) res_len, buf, (unsigned) buf_size, (unsigned) res_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (unsigned) buf_size); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret4; } #define expect_result_quote_failed(q,s) \ expect_result_quote_failed_n(q,MHD_STATICSTR_LEN_(q),\ s,__LINE__) static unsigned int check_quote_failed (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_quote_failed ("a", 0); r += expect_result_quote_failed ("aa", 1); r += expect_result_quote_failed ("abc\\", 4); r += expect_result_quote_failed ("abc\"", 4); r += expect_result_quote_failed ("abc\"\"\"\"", 6); r += expect_result_quote_failed ("abc\"\"\"\"", 7); r += expect_result_quote_failed ("abc\"\"\"\"", 8); r += expect_result_quote_failed ("abc\"\"\"\"", 9); r += expect_result_quote_failed ("abc\"\"\"\"", 10); r += expect_result_quote_failed ("abc\\\\\\\\", 9); r += expect_result_quote_failed ("abc\\\\\\\\", 10); r += expect_result_quote_failed ("abc\"\"\"\"", 9); r += expect_result_quote_failed ("abc\"\"\"\"", 10); r += expect_result_quote_failed ("abc\"\\\"\\", 9); r += expect_result_quote_failed ("abc\\\"\\\"", 10); r += expect_result_quote_failed ("\"\"\"\"abc", 6); r += expect_result_quote_failed ("\"\"\"\"abc", 7); r += expect_result_quote_failed ("\"\"\"\"abc", 8); r += expect_result_quote_failed ("\"\"\"\"abc", 9); r += expect_result_quote_failed ("\"\"\"\"abc", 10); r += expect_result_quote_failed ("\\\\\\\\abc", 9); r += expect_result_quote_failed ("\\\\\\\\abc", 10); r += expect_result_quote_failed ("\"\"\"\"abc", 9); r += expect_result_quote_failed ("\"\"\"\"abc", 10); r += expect_result_quote_failed ("\"\\\"\\abc", 9); r += expect_result_quote_failed ("\\\"\\\"abc", 10); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_match_caseless_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); /* The check: MHD_str_equal_caseless_quoted_bin_n () */ ret3 = 0; if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret3; } #define expect_match_caseless(q,u) \ expect_match_caseless_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_match_caseless (void) { unsigned int r = 0; /**< The number of errors */ r += expect_match_caseless ("a", "A"); r += expect_match_caseless ("abC", "aBc"); r += expect_match_caseless ("AbCdeF", "aBCdEF"); r += expect_match_caseless ("a\0" "Bc", "a\0" "bC"); r += expect_match_caseless ("Abc\\\"", "abC\""); r += expect_match_caseless ("\\\"", "\""); r += expect_match_caseless ("\\\"aBc", "\"abc"); r += expect_match_caseless ("abc\\\\", "ABC\\"); r += expect_match_caseless ("\\\\", "\\"); r += expect_match_caseless ("\\\\ABC", "\\abc"); r += expect_match_caseless ("\\\\ZYX", "\\ZYX"); r += expect_match_caseless ("abc", "ABC"); r += expect_match_caseless ("ABCabc", "abcABC"); r += expect_match_caseless ("abcXYZ", "ABCxyz"); r += expect_match_caseless ("AbCdEfABCabc", "ABcdEFabcABC"); r += expect_match_caseless ("a\\\\bc", "A\\BC"); r += expect_match_caseless ("ABCa\\\\bc", "abcA\\BC"); r += expect_match_caseless ("abcXYZ\\\\", "ABCxyz\\"); r += expect_match_caseless ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_invalid_n (const char *const quoted, const size_t quoted_len, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret1; mhd_assert (NULL != quoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); /* The check: MHD_str_unquote () */ ret1 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_unquote (quoted, quoted_len, buf); if (res_len != 0) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result size:\n"); } if (0 != ret1) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_unquote('%.*s', %u, (not checked)) -> %u\n" "\tEXPECTED: MHD_str_unquote('%.*s', %u, (not checked)) -> 0\n", (int) quoted_len, quoted, (unsigned) quoted_len, (unsigned) res_len, (int) quoted_len, quoted, (unsigned) quoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret1; } #define expect_result_invalid(q) \ expect_result_invalid_n(q,MHD_STATICSTR_LEN_(q),__LINE__) static unsigned int check_invalid (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_invalid ("\\"); r += expect_result_invalid ("\\\\\\"); r += expect_result_invalid ("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"); r += expect_result_invalid ("xyz\\"); r += expect_result_invalid ("\\\"\\"); r += expect_result_invalid ("\\\"\\\"\\\"\\"); return r; } /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* The check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* The check: MHD_str_equal_quoted_bin_n () */ ret3 = 0; if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret2 + ret3; } #define expect_result_unmatch(q,u) \ expect_result_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch (void) { unsigned int r = 0; /**< The number of errors */ /* Matched sequence except invalid backslash at the end */ r += expect_result_unmatch ("\\", ""); r += expect_result_unmatch ("a\\", "a"); r += expect_result_unmatch ("abc\\", "abc"); r += expect_result_unmatch ("a\0" "bc\\", "a\0" "bc"); r += expect_result_unmatch ("abc\\\"\\", "abc\""); r += expect_result_unmatch ("\\\"\\", "\""); r += expect_result_unmatch ("\\\"abc\\", "\"abc"); r += expect_result_unmatch ("abc\\\\\\", "abc\\"); r += expect_result_unmatch ("\\\\\\", "\\"); r += expect_result_unmatch ("\\\\abc\\", "\\abc"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", "\\\\\\\\123"); /* Invalid backslash at the end and empty string */ r += expect_result_unmatch ("\\", ""); r += expect_result_unmatch ("a\\", ""); r += expect_result_unmatch ("abc\\", ""); r += expect_result_unmatch ("a\0" "bc\\", ""); r += expect_result_unmatch ("abc\\\"\\", ""); r += expect_result_unmatch ("\\\"\\", ""); r += expect_result_unmatch ("\\\"abc\\", ""); r += expect_result_unmatch ("abc\\\\\\", ""); r += expect_result_unmatch ("\\\\\\", ""); r += expect_result_unmatch ("\\\\abc\\", ""); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", ""); /* Difference at binary zero */ r += expect_result_unmatch ("\0", ""); r += expect_result_unmatch ("", "\0"); r += expect_result_unmatch ("a\0", "a"); r += expect_result_unmatch ("a", "a\0"); r += expect_result_unmatch ("abc\0", "abc"); r += expect_result_unmatch ("abc", "abc\0"); r += expect_result_unmatch ("a\0" "bc\0", "a\0" "bc"); r += expect_result_unmatch ("a\0" "bc", "a\0" "bc\0"); r += expect_result_unmatch ("abc\\\"\0", "abc\""); r += expect_result_unmatch ("abc\\\"", "abc\"\0"); r += expect_result_unmatch ("\\\"\0", "\""); r += expect_result_unmatch ("\\\"", "\"\0"); r += expect_result_unmatch ("\\\"abc\0", "\"abc"); r += expect_result_unmatch ("\\\"abc", "\"abc\0"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0"); r += expect_result_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\"); r += expect_result_unmatch ("\0" "abc", "abc"); r += expect_result_unmatch ("abc", "\0" "abc"); r += expect_result_unmatch ("\0" "abc", "0abc"); r += expect_result_unmatch ("0abc", "\0" "abc"); r += expect_result_unmatch ("xyz", "xy" "\0" "z"); r += expect_result_unmatch ("xy" "\0" "z", "xyz"); /* Difference after binary zero */ r += expect_result_unmatch ("abc\0" "1", "abc\0" "2"); r += expect_result_unmatch ("a\0" "bcx", "a\0" "bcy"); r += expect_result_unmatch ("\0" "abc\\\"2", "\0" "abc\"1"); r += expect_result_unmatch ("\0" "abc1\\\"", "\0" "abc2\""); r += expect_result_unmatch ("\0" "\\\"c", "\0" "\"d"); r += expect_result_unmatch ("\\\"ab" "\0" "1c", "\"ab" "\0" "2c"); r += expect_result_unmatch ("a\0" "bcdef2", "a\0" "bcdef1"); r += expect_result_unmatch ("a\0" "bc2def", "a\0" "bc1def"); r += expect_result_unmatch ("a\0" "1bcdef", "a\0" "2bcdef"); r += expect_result_unmatch ("abcde\0" "f2", "abcde\0" "f1"); r += expect_result_unmatch ("123\\\\\\\\\\\\\0" "\\\\1", "123\\\\\\\0" "\\2"); r += expect_result_unmatch ("\\\\\\\\\\\\\0" "1\\\\", "\\\\\\" "2\\"); /* One side is empty */ r += expect_result_unmatch ("abc", ""); r += expect_result_unmatch ("", "abc"); r += expect_result_unmatch ("1234567890", ""); r += expect_result_unmatch ("", "1234567890"); r += expect_result_unmatch ("abc\\\"", ""); r += expect_result_unmatch ("", "abc\""); r += expect_result_unmatch ("\\\"", ""); r += expect_result_unmatch ("", "\""); r += expect_result_unmatch ("\\\"abc", ""); r += expect_result_unmatch ("", "\"abc"); r += expect_result_unmatch ("abc\\\\", ""); r += expect_result_unmatch ("", "abc\\"); r += expect_result_unmatch ("\\\\", ""); r += expect_result_unmatch ("", "\\"); r += expect_result_unmatch ("\\\\abc", ""); r += expect_result_unmatch ("", "\\abc"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123", ""); r += expect_result_unmatch ("", "\\\\\\\\123"); /* Various unmatched strings */ r += expect_result_unmatch ("a", "x"); r += expect_result_unmatch ("abc", "abcabc"); r += expect_result_unmatch ("abc", "abcabcabc"); r += expect_result_unmatch ("abc", "abcabcabcabc"); r += expect_result_unmatch ("ABCABC", "ABC"); r += expect_result_unmatch ("ABCABCABC", "ABC"); r += expect_result_unmatch ("ABCABCABCABC", "ABC"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\\\", "\\\\\\\\123"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\\"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_case_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* THe check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } return ret2; } #define expect_result_case_unmatch(q,u) \ expect_result_case_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch_case (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_case_unmatch ("a", "A"); r += expect_result_case_unmatch ("abC", "aBc"); r += expect_result_case_unmatch ("AbCdeF", "aBCdEF"); r += expect_result_case_unmatch ("a\0" "Bc", "a\0" "bC"); r += expect_result_case_unmatch ("Abc\\\"", "abC\""); r += expect_result_case_unmatch ("\\\"aBc", "\"abc"); r += expect_result_case_unmatch ("abc\\\\", "ABC\\"); r += expect_result_case_unmatch ("\\\\ABC", "\\abc"); r += expect_result_case_unmatch ("\\\\ZYX", "\\ZYx"); r += expect_result_case_unmatch ("abc", "ABC"); r += expect_result_case_unmatch ("ABCabc", "abcABC"); r += expect_result_case_unmatch ("abcXYZ", "ABCxyz"); r += expect_result_case_unmatch ("AbCdEfABCabc", "ABcdEFabcABC"); r += expect_result_case_unmatch ("a\\\\bc", "A\\BC"); r += expect_result_case_unmatch ("ABCa\\\\bc", "abcA\\BC"); r += expect_result_case_unmatch ("abcXYZ\\\\", "ABCxyz\\"); r += expect_result_case_unmatch ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_caseless_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* The check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* The check: MHD_str_equal_quoted_bin_n () */ ret3 = 0; if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret2 + ret3; } #define expect_result_caseless_unmatch(q,u) \ expect_result_caseless_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch_caseless (void) { unsigned int r = 0; /**< The number of errors */ /* Matched sequence except invalid backslash at the end */ r += expect_result_caseless_unmatch ("a\\", "A"); r += expect_result_caseless_unmatch ("abC\\", "abc"); r += expect_result_caseless_unmatch ("a\0" "Bc\\", "a\0" "bc"); r += expect_result_caseless_unmatch ("abc\\\"\\", "ABC\""); r += expect_result_caseless_unmatch ("\\\"\\", "\""); r += expect_result_caseless_unmatch ("\\\"ABC\\", "\"abc"); r += expect_result_caseless_unmatch ("Abc\\\\\\", "abC\\"); r += expect_result_caseless_unmatch ("\\\\\\", "\\"); r += expect_result_caseless_unmatch ("\\\\aBc\\", "\\abC"); /* Difference at binary zero */ r += expect_result_caseless_unmatch ("a\0", "A"); r += expect_result_caseless_unmatch ("A", "a\0"); r += expect_result_caseless_unmatch ("abC\0", "abc"); r += expect_result_caseless_unmatch ("abc", "ABc\0"); r += expect_result_caseless_unmatch ("a\0" "bC\0", "a\0" "bc"); r += expect_result_caseless_unmatch ("a\0" "bc", "A\0" "bc\0"); r += expect_result_caseless_unmatch ("ABC\\\"\0", "abc\""); r += expect_result_caseless_unmatch ("abc\\\"", "ABC\"\0"); r += expect_result_caseless_unmatch ("\\\"aBc\0", "\"abc"); r += expect_result_caseless_unmatch ("\\\"Abc", "\"abc\0"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\"); r += expect_result_caseless_unmatch ("\0" "aBc", "abc"); r += expect_result_caseless_unmatch ("abc", "\0" "abC"); r += expect_result_caseless_unmatch ("\0" "abc", "0abc"); r += expect_result_caseless_unmatch ("0abc", "\0" "aBc"); r += expect_result_caseless_unmatch ("xyZ", "xy" "\0" "z"); r += expect_result_caseless_unmatch ("Xy" "\0" "z", "xyz"); /* Difference after binary zero */ r += expect_result_caseless_unmatch ("abc\0" "1", "aBC\0" "2"); r += expect_result_caseless_unmatch ("a\0" "bcX", "a\0" "bcy"); r += expect_result_caseless_unmatch ("\0" "abc\\\"2", "\0" "Abc\"1"); r += expect_result_caseless_unmatch ("\0" "Abc1\\\"", "\0" "abc2\""); r += expect_result_caseless_unmatch ("\0" "\\\"c", "\0" "\"d"); r += expect_result_caseless_unmatch ("\\\"ab" "\0" "1C", "\"ab" "\0" "2C"); r += expect_result_caseless_unmatch ("a\0" "BCDef2", "a\0" "bcdef1"); r += expect_result_caseless_unmatch ("a\0" "bc2def", "a\0" "BC1def"); r += expect_result_caseless_unmatch ("a\0" "1bcdeF", "a\0" "2bcdef"); r += expect_result_caseless_unmatch ("abcde\0" "f2", "ABCDE\0" "f1"); r += expect_result_caseless_unmatch ("\\\"ab" "\0" "XC", "\"ab" "\0" "yC"); r += expect_result_caseless_unmatch ("a\0" "BCDefY", "a\0" "bcdefx"); r += expect_result_caseless_unmatch ("a\0" "bczdef", "a\0" "BCXdef"); r += expect_result_caseless_unmatch ("a\0" "YbcdeF", "a\0" "zbcdef"); r += expect_result_caseless_unmatch ("abcde\0" "fy", "ABCDE\0" "fX"); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_match (); errcount += check_quote_failed (); errcount += check_match_caseless (); errcount += check_invalid (); errcount += check_unmatch (); errcount += check_unmatch_case (); errcount += check_unmatch_caseless (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/sha256_ext.c0000644000175000017500000000551115035214301016273 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/sha256_ext.h * @brief Wrapper for SHA-256 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #include #include "sha256_ext.h" #include "mhd_assert.h" /** * Initialise structure for SHA-256 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx) { ctx->handle = NULL; ctx->ext_error = gnutls_hash_init (&ctx->handle, GNUTLS_DIG_SHA256); if ((0 != ctx->ext_error) && (NULL != ctx->handle)) { /* GnuTLS may return initialisation error and set the handle at the same time. Such handle cannot be used for calculations. Note: GnuTLS may also return an error and NOT set the handle. */ gnutls_free (ctx->handle); ctx->handle = NULL; } /* If handle is NULL, the error must be set */ mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error)); /* If error is set, the handle must be NULL */ mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle)); } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256CtxExt *ctx, const uint8_t *data, size_t length) { if (0 == ctx->ext_error) ctx->ext_error = gnutls_hash (ctx->handle, data, length); } /** * Finalise SHA-256 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx, uint8_t digest[SHA256_DIGEST_SIZE]) { if (0 == ctx->ext_error) gnutls_hash_output (ctx->handle, digest); } /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_SHA256_deinit (struct Sha256CtxExt *ctx) { if (NULL != ctx->handle) gnutls_hash_deinit (ctx->handle, NULL); } libmicrohttpd-1.0.2/src/microhttpd/test_str_bin_hex.c0000644000175000017500000003530414760713574017775 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_bin_hex.c * @brief Unit tests for hex strings <-> binary data processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str, size_t len) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); size_t r_pos = 0; size_t w_pos = 0; if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0]))) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (len > r_pos && w_pos + 1 < buf_size) { const unsigned char c = (unsigned char) str[r_pos]; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } r_pos++; } if (len != r_pos) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } #define TEST_BIN_MAX_SIZE (2 * 1024) /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_n (const char *const hex, const size_t hex_len, const uint8_t *const bin, const size_t bin_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != hex); mhd_assert (NULL != bin); mhd_assert (TEST_BIN_MAX_SIZE > bin_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1); mhd_assert (hex_len >= bin_size); mhd_assert (1 >= hex_len || hex_len > bin_size); ret = 0; /* check MHD_hex_to_bin() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_hex_to_bin (hex, hex_len, buf); if (res_size != bin_size) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong returned value:\n"); } else { if ((0 != bin_size) && (0 != memcmp (buf, bin, bin_size))) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong output data:\n"); } } if (((0 == res_size) && (fill_chr != buf[bin_size])) || ((0 != res_size) && (fill_chr != buf[res_size]))) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "A char written outside the buffer:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt ((const char *) bin, bin_size), (unsigned) bin_size); } } /* check MHD_bin_to_hex() */ if (0 == hex_len % 2) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_bin_to_hex_z (bin, bin_size, buf); if (res_size != hex_len) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "Wrong returned value:\n"); } else { if ((0 != hex_len) && (! MHD_str_equal_caseless_bin_n_ (buf, hex, hex_len))) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "Wrong output string:\n"); } } if (fill_chr != buf[res_size + 1]) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "A char written outside the buffer:\n"); } if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "The result is not zero-terminated:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_bin_to_hex (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt ((const char *) bin, bin_size), (unsigned) bin_size, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_bin_to_hex (\"%s\", %u, " "->(lower case)\"%s\") -> %u\n", n_prnt ((const char *) bin, bin_size), (unsigned) bin_size, n_prnt (hex, hex_len), (unsigned) bin_size); } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded_arr(h,a) \ expect_decoded_n(h,MHD_STATICSTR_LEN_(h),\ a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The lower case */ r += expect_decoded_arr ("000102030405060708090a0b0c0d0e" \ "0f101112131415161718191a1b1c1d" \ "1e1f202122232425262728292a2b2c" \ "2d2e2f303132333435363738393a3b" \ "3c3d3e3f404142434445464748494a" \ "4b4c4d4e4f50515253545556575859" \ "5a5b5c5d5e5f606162636465666768" \ "696a6b6c6d6e6f7071727374757677" \ "78797a7b7c7d7e7f80818283848586" \ "8788898a8b8c8d8e8f909192939495" \ "969798999a9b9c9d9e9fa0a1a2a3a4" \ "a5a6a7a8a9aaabacadaeafb0b1b2b3" \ "b4b5b6b7b8b9babbbcbdbebfc0c1c2" \ "c3c4c5c6c7c8c9cacbcccdcecfd0d1" \ "d2d3d4d5d6d7d8d9dadbdcdddedfe0" \ "e1e2e3e4e5e6e7e8e9eaebecedeeef" \ "f0f1f2f3f4f5f6f7f8f9fafbfcfdfe" \ "ff", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The upper case */ r += expect_decoded_arr ("000102030405060708090A0B0C0D0E" \ "0F101112131415161718191A1B1C1D" \ "1E1F202122232425262728292A2B2C" \ "2D2E2F303132333435363738393A3B" \ "3C3D3E3F404142434445464748494A" \ "4B4C4D4E4F50515253545556575859" \ "5A5B5C5D5E5F606162636465666768" \ "696A6B6C6D6E6F7071727374757677" \ "78797A7B7C7D7E7F80818283848586" \ "8788898A8B8C8D8E8F909192939495" \ "969798999A9B9C9D9E9FA0A1A2A3A4" \ "A5A6A7A8A9AAABACADAEAFB0B1B2B3" \ "B4B5B6B7B8B9BABBBCBDBEBFC0C1C2" \ "C3C4C5C6C7C8C9CACBCCCDCECFD0D1" \ "D2D3D4D5D6D7D8D9DADBDCDDDEDFE0" \ "E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" \ "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFE" \ "FF", bin); } if (1) { static const uint8_t bin[3] = {0x1, 0x2, 0x3}; r += expect_decoded_arr ("010203", bin); } if (1) { static const uint8_t bin[3] = {0x1, 0x2, 0x3}; r += expect_decoded_arr ("10203", bin); } if (1) { static const uint8_t bin[1] = {0x1}; r += expect_decoded_arr ("01", bin); } if (1) { static const uint8_t bin[1] = {0x1}; r += expect_decoded_arr ("1", bin); } return r; } /* return zero if succeed, number of failures otherwise */ static unsigned int expect_failed_n (const char *const hex, const size_t hex_len, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != hex); mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1); ret = 0; /* check MHD_hex_to_bin() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_hex_to_bin (hex, hex_len, buf); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, " "->(not defined)) -> 0\n", n_prnt (hex, hex_len), (unsigned) hex_len); } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_failed(h) \ expect_failed_n(h,MHD_STATICSTR_LEN_(h), \ __LINE__) static unsigned int check_broken_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_failed ("abcx"); r += expect_failed ("X"); r += expect_failed ("!"); r += expect_failed ("01z"); r += expect_failed ("0z"); r += expect_failed ("00z"); r += expect_failed ("000Y"); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_bin (); errcount += check_broken_str (); if (0 == errcount) printf ("All tests have been passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/test_upgrade.c0000644000175000017500000020624615035214301017101 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2020 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_upgrade.c * @brief Testcase for libmicrohttpd upgrading a connection * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include #include #include #ifndef WINDOWS #include #endif #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_sockets.h" #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #include "platform.h" #include "microhttpd.h" #include "test_helpers.h" #ifdef HTTPS_SUPPORT #include #include "../testcurl/https/tls_test_keys.h" #if defined(HAVE_FORK) && defined(HAVE_WAITPID) #include #include #endif /* HAVE_FORK && HAVE_WAITPID */ #endif /* HTTPS_SUPPORT */ #if defined(MHD_POSIX_SOCKETS) # ifdef MHD_WINSOCK_SOCKETS # error Both MHD_POSIX_SOCKETS and MHD_WINSOCK_SOCKETS are defined # endif /* MHD_WINSOCK_SOCKETS */ #elif ! defined(MHD_WINSOCK_SOCKETS) # error Neither MHD_POSIX_SOCKETS nor MHD_WINSOCK_SOCKETS are defined #endif /* MHD_WINSOCK_SOCKETS */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } static void _testErrorLog_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call resulted in error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); } #ifdef MHD_HAVE_MHD_FUNC_ #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, MHD_FUNC_, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, MHD_FUNC_, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, MHD_FUNC_, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, MHD_FUNC_, __LINE__) #define testErrorLog(ignore) \ _testErrorLog_func(NULL, MHD_FUNC_, __LINE__) #define testErrorLogDesc(errDesc) \ _testErrorLog_func(errDesc, MHD_FUNC_, __LINE__) #else /* ! MHD_HAVE_MHD_FUNC_ */ #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define testErrorLog(ignore) _testErrorLog_func(NULL, NULL, __LINE__) #define testErrorLogDesc(errDesc) _testErrorLog_func(errDesc, NULL, __LINE__) #endif /* ! MHD_HAVE_MHD_FUNC_ */ /* ** External parameters ** */ static bool use_large; static bool use_vlarge; static bool test_tls; static int verbose = 0; enum tls_tool { TLS_CLI_NO_TOOL = 0, TLS_CLI_GNUTLS, TLS_CLI_OPENSSL, TLS_LIB_GNUTLS }; static enum tls_tool use_tls_tool; /* ** Internal values ** */ /* Could be increased to facilitate debugging */ static int test_timeout = 5; static uint16_t global_port; static const void *rclient_msg; static size_t rclient_msg_size; static const void *app_msg; static size_t app_msg_size; static void *alloc_ptr[2] = {NULL, NULL}; static void fflush_allstd (void) { fflush (stderr); fflush (stdout); } #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) /** * Fork child that connects via GnuTLS-CLI to our @a port. Allows us to * talk to our port over a socket in @a sp without having to worry * about TLS. * * @param location where the socket is returned * @return -1 on error, otherwise PID of TLS child process */ static pid_t gnutlscli_connect (int *sock, uint16_t port) { pid_t chld; int sp[2]; char destination[30]; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sp)) { testErrorLogDesc ("socketpair() failed"); return (pid_t) -1; } chld = fork (); if (0 != chld) { *sock = sp[1]; MHD_socket_close_chk_ (sp[0]); return chld; } MHD_socket_close_chk_ (sp[1]); (void) close (0); (void) close (1); if (-1 == dup2 (sp[0], 0)) externalErrorExitDesc ("dup2() failed"); if (-1 == dup2 (sp[0], 1)) externalErrorExitDesc ("dup2() failed"); MHD_socket_close_chk_ (sp[0]); if (TLS_CLI_GNUTLS == use_tls_tool) { snprintf (destination, sizeof(destination), "%u", (unsigned int) port); execlp ("gnutls-cli", "gnutls-cli", "--insecure", "-p", destination, "127.0.0.1", (char *) NULL); } else if (TLS_CLI_OPENSSL == use_tls_tool) { snprintf (destination, sizeof(destination), "127.0.0.1:%u", (unsigned int) port); execlp ("openssl", "openssl", "s_client", "-connect", destination, "-verify", "1", (char *) NULL); } _exit (1); } #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ #if 0 /* Unused code */ /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("fcntl() failed"); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("fcntl() failed"); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("ioctlsocket() failed"); #endif /* MHD_WINSOCK_SOCKETS */ } #endif /* Unused code */ /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("fcntl() failed"); if (O_NONBLOCK != (flags & O_NONBLOCK)) if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("fcntl() failed"); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("ioctlsocket() failed"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Enable TCP_NODELAY on TCP/IP socket. * * @param fd the socket to manipulate */ static void make_nodelay (MHD_socket fd) { #ifdef TCP_NODELAY const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 == setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) return; /* Success exit point */ #ifndef MHD_WINSOCK_SOCKETS fprintf (stderr, "Failed to enable TCP_NODELAY on socket (ignored). " "errno: %d (%s)\n", (int) errno, strerror (errno)); #else /* MHD_WINSOCK_SOCKETS */ fprintf (stderr, "Failed to enable TCP_NODELAY on socket (ignored). " "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); #endif /* TCP_NODELAY */ } /** * Wrapper structure for plain&TLS sockets */ struct wr_socket { /** * Real network socket */ MHD_socket fd; /** * Type of this socket */ enum wr_type { wr_invalid = 0, wr_plain = 1, wr_tls = 2 } t; bool is_nonblocking; bool eof_recieved; #ifdef HTTPS_SUPPORT /** * TLS credentials */ gnutls_certificate_credentials_t tls_crd; /** * TLS session. */ gnutls_session_t tls_s; /** * TLS handshake already succeed? */ bool tls_connected; #endif }; /** * Get underlying real socket. * @return FD of real socket */ #define wr_fd(s) ((s)->fd) #if 0 /* Unused code */ static void wr_make_blocking (struct wr_socket *s) { if (s->is_nonblocking) make_blocking (s->fd); s->is_nonblocking = false; } #endif /* Unused code */ static void wr_make_nonblocking (struct wr_socket *s) { if (! s->is_nonblocking) make_nonblocking (s->fd); s->is_nonblocking = true; } /** * Create wr_socket with plain TCP underlying socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_plain_sckt (void) { struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_plain; s->eof_recieved = false; s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); s->is_nonblocking = false; if (MHD_INVALID_SOCKET != s->fd) { make_nodelay (s->fd); return s; /* Success */ } testErrorLogDesc ("socket() failed"); free (s); return NULL; } /** * Create wr_socket with TLS TCP underlying socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_tls_sckt (void) { #ifdef HTTPS_SUPPORT struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_tls; s->eof_recieved = false; s->tls_connected = 0; s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); s->is_nonblocking = false; if (MHD_INVALID_SOCKET != s->fd) { make_nodelay (s->fd); if (GNUTLS_E_SUCCESS == gnutls_init (&(s->tls_s), GNUTLS_CLIENT)) { if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (s->tls_s)) { if (GNUTLS_E_SUCCESS == gnutls_certificate_allocate_credentials (&(s->tls_crd))) { if (GNUTLS_E_SUCCESS == gnutls_credentials_set (s->tls_s, GNUTLS_CRD_CERTIFICATE, s->tls_crd)) { #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (s->tls_s, (int) (s->fd)); #else /* GnuTLS before 3.1.9 or Win x64 */ gnutls_transport_set_ptr (s->tls_s, (gnutls_transport_ptr_t) \ (intptr_t) (s->fd)); #endif /* GnuTLS before 3.1.9 or Win x64 */ return s; } else testErrorLogDesc ("gnutls_credentials_set() failed"); gnutls_certificate_free_credentials (s->tls_crd); } else testErrorLogDesc ("gnutls_certificate_allocate_credentials() failed"); } else testErrorLogDesc ("gnutls_set_default_priority() failed"); gnutls_deinit (s->tls_s); } else testErrorLogDesc ("gnutls_init() failed"); (void) MHD_socket_close_ (s->fd); } else testErrorLogDesc ("socket() failed"); free (s); #endif /* HTTPS_SUPPORT */ return NULL; } /** * Create wr_socket with plain TCP underlying socket * from already created TCP socket. * @param plain_sk real TCP socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_from_plain_sckt (MHD_socket plain_sk) { struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_plain; s->eof_recieved = false; s->fd = plain_sk; s->is_nonblocking = false; /* The actual mode is unknown */ wr_make_nonblocking (s); /* Force set mode to have correct status */ make_nodelay (s->fd); return s; } #if 0 /* Disabled code */ /** * Check whether shutdown of connection was received from remote * @param s socket to check * @return zero if shutdown signal has not been received, * 1 if shutdown signal was already received */ static int wr_is_eof_received (struct wr_socket *s) { return s->eof_recieved ? 1 : 0; } #endif /* Disabled code */ enum wr_wait_for_type { WR_WAIT_FOR_RECV = 0, WR_WAIT_FOR_SEND = 1 }; static bool wr_wait_socket_ready_noabort_ (struct wr_socket *s, int timeout_ms, enum wr_wait_for_type wait_for) { fd_set fds; int sel_res; struct timeval tmo; struct timeval *tmo_ptr; #ifndef MHD_WINSOCK_SOCKETS if (FD_SETSIZE <= s->fd) externalErrorExitDesc ("Too large FD value"); #endif /* ! MHD_WINSOCK_SOCKETS */ FD_ZERO (&fds); FD_SET (s->fd, &fds); if (0 <= timeout_ms) { #if ! defined(_WIN32) || defined(__CYGWIN__) tmo.tv_sec = (time_t) (timeout_ms / 1000); #else /* Native W32 */ tmo.tv_sec = (long) (timeout_ms / 1000); #endif /* Native W32 */ tmo.tv_usec = ((long) (timeout_ms % 1000)) * 1000; tmo_ptr = &tmo; } else tmo_ptr = NULL; /* No timeout */ do { if (WR_WAIT_FOR_RECV == wait_for) sel_res = select (1 + (int) s->fd, &fds, NULL, NULL, tmo_ptr); else sel_res = select (1 + (int) s->fd, NULL, &fds, NULL, tmo_ptr); } while (0 > sel_res && MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())); if (1 == sel_res) return true; if (0 == sel_res) fprintf (stderr, "Timeout"); else { #ifndef MHD_WINSOCK_SOCKETS fprintf (stderr, "Error %d (%s)", (int) errno, strerror (errno)); #else /* MHD_WINSOCK_SOCKETS */ fprintf (stderr, "Error (WSAGetLastError code: %d)", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ } fprintf (stderr, " waiting for socket to be available for %s.\n", (WR_WAIT_FOR_RECV == wait_for) ? "receiving" : "sending"); return false; } static void wr_wait_socket_ready_ (struct wr_socket *s, int timeout_ms, enum wr_wait_for_type wait_for) { if (wr_wait_socket_ready_noabort_ (s, timeout_ms, wait_for)) return; if (WR_WAIT_FOR_RECV == wait_for) mhdErrorExitDesc ("Client or application failed to receive the data"); else mhdErrorExitDesc ("Client or application failed to send the data"); } /** * Connect socket to specified address. * @param s socket to use * @param addr address to connect * @param length of structure pointed by @a addr * @param timeout_ms the maximum wait time in milliseconds to send the data, * no limit if negative value is used * @return zero on success, -1 otherwise. */ static int wr_connect_tmo (struct wr_socket *s, const struct sockaddr *addr, unsigned int length, int timeout_ms) { if (0 != connect (s->fd, addr, (socklen_t) length)) { int err; bool connect_completed = false; err = MHD_socket_get_error_ (); #if defined(MHD_POSIX_SOCKETS) while (! connect_completed && (EINTR == err)) { connect_completed = (0 == connect (s->fd, addr, (socklen_t) length)); if (! connect_completed) { err = errno; if (EALREADY == err) err = EINPROGRESS; else if (EISCONN == err) connect_completed = true; } } #endif /* MHD_POSIX_SOCKETS */ if (! connect_completed && (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_) || MHD_SCKT_ERR_IS_EAGAIN_ (err))) /* No modern system uses EAGAIN, except W32 */ connect_completed = wr_wait_socket_ready_noabort_ (s, timeout_ms, WR_WAIT_FOR_SEND); if (! connect_completed) { testErrorLogDesc ("connect() failed"); return -1; } } if (wr_plain == s->t) return 0; #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { /* Do not try handshake here as * it requires processing on MHD side and * when testing with "external" polling, * test will call MHD processing only * after return from wr_connect(). */ s->tls_connected = 0; return 0; } #endif /* HTTPS_SUPPORT */ testErrorLogDesc ("HTTPS socket connect called, but code does not support" \ " HTTPS sockets"); return -1; } /** * Connect socket to specified address. * @param s socket to use * @param addr address to connect * @param length of structure pointed by @a addr * @return zero on success, -1 otherwise. */ static int wr_connect (struct wr_socket *s, const struct sockaddr *addr, unsigned int length) { return wr_connect_tmo (s, addr, length, test_timeout * 1000); } #ifdef HTTPS_SUPPORT /* Only to be called from wr_send() and wr_recv() ! */ static bool wr_handshake_tmo_ (struct wr_socket *s, int timeout_ms) { int res = gnutls_handshake (s->tls_s); while ((GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res)) { wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); res = gnutls_handshake (s->tls_s); } if (GNUTLS_E_SUCCESS == res) s->tls_connected = true; else { fprintf (stderr, "The error returned by gnutls_handshake() is " "'%s' ", gnutls_strerror ((int) res)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) res)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) res); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_handshake() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ } return s->tls_connected; } #if 0 /* Unused function */ /* Only to be called from wr_send() and wr_recv() ! */ static bool wr_handshake_ (struct wr_socket *s) { return wr_handshake_tmo_ (s, test_timeout * 1000); } #endif /* Unused function */ #endif /* HTTPS_SUPPORT */ /** * Send data to remote by socket. * @param s the socket to use * @param buf the buffer with data to send * @param len the length of data in @a buf * @param timeout_ms the maximum wait time in milliseconds to send the data, * no limit if negative value is used * @return number of bytes were sent if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_send_tmo (struct wr_socket *s, const void *buf, size_t len, int timeout_ms) { if (wr_plain == s->t) { ssize_t res; while (! 0) { int err; res = MHD_send_ (s->fd, buf, len); if (0 <= res) break; /* Success */ err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) && ! MHD_SCKT_ERR_IS_EINTR_ (err)) break; /* Failure */ wr_wait_socket_ready_ (s, timeout_ms, WR_WAIT_FOR_SEND); } return res; } #ifdef HTTPS_SUPPORT else if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_record_send (s->tls_s, buf, len); if (ret >= 0) return ret; if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_record_send() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_record_send() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ testErrorLogDesc ("HTTPS socket send called, but code does not support" \ " HTTPS sockets"); return -1; } /** * Send data to remote by socket. * @param s the socket to use * @param buf the buffer with data to send * @param len the length of data in @a buf * @return number of bytes were sent if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_send (struct wr_socket *s, const void *buf, size_t len) { return wr_send_tmo (s, buf, len, test_timeout * 1000); } /** * Receive data from remote by socket. * @param s the socket to use * @param buf the buffer to store received data * @param len the length of @a buf * @param timeout_ms the maximum wait time in milliseconds to receive the data, * no limit if negative value is used * @return number of bytes were received if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_recv_tmo (struct wr_socket *s, void *buf, size_t len, int timeout_ms) { if (wr_plain == s->t) { ssize_t res; while (! 0) { int err; res = MHD_recv_ (s->fd, buf, len); if (0 == res) s->eof_recieved = true; if (0 <= res) break; /* Success */ err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) && ! MHD_SCKT_ERR_IS_EINTR_ (err)) break; /* Failure */ wr_wait_socket_ready_ (s, timeout_ms, WR_WAIT_FOR_RECV); } return res; } #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_record_recv (s->tls_s, buf, len); if (0 == ret) s->eof_recieved = true; if (ret >= 0) return ret; if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_record_recv() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_record_recv() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ return -1; } /** * Receive data from remote by socket. * @param s the socket to use * @param buf the buffer to store received data * @param len the length of @a buf * @return number of bytes were received if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_recv (struct wr_socket *s, void *buf, size_t len) { return wr_recv_tmo (s, buf, len, test_timeout * 1000); } /** * Shutdown send/write on the socket. * @param s the socket to shutdown * @param how the type of shutdown: SHUT_WR or SHUT_RDWR * @param timeout_ms the maximum wait time in milliseconds to receive the data, * no limit if negative value is used * @return zero on succeed, -1 otherwise */ static int wr_shutdown_tmo (struct wr_socket *s, int how, int timeout_ms) { switch (how) { case SHUT_WR: /* Valid value */ break; case SHUT_RDWR: /* Valid value */ break; case SHUT_RD: externalErrorExitDesc ("Unsupported 'how' value"); break; default: externalErrorExitDesc ("Invalid 'how' value"); break; } if (wr_plain == s->t) { (void) timeout_ms; /* Unused parameter for plain sockets */ return shutdown (s->fd, how); } #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_bye (s->tls_s, (SHUT_WR == how) ? GNUTLS_SHUT_WR : GNUTLS_SHUT_RDWR); if (GNUTLS_E_SUCCESS == ret) { #if 0 /* Disabled to test pure behaviour */ if (SHUT_RDWR == how) (void) shutdown (s->fd, how); /* Also shutdown the underlying transport layer */ #endif return 0; } if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_bye() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_bye() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ return -1; } /** * Shutdown the socket. * @param s the socket to shutdown * @return zero on succeed, -1 otherwise */ static int wr_shutdown (struct wr_socket *s, int how) { return wr_shutdown_tmo (s, how, test_timeout * 1000); } /** * Close socket and release allocated resourced * @param s the socket to close * @return zero on succeed, -1 otherwise */ static int wr_close (struct wr_socket *s) { int ret = (MHD_socket_close_ (s->fd)) ? 0 : -1; #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { gnutls_deinit (s->tls_s); gnutls_certificate_free_credentials (s->tls_crd); } #endif /* HTTPS_SUPPORT */ free (s); return ret; } /** * Thread we use to run the interaction with the upgraded socket. */ static pthread_t pt; /** * Will be set to the upgraded socket. */ static struct wr_socket *volatile usock; /** * Thread we use to run the interaction with the upgraded socket. */ static pthread_t pt_client; /** * Flag set to true once the client is finished. */ static volatile bool client_done; /** * Flag set to true once the app is finished. */ static volatile bool app_done; static const char * term_reason_str (enum MHD_RequestTerminationCode term_code) { switch ((int) term_code) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: return "COMPLETED_OK"; case MHD_REQUEST_TERMINATED_WITH_ERROR: return "TERMINATED_WITH_ERROR"; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: return "TIMEOUT_REACHED"; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: return "DAEMON_SHUTDOWN"; case MHD_REQUEST_TERMINATED_READ_ERROR: return "READ_ERROR"; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: return "CLIENT_ABORT"; case -1: return "(not called)"; default: return "(unknown code)"; } return "(problem)"; /* unreachable */ } /** * Callback used by MHD to notify the application about completed * requests. Frees memory. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the #MHD_AccessHandlerCallback * @param toe reason for request termination */ static void notify_completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { (void) cls; (void) connection; /* Unused. Silent compiler warning. */ if (verbose) printf ("notify_completed_cb() has been called with '%s' code.\n", term_reason_str (toe)); if ( (toe != MHD_REQUEST_TERMINATED_COMPLETED_OK) && (toe != MHD_REQUEST_TERMINATED_CLIENT_ABORT) && (toe != MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN) ) mhdErrorExitDesc ("notify_completed_cb() called with wrong code"); if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' parameter is NULL"); if (NULL == *req_cls) mhdErrorExitDesc ("'*req_cls' pointer is NULL"); if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ())) mhdErrorExitDesc ("notify_completed_cb() is called in wrong thread"); free (*req_cls); *req_cls = NULL; } /** * Logging callback. * * @param cls logging closure (NULL) * @param uri access URI * @param connection connection handle * @return #TEST_PTR */ static void * log_cb (void *cls, const char *uri, struct MHD_Connection *connection) { pthread_t *ppth; (void) cls; (void) connection; /* Unused. Silent compiler warning. */ if (NULL == uri) mhdErrorExitDesc ("The 'uri' parameter is NULL"); if (0 != strcmp (uri, "/")) { fprintf (stderr, "Wrong 'uri' value: '%s'. ", uri); mhdErrorExit (); } ppth = malloc (sizeof (pthread_t)); if (NULL == ppth) externalErrorExitDesc ("malloc() failed"); *ppth = pthread_self (); return (void *) ppth; } /** * Function to check that MHD properly notifies about starting * and stopping. * * @param cls client-defined closure * @param connection connection handle * @param socket_context socket-specific pointer where the * client can associate some state specific * to the TCP connection; note that this is * different from the "req_cls" which is per * HTTP request. The client can initialize * during #MHD_CONNECTION_NOTIFY_STARTED and * cleanup during #MHD_CONNECTION_NOTIFY_CLOSED * and access in the meantime using * #MHD_CONNECTION_INFO_SOCKET_CONTEXT. * @param toe reason for connection notification * @see #MHD_OPTION_NOTIFY_CONNECTION * @ingroup request */ static void notify_connection_cb (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe) { static int started = MHD_NO; (void) cls; (void) connection; /* Unused. Silent compiler warning. */ switch (toe) { case MHD_CONNECTION_NOTIFY_STARTED: if (MHD_NO != started) mhdErrorExitDesc ("The connection has been already started"); started = MHD_YES; *socket_context = &started; break; case MHD_CONNECTION_NOTIFY_CLOSED: if (MHD_YES != started) mhdErrorExitDesc ("The connection has not been started before"); if (&started != *socket_context) mhdErrorExitDesc ("Wrong '*socket_context' value"); *socket_context = NULL; started = MHD_NO; break; } } static void send_all (struct wr_socket *sock, const void *data, size_t data_size) { ssize_t ret; size_t sent; const uint8_t *const buf = (const uint8_t *) data; wr_make_nonblocking (sock); for (sent = 0; sent < data_size; sent += (size_t) ret) { ret = wr_send (sock, buf + sent, data_size - sent); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("send() failed"); } } } #define send_all_stext(sk,st) send_all(sk,st,MHD_STATICSTR_LEN_(st)) /** * Read character-by-character until we * get 'CRLNCRLN'. */ static void recv_hdr (struct wr_socket *sock) { unsigned int i; char next; char c; ssize_t ret; wr_make_nonblocking (sock); next = '\r'; i = 0; while (i < 4) { ret = wr_recv (sock, &c, 1); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ())) continue; if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; externalErrorExitDesc ("recv() failed"); } if (0 == ret) mhdErrorExitDesc ("The server unexpectedly closed connection"); if (c == next) { i++; if (next == '\r') next = '\n'; else next = '\r'; continue; } if (c == '\r') { i = 1; next = '\n'; continue; } i = 0; next = '\r'; } } static void recv_all (struct wr_socket *sock, const void *data, size_t data_size) { uint8_t *buf; ssize_t ret; size_t rcvd; buf = (uint8_t *) malloc (data_size); if (NULL == buf) externalErrorExitDesc ("malloc() failed"); wr_make_nonblocking (sock); for (rcvd = 0; rcvd < data_size; rcvd += (size_t) ret) { ret = wr_recv (sock, buf + rcvd, data_size - rcvd); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("recv() failed"); } else if (0 == ret) { fprintf (stderr, "Partial only received text. Expected: '%.*s' " "(length: %ud). Got: '%.*s' (length: %ud). ", (int) data_size, (const char *) data, (unsigned int) data_size, (int) rcvd, (const char *) buf, (unsigned int) rcvd); mhdErrorExitDesc ("The server unexpectedly closed connection"); } if ((data_size - rcvd) < (size_t) ret) externalErrorExitDesc ("recv() returned excessive amount of data"); if (0 != memcmp (data, buf, rcvd + (size_t) ret)) { fprintf (stderr, "Wrong received text. Expected: '%.*s'. " "Got: '%.*s'. ", (int) (rcvd + (size_t) ret), (const char *) data, (int) (rcvd + (size_t) ret), (const char *) buf); mhdErrorExit (); } } if (0 != memcmp (data, buf, data_size)) { fprintf (stderr, "Wrong received text. Expected: '%.*s'. " "Got: '%.*s'. ", (int) data_size, (const char *) data, (int) data_size, (const char *) buf); mhdErrorExit (); } free (buf); } #define recv_all_stext(sk,st) recv_all(sk,st,MHD_STATICSTR_LEN_(st)) /** * Shutdown write of the connection to signal end of transmission * for the remote side * @param sock the socket to shutdown */ static void send_eof (struct wr_socket *sock) { if (0 != wr_shutdown (sock, /* ** On Darwin local shutdown of RD cause error ** if remote side shut down WR before. wr_is_eof_received (sock) ? SHUT_RDWR : */ SHUT_WR)) externalErrorExitDesc ("Failed to shutdown connection"); } /** * Receive end of the transmission indication from the remote side * @param sock the socket to use */ static void receive_eof (struct wr_socket *sock) { uint8_t buf[127]; ssize_t ret; size_t rcvd; bool got_eof = false; wr_make_nonblocking (sock); for (rcvd = 0; rcvd < sizeof(buf); rcvd += (size_t) ret) { ret = wr_recv (sock, buf + rcvd, sizeof(buf) - rcvd); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("recv() failed"); } else if (0 == ret) { got_eof = true; break; } } if (got_eof && (0 == rcvd)) return; /* Success */ if (0 != rcvd) { if (sizeof(buf) == rcvd) { fprintf (stderr, "Received at least %lu extra bytes while " "end-of-file is expected.\n", (unsigned long) sizeof(buf)); mhdErrorExit (); } fprintf (stderr, "Received at %lu extra bytes and then %s" "end-of-file marker.\n", (unsigned long) rcvd, got_eof ? "" : "NO "); mhdErrorExit (); } if (! got_eof) mhdErrorExitDesc ("Failed to receive end-of-file marker."); } /** * Main function for the thread that runs the interaction with * the upgraded socket. * * @param cls the handle for the upgrade */ static void * run_usock (void *cls) { struct MHD_UpgradeResponseHandle *urh = cls; recv_all (usock, rclient_msg, rclient_msg_size); send_all (usock, app_msg, app_msg_size); recv_all_stext (usock, "Finished"); if (! test_tls) { receive_eof (usock); send_eof (usock); } MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); free (usock); usock = NULL; app_done = true; return NULL; } /** * Main function for the thread that runs the client-side of the * interaction with the upgraded socket. * * @param cls the client socket */ static void * run_usock_client (void *cls) { struct wr_socket *sock = cls; send_all_stext (sock, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\n\r\n"); recv_hdr (sock); send_all (sock, rclient_msg, rclient_msg_size); recv_all (sock, app_msg, app_msg_size); send_all_stext (sock, "Finished"); if (! test_tls) { send_eof (sock); receive_eof (sock); } wr_close (sock); client_done = true; return NULL; } /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ static void upgrade_cb (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { (void) cls; (void) connection; (void) req_cls; (void) extra_in; /* Unused. Silent compiler warning. */ usock = wr_create_from_plain_sckt (sock); wr_make_nonblocking (usock); if (0 != extra_in_size) mhdErrorExitDesc ("'extra_in_size' is not zero"); if (0 != pthread_create (&pt, NULL, &run_usock, urh)) externalErrorExitDesc ("pthread_create() failed"); } /** * A client has requested the given url using the given method * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc). The callback * must call MHD callbacks to provide content to give back to the * client and return an HTTP status code (i.e. #MHD_HTTP_OK, * #MHD_HTTP_NOT_FOUND, etc.). * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param url the requested url * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @param version the HTTP version string (i.e. * #MHD_HTTP_VERSION_1_1) * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of #MHD_get_connection_values; very large POST * data *will* be made available incrementally in * @a upload_data) * @param upload_data_size set initially to the size of the * @a upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global #MHD_RequestCompletedCallback (which * can be set with the #MHD_OPTION_NOTIFY_COMPLETED). * Initially, `*req_cls` will be NULL. * @return #MHD_YES if the connection was handled successfully, * #MHD_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result ahc_upgrade (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *resp; (void) cls; (void) url; (void) method; /* Unused. Silent compiler warning. */ (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' is NULL"); if (NULL == *req_cls) mhdErrorExitDesc ("'*req_cls' value is NULL"); if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ())) mhdErrorExitDesc ("ahc_upgrade() is called in wrong thread"); resp = MHD_create_response_for_upgrade (&upgrade_cb, NULL); if (NULL == resp) mhdErrorExitDesc ("MHD_create_response_for_upgrade() failed"); if (MHD_YES != MHD_add_response_header (resp, MHD_HTTP_HEADER_UPGRADE, "Hello World Protocol")) mhdErrorExitDesc ("MHD_add_response_header() failed"); if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, resp)) mhdErrorExitDesc ("MHD_queue_response() failed"); MHD_destroy_response (resp); return MHD_YES; } /** * Run the MHD external event loop using select or epoll. * * select/epoll modes are used automatically based on daemon's flags. * * @param daemon daemon to run it for */ static void run_mhd_select_loop (struct MHD_Daemon *daemon) { const time_t start_time = time (NULL); const union MHD_DaemonInfo *pdinfo; bool connection_was_accepted; bool connection_has_finished; #ifdef EPOLL_SUPPORT bool use_epoll = false; int ep = -1; pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_FLAGS); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); else use_epoll = (0 != (pdinfo->flags & MHD_USE_EPOLL)); if (use_epoll) { pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_EPOLL_FD); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); ep = pdinfo->listen_fd; if (0 > ep) mhdErrorExitDesc ("Invalid epoll FD value"); } #endif /* EPOLL_SUPPORT */ connection_was_accepted = false; connection_has_finished = false; while (1) { fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd; struct timeval tv; uint64_t to64; bool has_mhd_timeout; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max_fd = MHD_INVALID_SOCKET; if (time (NULL) - start_time > ((time_t) test_timeout)) mhdErrorExitDesc ("Test timeout"); pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); if (0 != pdinfo->num_connections) connection_was_accepted = true; else { if (connection_was_accepted) connection_has_finished = true; } if (connection_has_finished) return; if (MHD_YES != MHD_get_fdset (daemon, &rs, &ws, &es, &max_fd)) mhdErrorExitDesc ("MHD_get_fdset() failed"); #ifdef EPOLL_SUPPORT if (use_epoll) { if (ep != max_fd) mhdErrorExitDesc ("Wrong 'max_fd' value"); if (! FD_ISSET (ep, &rs)) mhdErrorExitDesc ("Epoll FD is NOT set in read fd_set"); } #endif /* EPOLL_SUPPORT */ has_mhd_timeout = (MHD_NO != MHD_get_timeout64 (daemon, &to64)); if (has_mhd_timeout) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (to64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (to64 / 1000); #endif /* Native W32 */ tv.tv_usec = (long) (1000 * (to64 % 1000)); } else { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) test_timeout; #else /* Native W32 */ tv.tv_sec = (long) test_timeout; #endif /* Native W32 */ tv.tv_usec = 0; } #ifdef MHD_WINSOCK_SOCKETS if ((0 == rs.fd_count) && (0 == ws.fd_count) && (0 != es.fd_count)) Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); else /* Combined with the next 'if' */ #endif if (1) { int sel_res; sel_res = MHD_SYS_select_ (max_fd + 1, &rs, &ws, &es, &tv); if (0 == sel_res) { if (! has_mhd_timeout) mhdErrorExitDesc ("Timeout waiting for data on sockets"); } else if (0 > sel_res) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) #endif /* MHD_POSIX_SOCKETS */ mhdErrorExitDesc ("Unexpected select() error"); } } MHD_run_from_select (daemon, &rs, &ws, &es); } } #ifdef HAVE_POLL /** * Run the MHD external event loop using select. * * @param daemon daemon to run it for */ _MHD_NORETURN static void run_mhd_poll_loop (struct MHD_Daemon *daemon) { (void) daemon; /* Unused. Silent compiler warning. */ externalErrorExitDesc ("Not implementable with MHD API"); } #endif /* HAVE_POLL */ /** * Run the MHD external event loop using select. * * @param daemon daemon to run it for */ static void run_mhd_loop (struct MHD_Daemon *daemon, unsigned int flags) { if (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL))) run_mhd_select_loop (daemon); #ifdef HAVE_POLL else if (0 != (flags & MHD_USE_POLL)) run_mhd_poll_loop (daemon); #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT else if (0 != (flags & MHD_USE_EPOLL)) run_mhd_select_loop (daemon); #endif else externalErrorExitDesc ("Wrong 'flags' value"); } /** * Test upgrading a connection. * * @param flags which event loop style should be tested * @param pool size of the thread pool, 0 to disable */ static unsigned int test_upgrade (unsigned int flags, unsigned int pool) { struct MHD_Daemon *d = NULL; struct wr_socket *sock; struct sockaddr_in sa; enum MHD_FLAG used_flags; const union MHD_DaemonInfo *dinfo; #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) pid_t pid = -1; #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ size_t mem_limit; /* Handle memory limits. Actually makes sense only for TLS */ if (use_vlarge) mem_limit = 64U * 1024U; /* Half of the buffer should be large enough to take more than max TLS packet */ else if (use_large) mem_limit = 4U * 1024; /* Make sure that several iteration required to deliver a single message */ else mem_limit = 0; /* Use default value */ client_done = false; app_done = false; if (! test_tls) d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE | MHD_USE_ITC, global_port, NULL, NULL, &ahc_upgrade, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, ¬ify_completed_cb, NULL, MHD_OPTION_NOTIFY_CONNECTION, ¬ify_connection_cb, NULL, MHD_OPTION_THREAD_POOL_SIZE, pool, MHD_OPTION_CONNECTION_TIMEOUT, test_timeout, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_END); #ifdef HTTPS_SUPPORT else d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE | MHD_USE_TLS | MHD_USE_ITC, global_port, NULL, NULL, &ahc_upgrade, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, ¬ify_completed_cb, NULL, MHD_OPTION_NOTIFY_CONNECTION, ¬ify_connection_cb, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_THREAD_POOL_SIZE, pool, MHD_OPTION_CONNECTION_TIMEOUT, test_timeout, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_END); #endif /* HTTPS_SUPPORT */ if (NULL == d) mhdErrorExitDesc ("MHD_start_daemon() failed"); dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); used_flags = dinfo->flags; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); global_port = dinfo->port; /* Re-use the same port for the next checks */ if (! test_tls || (TLS_LIB_GNUTLS == use_tls_tool)) { sock = test_tls ? wr_create_tls_sckt () : wr_create_plain_sckt (); if (NULL == sock) externalErrorExitDesc ("Create socket failed"); wr_make_nonblocking (sock); sa.sin_family = AF_INET; sa.sin_port = htons (dinfo->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != wr_connect (sock, (struct sockaddr *) &sa, sizeof (sa))) externalErrorExitDesc ("Connect socket failed"); } else { #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) MHD_socket tls_fork_sock; uint16_t port; port = dinfo->port; if (-1 == (pid = gnutlscli_connect (&tls_fork_sock, port))) externalErrorExitDesc ("gnutlscli_connect() failed"); sock = wr_create_from_plain_sckt (tls_fork_sock); if (NULL == sock) externalErrorExitDesc ("wr_create_from_plain_sckt() failed"); wr_make_nonblocking (sock); #else /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */ externalErrorExitDesc ("Unsupported 'use_tls_tool' value"); #endif /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */ } if (0 != pthread_create (&pt_client, NULL, &run_usock_client, sock)) externalErrorExitDesc ("pthread_create() failed"); if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) ) run_mhd_loop (d, used_flags); if (0 != pthread_join (pt_client, NULL)) externalErrorExitDesc ("pthread_join() failed"); if (0 != pthread_join (pt, NULL)) externalErrorExitDesc ("pthread_join() failed"); #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) if (test_tls && (TLS_LIB_GNUTLS != use_tls_tool)) { if ((pid_t) -1 == waitpid (pid, NULL, 0)) externalErrorExitDesc ("waitpid() failed"); } #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ if (! client_done) externalErrorExitDesc ("The client thread has not signalled " \ "successful finish"); if (! app_done) externalErrorExitDesc ("The application thread has not signalled " \ "successful finish"); MHD_stop_daemon (d); return 0; } enum test_msg_type { test_msg_large_app_data, test_msg_large_rclient_data, test_msg_vlarge_app_data, test_msg_vlarge_rclient_data }; /** * Initialise test message data * @param buf the pointer to the buffer to fill with the test data * @param buf_size the size of the @a buf * @param msg_type the type of the data to fill the @a buf * @return the @a buf pointer */ static void * init_test_msg (void *buf, size_t buf_size, enum test_msg_type msg_type) { size_t i; char *const text_buf = (char *) buf; uint8_t *const bin_buf = (uint8_t *) buf; if (0 == buf_size) return buf; switch (msg_type) { case test_msg_large_app_data: case test_msg_large_rclient_data: /* Simulate text data */ for (i = 0; i < buf_size; ++i) { size_t pos; if (test_msg_large_app_data == msg_type) pos = i + 43; else pos = i + 26; if ((0 == i) || (2 == pos % 100) ) text_buf[i] = (char) (unsigned char) ((test_msg_large_app_data == msg_type) ? ('Z' - pos % ('Z' - 'A' + 1)) : ('A' + pos % ('Z' - 'A' + 1))); else if (0 == pos % 100) text_buf[i] = '.'; else if (1 == pos % 100) text_buf[i] = ' '; else if ((99 != pos % 100) && (2 != pos % 100) && (0 == pos % 5)) text_buf[i] = ' '; else if (test_msg_large_app_data == msg_type) text_buf[i] = (char) (unsigned char) ('z' - pos % ('z' - 'a' + 1)); else text_buf[i] = (char) (unsigned char) ('a' + pos % ('z' - 'a' + 1)); } break; case test_msg_vlarge_app_data: /* Simulate binary data */ for (i = 0; i < buf_size; ++i) { bin_buf[i] = (uint8_t) ((i + 182) & 0xFF); } break; case test_msg_vlarge_rclient_data: /* Simulate binary data */ for (i = 0; i < buf_size; ++i) { bin_buf[i] = (uint8_t) ((111 - i) & 0xFF); } break; default: exit (99); break; } return buf; } /** * Perform initialisation of variables used in all check in this test * @return true if succeed, * false if failed. */ static bool global_test_init (void) { if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) global_port = 0; else { global_port = 1090; if (test_tls) global_port += 1U << 0; if (use_large) global_port += 1U << 1; else if (use_vlarge) global_port += 1U << 2; } if (use_large || use_vlarge) { unsigned int i; size_t alloc_size; alloc_size = use_vlarge ? (64U * 1024U) : (17U * 1024U); for (i = 0; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); ++i) { alloc_ptr[i] = malloc (alloc_size); if (NULL == alloc_ptr[i]) { for (--i; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); --i) { free (alloc_ptr[i]); } return false; } } rclient_msg_size = alloc_size; rclient_msg = init_test_msg (alloc_ptr[0], rclient_msg_size, use_vlarge ? test_msg_vlarge_rclient_data : test_msg_large_rclient_data); app_msg_size = alloc_size; app_msg = init_test_msg (alloc_ptr[1], app_msg_size, use_vlarge ? test_msg_vlarge_app_data : test_msg_large_app_data); } else { unsigned int i; for (i = 0; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); ++i) alloc_ptr[i] = NULL; rclient_msg_size = MHD_STATICSTR_LEN_ ("Hello"); rclient_msg = "Hello"; app_msg_size = MHD_STATICSTR_LEN_ ("World"); app_msg = "World"; } return true; } /** * Perform de-initialisation of variables with memory de-allocation if required. */ static void global_test_deinit (void) { unsigned int i; for (i = ((sizeof(alloc_ptr) / sizeof(alloc_ptr[0])) - 1); i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); --i) { if (NULL != alloc_ptr[i]) free (alloc_ptr[i]); } } int main (int argc, char *const *argv) { unsigned int error_count = 0; unsigned int res; use_vlarge = (0 != has_in_name (argv[0], "_vlarge")); use_large = (! use_vlarge) && (0 != has_in_name (argv[0], "_large")); use_tls_tool = TLS_CLI_NO_TOOL; test_tls = has_in_name (argv[0], "_tls"); verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if ((((int) ((~((unsigned int) 0U)) >> 1)) / 1000) < test_timeout) { fprintf (stderr, "The test timeout value (%d) is too large.\n" "The test cannot run.\n", test_timeout); fprintf (stderr, "The maximum allowed timeout value is %d.\n", (((int) ((~((unsigned int) 0U)) >> 1)) / 1000)); return 3; } if (test_tls) { use_tls_tool = TLS_LIB_GNUTLS; /* Should be always available as MHD uses it. */ #ifdef HTTPS_SUPPORT if (has_param (argc, argv, "--use-gnutls-cli")) use_tls_tool = TLS_CLI_GNUTLS; else if (has_param (argc, argv, "--use-openssl")) use_tls_tool = TLS_CLI_OPENSSL; else if (has_param (argc, argv, "--use-gnutls-lib")) use_tls_tool = TLS_LIB_GNUTLS; #if defined(HAVE_FORK) && defined(HAVE_WAITPID) else if (0 == system ("gnutls-cli --version 1> /dev/null 2> /dev/null")) use_tls_tool = TLS_CLI_GNUTLS; else if (0 == system ("openssl version 1> /dev/null 2> /dev/null")) use_tls_tool = TLS_CLI_OPENSSL; #endif /* HAVE_FORK && HAVE_WAITPID */ if (verbose) { switch (use_tls_tool) { case TLS_CLI_GNUTLS: printf ("GnuTLS-CLI will be used for testing.\n"); break; case TLS_CLI_OPENSSL: printf ("Command line version of OpenSSL will be used for testing.\n"); break; case TLS_LIB_GNUTLS: printf ("GnuTLS library will be used for testing.\n"); break; case TLS_CLI_NO_TOOL: default: externalErrorExitDesc ("Wrong 'use_tls_tool' value"); } } if ( (TLS_LIB_GNUTLS == use_tls_tool) && (GNUTLS_E_SUCCESS != gnutls_global_init ()) ) externalErrorExitDesc ("gnutls_global_init() failed"); #else /* ! HTTPS_SUPPORT */ fprintf (stderr, "HTTPS support was disabled by configure.\n"); return 77; #endif /* ! HTTPS_SUPPORT */ } if (! global_test_init ()) { #ifdef HTTPS_SUPPORT if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool)) gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ fprintf (stderr, "Failed to initialise the test.\n"); return 99; } /* run tests */ if (verbose) printf ("Starting HTTP \"Upgrade\" tests with %s connections.\n", test_tls ? "TLS" : "plain"); /* try external select */ res = test_upgrade (0, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external select, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external select.\n"); /* Try external auto */ res = test_upgrade (MHD_USE_AUTO, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external 'auto', return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external 'auto'.\n"); #ifdef EPOLL_SUPPORT res = test_upgrade (MHD_USE_EPOLL, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external select with EPOLL, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external select with EPOLL.\n"); #endif /* Test thread-per-connection */ res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection and 'auto', return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection and 'auto'.\n"); #ifdef HAVE_POLL res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection and poll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection and poll.\n"); #endif /* HAVE_POLL */ /* Test different event loops, with and without thread pool */ res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal select, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal select.\n"); res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD, 2); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal select with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal select with thread pool.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal 'auto' return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal 'auto'.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, 2); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal 'auto' with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal 'auto' with thread pool.\n"); #ifdef HAVE_POLL res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal poll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal poll.\n"); res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD, 2); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal poll with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal poll with thread pool.\n"); #endif #ifdef EPOLL_SUPPORT res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD, 0); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal epoll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal epoll.\n"); res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD, 2); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal epoll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal epoll.\n"); #endif /* report result */ if (0 != error_count) fprintf (stderr, "Error (code: %u)\n", error_count); global_test_deinit (); #ifdef HTTPS_SUPPORT if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool)) gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ return error_count != 0; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/test_mhd_version.c0000644000175000017500000001415115035214301017757 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/test_mhd_version.Ñ * @brief Tests for MHD versions identifiers * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #ifdef HAVE_INTTYPES_H #include #else /* ! HAVE_INTTYPES_H */ #define PRIX32 "X" #endif /* ! HAVE_INTTYPES_H */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "microhttpd.h" #ifdef PACKAGE_VERSION static const char str_macro_pkg_ver[] = PACKAGE_VERSION; #else /* ! PACKAGE_VERSION */ static const char str_macro_pkg_ver[] = "error!"; #error No PACKAGE_VERSION defined #endif /* ! PACKAGE_VERSION */ #ifdef VERSION static const char str_macro_ver[] = VERSION; #else /* ! VERSION */ static const char str_macro_ver[] = "error!"; #error No PACKAGE_VERSION defined #endif /* ! VERSION */ #ifdef MHD_VERSION static const uint32_t bin_macro = (uint32_t) (MHD_VERSION); #else /* ! MHD_VERSION */ static const uint32_t bin_macro = 0; #error MHD_VERSION is not defined #endif /* ! MHD_VERSION */ /* 0 = success, 1 = failure */ static int test_macro1_vs_macro2_str (void) { printf ("Checking PACKAGE_VERSION macro vs VERSION macro.\n"); if (0 != strcmp (str_macro_pkg_ver, str_macro_ver)) { fprintf (stderr, "'%s' vs '%s' - FAILED.\n", str_macro_pkg_ver, str_macro_ver); return 1; } printf ("'%s' vs '%s' - success.\n", str_macro_pkg_ver, str_macro_ver); return 0; } /* 0 = success, 1 = failure */ static int test_macro2_vs_func_str (void) { const char *str_func = MHD_get_version (); printf ("Checking VERSION macro vs MHD_get_version() function.\n"); if (NULL == str_func) { fprintf (stderr, "MHD_get_version() returned NULL.\n"); return 1; } if (0 != strcmp (str_macro_ver, str_func)) { fprintf (stderr, "'%s' vs '%s' - FAILED.\n", str_macro_ver, str_func); return 1; } printf ("'%s' vs '%s' - success.\n", str_macro_ver, str_func); return 0; } /* 0 = success, 1 = failure */ static int test_func_str_vs_macro_bin (void) { char bin_print[64]; int res; const char *str_func = MHD_get_version (); printf ("Checking MHD_get_version() function vs MHD_VERSION macro.\n"); #ifdef HAVE_SNPRINTF res = snprintf (bin_print, sizeof(bin_print), "%X.%X.%X", (unsigned int) ((bin_macro >> 24) & 0xFF), (unsigned int) ((bin_macro >> 16) & 0xFF), (unsigned int) ((bin_macro >> 8) & 0xFF)); #else /* ! HAVE_SNPRINTF */ res = sprintf (bin_print, "%X.%X.%X", (unsigned int) ((bin_macro >> 24) & 0xFF), (unsigned int) ((bin_macro >> 16) & 0xFF), (unsigned int) ((bin_macro >> 8) & 0xFF)); #endif /* ! HAVE_SNPRINTF */ if ((9 < res) || (0 >= res)) { fprintf (stderr, "snprintf() error.\n"); exit (99); } if (0 != strcmp (str_func, bin_print)) { fprintf (stderr, "'%s' vs '0x%08" PRIX32 "' ('%s') - FAILED.\n", str_func, bin_macro, bin_print); return 1; } fprintf (stderr, "'%s' vs '0x%08" PRIX32 "' ('%s') - success.\n", str_func, bin_macro, bin_print); return 0; } /* 0 = success, 1 = failure */ static int test_macro_vs_func_bin (void) { const uint32_t bin_func = MHD_get_version_bin (); printf ("Checking MHD_VERSION macro vs MHD_get_version_bin() function.\n"); if (bin_macro != bin_func) { fprintf (stderr, "'0x%08" PRIX32 "' vs '0x%08" PRIX32 "' - FAILED.\n", bin_macro, bin_func); return 1; } printf ("'0x%08" PRIX32 "' vs '0x%08" PRIX32 "' - success.\n", bin_macro, bin_func); return 0; } /* 0 = success, 1 = failure */ static int test_func_bin_format (void) { const uint32_t bin_func = MHD_get_version_bin (); unsigned int test_byte; int ret = 0; printf ("Checking format of MHD_get_version_bin() function return value.\n"); test_byte = (unsigned int) ((bin_func >> 24) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fprintf (stderr, "Invalid value in the first (most significant) byte: %02X\n", test_byte); ret = 1; } test_byte = (unsigned int) ((bin_func >> 16) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fprintf (stderr, "Invalid value in the second byte: %02X\n", test_byte); ret = 1; } test_byte = (unsigned int) ((bin_func >> 8) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fprintf (stderr, "Invalid value in the third byte: %02X\n", test_byte); ret = 1; } if (0 != ret) { fprintf (stderr, "The value (0x%08" PRIX32 ") returned by MHD_get_version_bin() " "function is invalid as it cannot be used as packed BCD form " "(its hexadecimal representation has at least one digit in " "A-F range).\n", bin_func); return 1; } printf ("'0x%08" PRIX32 "' - success.\n", bin_func); return 0; } int main (void) { int res; res = test_macro1_vs_macro2_str (); res += test_macro2_vs_func_str (); res += test_func_str_vs_macro_bin (); res += test_macro_vs_func_bin (); res += test_func_bin_format (); if (0 != res) { fprintf (stderr, "Test failed. Number of errors: %d\n", res); return 1; } printf ("Test succeed.\n"); return 0; } libmicrohttpd-1.0.2/src/microhttpd/mhd_itc.h0000644000175000017500000002533415035214301016024 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc.h * @brief Header for platform-independent inter-thread communication * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic abstraction for inter-thread communication. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_ITC_H #define MHD_ITC_H 1 #include "mhd_itc_types.h" #include #ifndef MHD_PANIC # include # ifdef HAVE_STDLIB_H # include # endif /* HAVE_STDLIB_H */ /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #if defined(_MHD_ITC_EVENTFD) /* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */ #include #include /* for uint64_t */ #ifdef HAVE_UNISTD_H #include /* for read(), write() */ #endif /* HAVE_UNISTD_H */ #ifdef HAVE_STRING_H #include /* for strerror() */ #include #endif /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (1) /** * Initialise ITC by generating eventFD * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_init_(itc) \ (-1 != ((itc).fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK))) /** * Get description string of last errno for itc operations. */ #define MHD_itc_last_strerror_() strerror (errno) /** * Internal static const helper for MHD_itc_activate_() */ static const uint64_t _MHD_itc_wr_data = 1; /** * Activate signal on @a itc * @param itc the itc to use * @param str ignored * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((write ((itc).fd, (const void*) &_MHD_itc_wr_data, \ sizeof(_MHD_itc_wr_data)) > 0) || (EAGAIN == errno)) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).fd) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).fd) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) \ do { uint64_t __b; \ (void) read ((itc).fd, (void*)&__b, sizeof(__b)); \ } while (0) /** * Destroy previously initialised ITC. Note that close() * on some platforms returns odd errors, so we ONLY fail * if the errno is EBADF. * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ ((0 == close ((itc).fd)) || (EBADF != errno)) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (-1 != ((itc).fd)) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) ((itc).fd = -1) #elif defined(_MHD_ITC_PIPE) /* **************** Standard UNIX ITC implementation by pipe ********** */ #if defined(HAVE_PIPE2_FUNC) && defined(HAVE_FCNTL_H) # include /* for O_CLOEXEC, O_NONBLOCK */ #endif /* HAVE_PIPE2_FUNC && HAVE_FCNTL_H */ #ifdef HAVE_UNISTD_H #include /* for read(), write(), errno */ #endif /* HAVE_UNISTD_H */ #ifdef HAVE_STRING_H #include /* for strerror() */ #endif /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (2) /** * Initialise ITC by generating pipe * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #ifdef HAVE_PIPE2_FUNC # define MHD_itc_init_(itc) (! pipe2 ((itc).fd, O_CLOEXEC | O_NONBLOCK)) #else /* ! HAVE_PIPE2_FUNC */ # define MHD_itc_init_(itc) \ ( (! pipe ((itc).fd)) ? \ (MHD_itc_nonblocking_ ((itc)) ? \ (! 0) : \ (MHD_itc_destroy_ ((itc)), 0) ) \ : (0) ) #endif /* ! HAVE_PIPE2_FUNC */ /** * Get description string of last errno for itc operations. */ #define MHD_itc_last_strerror_() strerror (errno) /** * Activate signal on @a itc * @param itc the itc to use * @param str one-symbol string, useful only for strace debug * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((write ((itc).fd[1], (const void*) (str), 1) > 0) || (EAGAIN == errno)) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).fd[0]) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).fd[1]) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) do \ { long __b; \ while (0 < read ((itc).fd[0], (void*) &__b, sizeof(__b))) \ {(void)0;} } while (0) /** * Destroy previously initialised ITC * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ ( (0 == close ((itc).fd[0])) ? \ (0 == close ((itc).fd[1])) : \ ((close ((itc).fd[1])), 0) ) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (-1 != (itc).fd[0]) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) ((itc).fd[0] = (itc).fd[1] = -1) #ifndef HAVE_PIPE2_FUNC /** * Change itc FD options to be non-blocking. * * @param fd the FD to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_itc_nonblocking_ (struct MHD_itc_ itc); #endif /* ! HAVE_PIPE2_FUNC */ #elif defined(_MHD_ITC_SOCKETPAIR) /* **************** ITC implementation by socket pair ********** */ #include "mhd_sockets.h" /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (2) /** * Initialise ITC by generating socketpair * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #ifdef MHD_socket_pair_nblk_ # define MHD_itc_init_(itc) MHD_socket_pair_nblk_ ((itc).sk) #else /* ! MHD_socket_pair_nblk_ */ # define MHD_itc_init_(itc) \ (MHD_socket_pair_ ((itc).sk) ? \ (MHD_itc_nonblocking_ ((itc)) ? \ (! 0) : \ (MHD_itc_destroy_ ((itc)), 0) ) \ : (0)) #endif /* ! MHD_socket_pair_nblk_ */ /** * Get description string of last error for itc operations. */ #define MHD_itc_last_strerror_() MHD_socket_last_strerr_ () /** * Activate signal on @a itc * @param itc the itc to use * @param str one-symbol string, useful only for strace debug * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((MHD_send_ ((itc).sk[1], (str), 1) > 0) || \ (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()))) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).sk[0]) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).sk[1]) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) do \ { long __b; \ while (0 < recv ((itc).sk[0], (void*) &__b, sizeof(__b), 0)) \ {(void)0;} } while (0) /** * Destroy previously initialised ITC * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ (MHD_socket_close_ ((itc).sk[0]) ? \ MHD_socket_close_ ((itc).sk[1]) : \ ((void) MHD_socket_close_ ((itc).sk[1]), 0) ) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (MHD_INVALID_SOCKET != (itc).sk[0]) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) \ ((itc).sk[0] = (itc).sk[1] = MHD_INVALID_SOCKET) #ifndef MHD_socket_pair_nblk_ # define MHD_itc_nonblocking_(pip) \ (MHD_socket_nonblocking_ ((pip).sk[0]) && \ MHD_socket_nonblocking_ ((pip).sk[1])) #endif /* ! MHD_socket_pair_nblk_ */ #endif /* _MHD_ITC_SOCKETPAIR */ /** * Destroy previously initialised ITC and abort execution * if error is detected. * @param itc the itc to destroy */ #define MHD_itc_destroy_chk_(itc) do { \ if (! MHD_itc_destroy_ (itc)) \ MHD_PANIC (_ ("Failed to destroy ITC.\n")); \ } while (0) /** * Check whether ITC has invalid value. * * Macro check whether @a itc value is invalid, * macro does not check whether @a itc was destroyed. * @param itc the itc to check * @return boolean true if @a itc has invalid value, * boolean false otherwise. */ #define MHD_ITC_IS_INVALID_(itc) (! MHD_ITC_IS_VALID_ (itc)) #endif /* MHD_ITC_H */ libmicrohttpd-1.0.2/src/microhttpd/test_postprocessor.c0000644000175000017500000006677114760713574020432 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2013, 2019, 2020 Christian Grothoff Copyright (C) 2021 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor.c * @brief Testcase for postprocessor * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "internal.h" #include #include #include #include "mhd_compat.h" #ifndef WINDOWS #include #endif #ifndef MHD_DEBUG_PP #define MHD_DEBUG_PP 0 #endif /* MHD_DEBUG_PP */ struct expResult { const char *key; const char *fname; const char *cnt_type; const char *tr_enc; const char *data; }; /** * Array of values that the value checker "wants". * Each series of checks should be terminated by * five NULL-entries. */ static struct expResult exp_results[] = { #define URL_NOVALUE1_DATA "abc&x=5" #define URL_NOVALUE1_START 0 {"abc", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */ {"x", NULL, NULL, NULL, "5"}, #define URL_NOVALUE1_END (URL_NOVALUE1_START + 2) #define URL_NOVALUE2_DATA "abc=&x=5" #define URL_NOVALUE2_START URL_NOVALUE1_END {"abc", NULL, NULL, NULL, ""}, {"x", NULL, NULL, NULL, "5"}, #define URL_NOVALUE2_END (URL_NOVALUE2_START + 2) #define URL_NOVALUE3_DATA "xyz=" #define URL_NOVALUE3_START URL_NOVALUE2_END {"xyz", NULL, NULL, NULL, ""}, #define URL_NOVALUE3_END (URL_NOVALUE3_START + 1) #define URL_NOVALUE4_DATA "xyz" #define URL_NOVALUE4_START URL_NOVALUE3_END {"xyz", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */ #define URL_NOVALUE4_END (URL_NOVALUE4_START + 1) #define URL_DATA "abc=def&x=5" #define URL_START URL_NOVALUE4_END {"abc", NULL, NULL, NULL, "def"}, {"x", NULL, NULL, NULL, "5"}, #define URL_END (URL_START + 2) #define URL_ENC_DATA "space=%20&key%201=&crlf=%0D%0a&mix%09ed=%2001%0d%0A" #define URL_ENC_START URL_END {"space", NULL, NULL, NULL, " "}, {"key 1", NULL, NULL, NULL, ""}, {"crlf", NULL, NULL, NULL, "\r\n"}, {"mix\ted", NULL, NULL, NULL, " 01\r\n"}, #define URL_ENC_END (URL_ENC_START + 4) {NULL, NULL, NULL, NULL, NULL}, #define FORM_DATA \ "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \ "Joe Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\";" \ " filename=\"file1.txt\"\r\nContent-Type: text/plain\r\n" \ "Content-Transfer-Encoding: binary\r\n\r\nfiledata\r\n--AaB03x--\r\n" #define FORM_START (URL_ENC_END + 1) {"field1", NULL, NULL, NULL, "Joe Blow"}, {"pics", "file1.txt", "text/plain", "binary", "filedata"}, #define FORM_END (FORM_START + 2) {NULL, NULL, NULL, NULL, NULL}, #define FORM_NESTED_DATA \ "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \ "Jane Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\"\r\n" \ "Content-type: multipart/mixed, boundary=BbC04y\r\n\r\n--BbC04y\r\n" \ "Content-disposition: attachment; filename=\"file1.txt\"\r\n" \ "Content-Type: text/plain\r\n\r\nfiledata1\r\n--BbC04y\r\n" \ "Content-disposition: attachment; filename=\"file2.gif\"\r\n" \ "Content-type: image/gif\r\nContent-Transfer-Encoding: binary\r\n\r\n" \ "filedata2\r\n--BbC04y--\r\n--AaB03x--" #define FORM_NESTED_START (FORM_END + 1) {"field1", NULL, NULL, NULL, "Jane Blow"}, {"pics", "file1.txt", "text/plain", NULL, "filedata1"}, {"pics", "file2.gif", "image/gif", "binary", "filedata2"}, #define FORM_NESTED_END (FORM_NESTED_START + 3) {NULL, NULL, NULL, NULL, NULL}, #define URL_EMPTY_VALUE_DATA "key1=value1&key2=&key3=" #define URL_EMPTY_VALUE_START (FORM_NESTED_END + 1) {"key1", NULL, NULL, NULL, "value1"}, {"key2", NULL, NULL, NULL, ""}, {"key3", NULL, NULL, NULL, ""}, #define URL_EMPTY_VALUE_END (URL_EMPTY_VALUE_START + 3) {NULL, NULL, NULL, NULL, NULL} }; static int mismatch (const char *a, const char *b) { if (a == b) return 0; if ((a == NULL) || (b == NULL)) return 1; return 0 != strcmp (a, b); } static int mismatch2 (const char *data, const char *expected, size_t offset, size_t size) { if (data == expected) return 0; if ((data == NULL) || (expected == NULL)) return 1; return 0 != memcmp (data, expected + offset, size); } static enum MHD_Result value_checker (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { unsigned int *idxp = cls; struct expResult *expect = exp_results + *idxp; (void) kind; /* Unused. Silent compiler warning. */ #if MHD_DEBUG_PP fprintf (stderr, "VC: `%s' `%s' `%s' `%s' (+%u)`%.*s' (%d)\n", key ? key : "(NULL)", filename ? filename : "(NULL)", content_type ? content_type : "(NULL)", transfer_encoding ? transfer_encoding : "(NULL)", (unsigned int) off, (int) (data ? size : 6), data ? data : "(NULL)", (int) size); #endif if (*idxp == (unsigned int) -1) exit (99); if ( (0 != off) && (0 == size) ) { if (NULL == expect->data) *idxp += 1; return MHD_YES; } if ((expect->key == NULL) || (0 != strcmp (key, expect->key)) || (mismatch (filename, expect->fname)) || (mismatch (content_type, expect->cnt_type)) || (mismatch (transfer_encoding, expect->tr_enc)) || (strlen (expect->data) < off) || (mismatch2 (data, expect->data, (size_t) off, size))) { *idxp = (unsigned int) -1; fprintf (stderr, "Failed with: `%s' `%s' `%s' `%s' `%.*s'\n", key ? key : "(NULL)", filename ? filename : "(NULL)", content_type ? content_type : "(NULL)", transfer_encoding ? transfer_encoding : "(NULL)", (int) (data ? size : 6), data ? data : "(NULL)"); fprintf (stderr, "Wanted: `%s' `%s' `%s' `%s' `%s'\n", expect->key ? expect->key : "(NULL)", expect->fname ? expect->fname : "(NULL)", expect->cnt_type ? expect->cnt_type : "(NULL)", expect->tr_enc ? expect->tr_enc : "(NULL)", expect->data ? expect->data : "(NULL)"); fprintf (stderr, "Unexpected result: %d/%d/%d/%d/%d/%d\n", (expect->key == NULL), (NULL != expect->key) && (0 != strcmp (key, expect->key)), (mismatch (filename, expect->fname)), (mismatch (content_type, expect->cnt_type)), (mismatch (transfer_encoding, expect->tr_enc)), (strlen (expect->data) < off) || (mismatch2 (data, expect->data, (size_t) off, size))); return MHD_NO; } if ( ( (NULL == expect->data) && (0 == off + size) ) || ( (NULL != expect->data) && (off + size == strlen (expect->data)) ) ) *idxp += 1; return MHD_YES; } static unsigned int test_urlencoding_case (unsigned int want_start, unsigned int want_end, const char *url_data) { size_t step; unsigned int errors = 0; const size_t size = strlen (url_data); for (step = 1; size >= step; ++step) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = want_start; size_t i; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { size_t left = size - i; if (MHD_YES != MHD_post_process (pp, &url_data[i], (left > step) ? step : left)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } MHD_destroy_post_processor (pp); if (want_off != want_end) { fprintf (stderr, "Test failed in line %u.\tStep: %u.\tData: \"%s\"\n" \ " Got: %u\tExpected: %u\n", (unsigned int) __LINE__, (unsigned int) step, url_data, want_off, want_end); errors++; } } return errors; } static unsigned int test_urlencoding (void) { unsigned int errorCount = 0; errorCount += test_urlencoding_case (URL_START, URL_END, URL_DATA); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, URL_ENC_DATA); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, URL_NOVALUE1_DATA); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, URL_NOVALUE2_DATA); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, URL_NOVALUE3_DATA); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_START, /* No advance */ URL_NOVALUE4_DATA); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, URL_EMPTY_VALUE_DATA); errorCount += test_urlencoding_case (URL_START, URL_END, URL_DATA "\n"); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, URL_ENC_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, URL_NOVALUE1_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, URL_NOVALUE2_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, URL_NOVALUE3_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_END, /* With advance */ URL_NOVALUE4_DATA "\n"); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, URL_EMPTY_VALUE_DATA "\n"); errorCount += test_urlencoding_case (URL_START, URL_END, "&&" URL_DATA); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, "&&" URL_ENC_DATA); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, "&&" URL_NOVALUE1_DATA); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, "&&" URL_NOVALUE2_DATA); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, "&&" URL_NOVALUE3_DATA); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_START, /* No advance */ "&&" URL_NOVALUE4_DATA); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, "&&" URL_EMPTY_VALUE_DATA); if (0 != errorCount) fprintf (stderr, "Test failed in line %u with %u errors\n", (unsigned int) __LINE__, errorCount); return errorCount; } static unsigned int test_multipart_garbage (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off; size_t size = MHD_STATICSTR_LEN_ (FORM_DATA); size_t splitpoint; char xdata[MHD_STATICSTR_LEN_ (FORM_DATA) + 3]; /* fill in evil garbage at the beginning */ xdata[0] = '-'; xdata[1] = 'x'; xdata[2] = '\r'; memcpy (&xdata[3], FORM_DATA, size); size += 3; for (splitpoint = 1; splitpoint < size; splitpoint++) { want_off = FORM_START; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA \ ", boundary=AaB03x"); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } if (MHD_YES != MHD_post_process (pp, xdata, splitpoint)) { fprintf (stderr, "Test failed in line %u at point %d\n", (unsigned int) __LINE__, (int) splitpoint); exit (49); } if (MHD_YES != MHD_post_process (pp, &xdata[splitpoint], size - splitpoint)) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); exit (49); } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); return (unsigned int) splitpoint; } } return 0; } static unsigned int test_multipart_splits (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off; size_t size; size_t splitpoint; size = strlen (FORM_DATA); for (splitpoint = 1; splitpoint < size; splitpoint++) { want_off = FORM_START; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } if (MHD_YES != MHD_post_process (pp, FORM_DATA, splitpoint)) { fprintf (stderr, "Test failed in line %u at point %d\n", (unsigned int) __LINE__, (int) splitpoint); exit (49); } if (MHD_YES != MHD_post_process (pp, &FORM_DATA[splitpoint], size - splitpoint)) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); exit (49); } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); return (unsigned int) splitpoint; } } return 0; } static unsigned int test_multipart (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = FORM_START; size_t i; size_t delta; size_t size; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.kind = MHD_HEADER_KIND; header.header_size = strlen (header.header); header.value_size = strlen (header.value); pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } i = 0; size = strlen (FORM_DATA); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &FORM_DATA[i], delta)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. delta: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) delta, (unsigned int) __LINE__); exit (49); } i += delta; } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u\n", (unsigned int) __LINE__); return 2; } return 0; } static unsigned int test_nested_multipart (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = FORM_NESTED_START; size_t i; size_t delta; size_t size; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.kind = MHD_HEADER_KIND; header.header_size = strlen (header.header); header.value_size = strlen (header.value); pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } i = 0; size = strlen (FORM_NESTED_DATA); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &FORM_NESTED_DATA[i], delta)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. delta: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) delta, (unsigned int) __LINE__); exit (49); } i += delta; } MHD_destroy_post_processor (pp); if (want_off != FORM_NESTED_END) { fprintf (stderr, "Test failed in line %u\n", (unsigned int) __LINE__); return 4; } return 0; } static enum MHD_Result value_checker2 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) data; (void) off; (void) size; return MHD_YES; } static unsigned int test_overflow (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; size_t i; size_t j; size_t delta; char *buf; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; for (i = 128; i < 1024 * 1024; i += 1024) { pp = MHD_create_post_processor (&connection, 1024, &value_checker2, NULL); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } buf = malloc (i); if (NULL == buf) return 1; memset (buf, 'A', i); buf[i / 2] = '='; delta = 1 + (((size_t) MHD_random_ ()) % (i - 1)); j = 0; while (j < i) { if (j + delta > i) delta = i - j; if (MHD_NO == MHD_post_process (pp, &buf[j], delta)) break; j += delta; } free (buf); MHD_destroy_post_processor (pp); } return 0; } static unsigned int test_empty_key (void) { const char form_data[] = "=abcdef"; size_t step; const size_t size = MHD_STATICSTR_LEN_ (form_data); for (step = 1; size >= step; ++step) { size_t i; struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; connection.rq.headers_received_tail = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker2, NULL); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { if (MHD_NO != MHD_post_process (pp, form_data + i, (step > size - i) ? (size - i) : step)) { fprintf (stderr, "Succeed to process the broken data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } MHD_destroy_post_processor (pp); } return 0; } static unsigned int test_double_value (void) { const char form_data[] = URL_DATA "=abcdef"; size_t step; const size_t size = MHD_STATICSTR_LEN_ (form_data); const size_t safe_size = MHD_STATICSTR_LEN_ (URL_DATA); for (step = 1; size >= step; ++step) { size_t i; struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int results_off = URL_START; unsigned int results_final = results_off + 1; /* First value is correct */ memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; connection.rq.headers_received_tail = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &results_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { if (MHD_NO != MHD_post_process (pp, form_data + i, (step > size - i) ? (size - i) : step)) { if (safe_size == i + step) results_final = URL_END; if (safe_size < i + step) { fprintf (stderr, "Succeed to process the broken data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } else { if (safe_size >= i + step) { fprintf (stderr, "Failed to process the data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } } MHD_destroy_post_processor (pp); if (results_final != results_off) { fprintf (stderr, "Test failed in line %u.\tStep:%u\n Got: %u\tExpected: %u\n", (unsigned int) __LINE__, (unsigned int) step, results_off, results_final); return 1; } } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_multipart_splits (); errorCount += test_multipart_garbage (); errorCount += test_urlencoding (); errorCount += test_multipart (); errorCount += test_nested_multipart (); errorCount += test_empty_key (); errorCount += test_double_value (); errorCount += test_overflow (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/mhd_mono_clock.h0000644000175000017500000000373515035214301017371 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_mono_clock.h * @brief internal monotonic clock functions declarations * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MONO_CLOCK_H #define MHD_MONO_CLOCK_H 1 #include "mhd_options.h" #if defined(HAVE_TIME_H) #include #elif defined(HAVE_SYS_TYPES_H) #include #endif #include /** * Initialise monotonic seconds and milliseconds counters. */ void MHD_monotonic_sec_counter_init (void); /** * Deinitialise monotonic seconds and milliseconds counters by freeing * any allocated resources */ void MHD_monotonic_sec_counter_finish (void); /** * Monotonic seconds counter. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of seconds from some fixed moment */ time_t MHD_monotonic_sec_counter (void); /** * Monotonic milliseconds counter, useful for timeout calculation. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of microseconds from some fixed moment */ uint64_t MHD_monotonic_msec_counter (void); #endif /* MHD_MONO_CLOCK_H */ libmicrohttpd-1.0.2/src/microhttpd/test_str_base64.c0000644000175000017500000011425514760713574017450 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_base64.c * @brief Unit tests for base64 strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #define TEST_BIN_MAX_SIZE 1024 /* return zero if succeed, one otherwise */ static unsigned int expect_decoded_n (const char *const encoded, const size_t encoded_len, const uint8_t *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static uint8_t buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size); mhd_assert (encoded_len >= decoded_size); mhd_assert (0 == encoded_len || encoded_len > decoded_size); ret = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, decoded_size); if (res_size != decoded_size) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n"); } else if ((0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong output binary:\n"); } if (0 != ret) { static char prnt[TEST_BIN_MAX_SIZE * 2 + 1]; size_t prnt_size; if (TEST_BIN_MAX_SIZE <= res_size * 2) { fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) decoded_size, (unsigned) res_size); } else { prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt); mhd_assert (2 * res_size == prnt_size); fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) decoded_size, (unsigned) res_size); } prnt_size = MHD_bin_to_hex_z (decoded, decoded_size, prnt); mhd_assert (2 * decoded_size == prnt_size); fprintf (stderr, "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) decoded_size, (unsigned) decoded_size); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded(e,d) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ (const uint8_t*)(d),MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded ("", ""); /* Base sequences without padding */ r += expect_decoded ("YWFh", "aaa"); r += expect_decoded ("YmJi", "bbb"); r += expect_decoded ("Y2Nj", "ccc"); r += expect_decoded ("ZGRk", "ddd"); r += expect_decoded ("bGxs", "lll"); r += expect_decoded ("bW1t", "mmm"); r += expect_decoded ("bm5u", "nnn"); r += expect_decoded ("b29v", "ooo"); r += expect_decoded ("d3d3", "www"); r += expect_decoded ("eHh4", "xxx"); r += expect_decoded ("eXl5", "yyy"); r += expect_decoded ("enp6", "zzz"); r += expect_decoded ("QUFB", "AAA"); r += expect_decoded ("R0dH", "GGG"); r += expect_decoded ("TU1N", "MMM"); r += expect_decoded ("VFRU", "TTT"); r += expect_decoded ("Wlpa", "ZZZ"); r += expect_decoded ("MDEy", "012"); r += expect_decoded ("MzQ1", "345"); r += expect_decoded ("Njc4", "678"); r += expect_decoded ("OTAx", "901"); r += expect_decoded ("YWFhYWFh", "aaaaaa"); r += expect_decoded ("YmJiYmJi", "bbbbbb"); r += expect_decoded ("Y2NjY2Nj", "cccccc"); r += expect_decoded ("ZGRkZGRk", "dddddd"); r += expect_decoded ("bGxsbGxs", "llllll"); r += expect_decoded ("bW1tbW1t", "mmmmmm"); r += expect_decoded ("bm5ubm5u", "nnnnnn"); r += expect_decoded ("b29vb29v", "oooooo"); r += expect_decoded ("d3d3d3d3", "wwwwww"); r += expect_decoded ("eHh4eHh4", "xxxxxx"); r += expect_decoded ("eXl5eXl5", "yyyyyy"); r += expect_decoded ("enp6enp6", "zzzzzz"); r += expect_decoded ("QUFBQUFB", "AAAAAA"); r += expect_decoded ("R0dHR0dH", "GGGGGG"); r += expect_decoded ("TU1NTU1N", "MMMMMM"); r += expect_decoded ("VFRUVFRU", "TTTTTT"); r += expect_decoded ("WlpaWlpa", "ZZZZZZ"); r += expect_decoded ("MDEyMDEy", "012012"); r += expect_decoded ("MzQ1MzQ1", "345345"); r += expect_decoded ("Njc4Njc4", "678678"); r += expect_decoded ("OTAxOTAx", "901901"); /* Various lengths */ r += expect_decoded ("YQ==", "a"); r += expect_decoded ("YmM=", "bc"); r += expect_decoded ("REVGRw==", "DEFG"); r += expect_decoded ("MTIzdA==", "123t"); r += expect_decoded ("MTIzNDU=", "12345"); r += expect_decoded ("VGVzdCBTdHI=", "Test Str"); r += expect_decoded ("VGVzdCBzdHJpbmc=", "Test string"); r += expect_decoded ("VGVzdCBzdHJpbmcu", "Test string."); r += expect_decoded ("TG9uZ2VyIHN0cmluZw==", "Longer string"); r += expect_decoded ("TG9uZ2VyIHN0cmluZy4=", "Longer string."); r += expect_decoded ("TG9uZ2VyIHN0cmluZzIu", "Longer string2."); return r; } #define expect_decoded_arr(e,a) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; r += expect_decoded_arr ("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISI" \ "jJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERU" \ "ZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoa" \ "WprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouM" \ "jY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+" \ "wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0t" \ "PU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19" \ "vf4+fr7/P3+/w==", bin); } if (1) { static const uint8_t bin[256] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0 }; r += expect_decoded_arr ("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiM" \ "kJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRk" \ "dISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpa" \ "mtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yN" \ "jo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7C" \ "xsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09" \ "TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29" \ "/j5+vv8/f7/AA==", bin); } if (1) { static const uint8_t bin[256] = {0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0, 0x1 }; r += expect_decoded_arr ("AgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQ" \ "lJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0" \ "hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa" \ "2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2O" \ "j5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLG" \ "ys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1N" \ "XW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+" \ "Pn6+/z9/v8AAQ==", bin); } if (1) { static const uint8_t bin[256] = {0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0, 0x1, 0x2 }; r += expect_decoded_arr ("AwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCU" \ "mJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSE" \ "lKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprb" \ "G1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P" \ "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbK" \ "ztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1d" \ "bX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+" \ "fr7/P3+/wABAg==", bin); } if (1) { static const uint8_t bin[256] = {0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0 }; r += expect_decoded_arr ("//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3" \ "c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7ur" \ "m4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXl" \ "pWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRz" \ "cnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVB" \ "PTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLS" \ "wrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKC" \ "QgHBgUEAwIBAA==", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1}; r += expect_decoded_arr ("AP/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397" \ "d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7" \ "q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl" \ "5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0" \ "c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlF" \ "QT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi" \ "0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLC" \ "gkIBwYFBAMCAQ==", bin); } if (1) { static const uint8_t bin[256] = {0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2}; r += expect_decoded_arr ("AQD//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/" \ "e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vL" \ "u6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZm" \ "JeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1" \ "dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1J" \ "RUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy" \ "4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MC" \ "woJCAcGBQQDAg==", bin); } if (1) { static const uint8_t bin[256] = {0x2, 0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3}; r += expect_decoded_arr ("AgEA//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eD" \ "f3t3c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vb" \ "y7urm4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuam" \ "ZiXlpWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2" \ "dXRzcnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFN" \ "SUVBPTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC" \ "8uLSwrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4ND" \ "AsKCQgHBgUEAw==", bin); } if (1) { static const uint8_t bin[256] = {0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff}; r += expect_decoded_arr ("/v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dz" \ "b2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ub" \ "i3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWl" \ "ZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNy" \ "cXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9" \ "OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLC" \ "sqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJC" \ "AcGBQQDAgEA/w==", bin); } if (1) { static const uint8_t bin[256] = {0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff, 0xfe}; r += expect_decoded_arr ("/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nv" \ "a2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uL" \ "e2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVl" \ "JOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3Jx" \ "cG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05" \ "NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKy" \ "opKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIB" \ "wYFBAMCAQD//g==", bin); } if (1) { static const uint8_t bin[256] = {0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff, 0xfe, 0xfd }; r += expect_decoded_arr ("/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3c29r" \ "Z2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7urm4t7" \ "a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXlpWUk" \ "5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRzcnFw" \ "b25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVBPTk1" \ "MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLSwrKi" \ "koJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKCQgHB" \ "gUEAwIBAP/+/Q==", bin); } if (1) { static const uint8_t bin[48] = {0x00, 0x10, 0x83, 0x10, 0x51, 0x87, 0x20, 0x92, 0x8b, 0x30, 0xd3, 0x8f, 0x41, 0x14, 0x93, 0x51, 0x55, 0x97, 0x61, 0x96, 0x9b, 0x71, 0xd7, 0x9f, 0x82, 0x18, 0xa3, 0x92, 0x59, 0xa7, 0xa2, 0x9a, 0xab, 0xb2, 0xdb, 0xaf, 0xc3, 0x1c, 0xb3, 0xd3, 0x5d, 0xb7, 0xe3, 0x9e, 0xbb, 0xf3, 0xdf, 0xbf }; r += expect_decoded_arr ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefghijklmnopqrstuvwxyz0123456789+/", bin); } if (1) { static const uint8_t bin[49] = {0x00, 0x10, 0x83, 0x10, 0x51, 0x87, 0x20, 0x92, 0x8b, 0x30, 0xd3, 0x8f, 0x41, 0x14, 0x93, 0x51, 0x55, 0x97, 0x61, 0x96, 0x9b, 0x71, 0xd7, 0x9f, 0x82, 0x18, 0xa3, 0x92, 0x59, 0xa7, 0xa2, 0x9a, 0xab, 0xb2, 0xdb, 0xaf, 0xc3, 0x1c, 0xb3, 0xd3, 0x5d, 0xb7, 0xe3, 0x9e, 0xbb, 0xf3, 0xdf, 0xbf, 0x00 }; r += expect_decoded_arr ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefghijklmnopqrstuvwxyz0123456789+/" \ "AA==", bin); } if (1) { static const uint8_t bin[48] = {0xff, 0xef, 0x7c, 0xef, 0xae, 0x78, 0xdf, 0x6d, 0x74, 0xcf, 0x2c, 0x70, 0xbe, 0xeb, 0x6c, 0xae, 0xaa, 0x68, 0x9e, 0x69, 0x64, 0x8e, 0x28, 0x60, 0x7d, 0xe7, 0x5c, 0x6d, 0xa6, 0x58, 0x5d, 0x65, 0x54, 0x4d, 0x24, 0x50, 0x3c, 0xe3, 0x4c, 0x2c, 0xa2, 0x48, 0x1c, 0x61, 0x44, 0x0c, 0x20, 0x40 }; r += expect_decoded_arr ("/+9876543210zyxwvutsrqponmlkjihgfedcba" \ "ZYXWVUTSRQPONMLKJIHGFEDCBA", bin); } if (1) { static const uint8_t bin[49] = {0xff, 0xef, 0x7c, 0xef, 0xae, 0x78, 0xdf, 0x6d, 0x74, 0xcf, 0x2c, 0x70, 0xbe, 0xeb, 0x6c, 0xae, 0xaa, 0x68, 0x9e, 0x69, 0x64, 0x8e, 0x28, 0x60, 0x7d, 0xe7, 0x5c, 0x6d, 0xa6, 0x58, 0x5d, 0x65, 0x54, 0x4d, 0x24, 0x50, 0x3c, 0xe3, 0x4c, 0x2c, 0xa2, 0x48, 0x1c, 0x61, 0x44, 0x0c, 0x20, 0x40, 0x00 }; r += expect_decoded_arr ("/+9876543210zyxwvutsrqponmlkjihgfedcba" \ "ZYXWVUTSRQPONMLKJIHGFEDCBAAA==", bin); } return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_fail_n (const char *const encoded, const size_t encoded_len, const unsigned int line_num) { static const char fill_chr = '#'; static uint8_t buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len); ret = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, sizeof(buf)); if (res_size != 0) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n"); } if (0 != ret) { static char prnt[TEST_BIN_MAX_SIZE * 2 + 1]; size_t prnt_size; if (TEST_BIN_MAX_SIZE <= res_size * 2) { fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) sizeof(buf), (unsigned) res_size); } else { prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt); mhd_assert (2 * res_size == prnt_size); fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) sizeof(buf), (unsigned) res_size); } fprintf (stderr, "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->(empty), %u)" " -> 0\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) sizeof(buf)); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_fail(e) \ expect_fail_n(e,MHD_STATICSTR_LEN_(e),__LINE__) static unsigned int check_fail (void) { unsigned int r = 0; /**< The number of errors */ /* Base sequences with wrong length */ r += expect_fail ("YWFh/"); r += expect_fail ("YWFh/Q"); r += expect_fail ("YWFhE/Q"); r += expect_fail ("bW1tbW1t/"); r += expect_fail ("bW1tbW1t/Q"); r += expect_fail ("bW1tbW1tE/Q"); /* Base sequences with wrong char */ r += expect_fail ("%mJi"); r += expect_fail ("Y%Nj"); r += expect_fail ("ZG%k"); r += expect_fail ("bGx%"); r += expect_fail ("#W1t"); r += expect_fail ("b#5u"); r += expect_fail ("b2#v"); r += expect_fail ("d3d#"); r += expect_fail ("^Hh4"); r += expect_fail ("e^l5"); r += expect_fail ("en^6"); r += expect_fail ("QUF^"); r += expect_fail ("~0dH"); r += expect_fail ("T~1N"); r += expect_fail ("VF~U"); r += expect_fail ("Wlp~"); r += expect_fail ("*DEy"); r += expect_fail ("M*Q1"); r += expect_fail ("Nj*4"); r += expect_fail ("OTA*"); r += expect_fail ("&WFhYWFh"); r += expect_fail ("Y&JiYmJi"); r += expect_fail ("Y2&jY2Nj"); r += expect_fail ("ZGR&ZGRk"); r += expect_fail ("bGxs&Gxs"); r += expect_fail ("bW1tb&1t"); r += expect_fail ("bm5ubm&u"); r += expect_fail ("b29vb29&"); r += expect_fail ("!3d3d3d3"); r += expect_fail ("e!h4eHh4"); r += expect_fail ("eX!5eXl5"); r += expect_fail ("enp!enp6"); r += expect_fail ("QUFB!UFB"); r += expect_fail ("R0dHR!dH"); r += expect_fail ("TU1NTU!N"); r += expect_fail ("VFRUVFR!"); /* Bad high-ASCII char */ r += expect_fail ("\xff" "WFhYWFh"); r += expect_fail ("Y\xfe" "JiYmJi"); r += expect_fail ("Y2\xfd" "jY2Nj"); r += expect_fail ("ZGR\xfc" "ZGRk"); r += expect_fail ("bGxs\xfb" "Gxs"); r += expect_fail ("bW1tbW\xfa" "1t"); r += expect_fail ("bm5ubm\xf9" "u"); r += expect_fail ("b29vb29\xf8"); r += expect_fail ("d3d3d3d\x80"); r += expect_fail ("eHh4eH\x81" "4"); r += expect_fail ("eXl5e\x82" "l5"); r += expect_fail ("enp6\x83" "np6"); r += expect_fail ("QUF\x84" "QUFB"); r += expect_fail ("TU\x85" "NTU1N"); r += expect_fail ("V\x86" "RUVFRU"); r += expect_fail ("\x87" "lpaWlpa"); /* Base sequences with wrong padding char */ r += expect_fail ("=lpaWlpa"); r += expect_fail ("M=EyMDEy"); r += expect_fail ("Mz=1MzQ1"); r += expect_fail ("Njc=Njc4"); r += expect_fail ("OTAx=TAx"); r += expect_fail ("ZGRkZ=Rk"); r += expect_fail ("bGxsbG=s"); r += expect_fail ("bW1tb==="); r += expect_fail ("bm5u===="); /* Bad last char (valid for Base64, but padding part is not zero */ r += expect_fail ("TG9uZ2VyIHN0cmluZo=="); r += expect_fail ("TG9uZ2VyIHN0cmluZyK="); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_str (); errcount += check_decode_bin (); errcount += check_fail (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/postprocessor.c0000644000175000017500000011263015035214301017331 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file postprocessor.c * @brief Methods for parsing POST data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "postprocessor.h" #include "internal.h" #include "mhd_str.h" #include "mhd_compat.h" #include "mhd_assert.h" /** * Size of on-stack buffer that we use for un-escaping of the value. * We use a pretty small value to be nice to the stack on embedded * systems. */ #define XBUF_SIZE 512 _MHD_EXTERN struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iter, void *iter_cls) { struct MHD_PostProcessor *ret; const char *encoding; const char *boundary; size_t blen; if ( (buffer_size < 256) || (NULL == connection) || (NULL == iter)) MHD_PANIC (_ ("libmicrohttpd API violation.\n")); encoding = NULL; if (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_CONTENT_TYPE), &encoding, NULL)) return NULL; mhd_assert (NULL != encoding); boundary = NULL; if (! MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_FORM_URLENCODED))) { if (! MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))) return NULL; boundary = &encoding[MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)]; /* Q: should this be "strcasestr"? */ boundary = strstr (boundary, "boundary="); if (NULL == boundary) return NULL; /* failed to determine boundary */ boundary += MHD_STATICSTR_LEN_ ("boundary="); blen = strlen (boundary); if ( (blen < 2) || (blen * 2 + 2 > buffer_size) ) return NULL; /* (will be) out of memory or invalid boundary */ if ( (boundary[0] == '"') && (boundary[blen - 1] == '"') ) { /* remove enclosing quotes */ ++boundary; blen -= 2; } } else blen = 0; buffer_size += 4; /* round up to get nice block sizes despite boundary search */ /* add +1 to ensure we ALWAYS have a zero-termination at the end */ if (NULL == (ret = MHD_calloc_ (1, sizeof (struct MHD_PostProcessor) + buffer_size + 1))) return NULL; ret->connection = connection; ret->ikvi = iter; ret->cls = iter_cls; ret->encoding = encoding; ret->buffer_size = buffer_size; ret->state = PP_Init; ret->blen = blen; ret->boundary = boundary; ret->skip_rn = RN_Inactive; return ret; } /** * Give a (possibly partial) value to the application callback. We have some * part of the value in the 'pp->xbuf', the rest is between @a value_start and * @a value_end. If @a last_escape is non-NULL, there may be an incomplete * escape sequence at at @a value_escape between @a value_start and @a * value_end which we should preserve in 'pp->xbuf' for the future. * * Unescapes the value and calls the iterator together with the key. The key * must already be in the key buffer allocated and 0-terminated at the end of * @a pp at the time of the call. * * @param[in,out] pp post processor to act upon * @param value_start where in memory is the value * @param value_end where does the value end * @param last_escape last '%'-sign in value range, * if relevant, or NULL */ static void process_value (struct MHD_PostProcessor *pp, const char *value_start, const char *value_end, const char *last_escape) { char xbuf[XBUF_SIZE + 1]; size_t xoff; mhd_assert (pp->xbuf_pos < sizeof (xbuf)); /* 'value_start' and 'value_end' must be either both non-NULL or both NULL */ mhd_assert ( (NULL == value_start) || (NULL != value_end) ); mhd_assert ( (NULL != value_start) || (NULL == value_end) ); mhd_assert ( (NULL == last_escape) || (NULL != value_start) ); /* move remaining input from previous round into processing buffer */ if (0 != pp->xbuf_pos) memcpy (xbuf, pp->xbuf, pp->xbuf_pos); xoff = pp->xbuf_pos; pp->xbuf_pos = 0; if ( (NULL != last_escape) && (((size_t) (value_end - last_escape)) < sizeof (pp->xbuf)) ) { mhd_assert (value_end >= last_escape); pp->xbuf_pos = (size_t) (value_end - last_escape); memcpy (pp->xbuf, last_escape, (size_t) (value_end - last_escape)); value_end = last_escape; } while ( (value_start != value_end) || (pp->must_ikvi) || (xoff > 0) ) { size_t delta = (size_t) (value_end - value_start); bool cut = false; size_t clen = 0; mhd_assert (value_end >= value_start); if (delta > XBUF_SIZE - xoff) delta = XBUF_SIZE - xoff; /* move (additional) input into processing buffer */ if (0 != delta) { memcpy (&xbuf[xoff], value_start, delta); xoff += delta; value_start += delta; } /* find if escape sequence is at the end of the processing buffer; if so, exclude those from processing (reduce delta to point at end of processed region) */ if ( (xoff > 0) && ('%' == xbuf[xoff - 1]) ) { cut = (xoff != XBUF_SIZE); xoff--; if (cut) { /* move escape sequence into buffer for next function invocation */ pp->xbuf[0] = '%'; pp->xbuf_pos = 1; } else { /* just skip escape sequence for next loop iteration */ delta = xoff; clen = 1; } } else if ( (xoff > 1) && ('%' == xbuf[xoff - 2]) ) { cut = (xoff != XBUF_SIZE); xoff -= 2; if (cut) { /* move escape sequence into buffer for next function invocation */ memcpy (pp->xbuf, &xbuf[xoff], 2); pp->xbuf_pos = 2; } else { /* just skip escape sequence for next loop iteration */ delta = xoff; clen = 2; } } mhd_assert (xoff < sizeof (xbuf)); /* unescape */ xbuf[xoff] = '\0'; /* 0-terminate in preparation */ if (0 != xoff) { MHD_unescape_plus (xbuf); xoff = MHD_http_unescape (xbuf); } /* finally: call application! */ if (pp->must_ikvi || (0 != xoff) ) { pp->must_ikvi = false; if (MHD_NO == pp->ikvi (pp->cls, MHD_POSTDATA_KIND, (const char *) &pp[1], /* key */ NULL, NULL, NULL, xbuf, pp->value_offset, xoff)) { pp->state = PP_Error; return; } } pp->value_offset += xoff; if (cut) break; if (0 != clen) { xbuf[delta] = '%'; /* undo 0-termination */ memmove (xbuf, &xbuf[delta], clen); } xoff = clen; } } /** * Process url-encoded POST data. * * @param pp post processor context * @param post_data upload data * @param post_data_len number of bytes in @a post_data * @return #MHD_YES on success, #MHD_NO if there was an error processing the data */ static enum MHD_Result post_process_urlencoded (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { char *kbuf = (char *) &pp[1]; size_t poff; const char *start_key = NULL; const char *end_key = NULL; const char *start_value = NULL; const char *end_value = NULL; const char *last_escape = NULL; mhd_assert (PP_Callback != pp->state); poff = 0; while ( ( (poff < post_data_len) || (pp->state == PP_Callback) ) && (pp->state != PP_Error) ) { switch (pp->state) { case PP_Error: /* clearly impossible as per while loop invariant */ abort (); break; /* Unreachable */ case PP_Init: /* initial phase */ mhd_assert (NULL == start_key); mhd_assert (NULL == end_key); mhd_assert (NULL == start_value); mhd_assert (NULL == end_value); switch (post_data[poff]) { case '=': /* Case: (no key)'=' */ /* Empty key with value */ pp->state = PP_Error; continue; case '&': /* Case: (no key)'&' */ /* Empty key without value */ poff++; continue; case '\n': case '\r': /* Case: (no key)'\n' or (no key)'\r' */ pp->state = PP_Done; poff++; break; default: /* normal character, key start, advance! */ pp->state = PP_ProcessKey; start_key = &post_data[poff]; pp->must_ikvi = true; poff++; continue; } break; /* end PP_Init */ case PP_ProcessKey: /* key phase */ mhd_assert (NULL == start_value); mhd_assert (NULL == end_value); mhd_assert (NULL != start_key || 0 == poff); mhd_assert (0 != poff || NULL == start_key); mhd_assert (NULL == end_key); switch (post_data[poff]) { case '=': /* Case: 'key=' */ if (0 != poff) end_key = &post_data[poff]; poff++; pp->state = PP_ProcessValue; break; case '&': /* Case: 'key&' */ if (0 != poff) end_key = &post_data[poff]; poff++; pp->state = PP_Callback; break; case '\n': case '\r': /* Case: 'key\n' or 'key\r' */ if (0 != poff) end_key = &post_data[poff]; /* No advance here, 'PP_Done' will be selected by next 'PP_Init' phase */ pp->state = PP_Callback; break; default: /* normal character, advance! */ if (0 == poff) start_key = post_data; poff++; break; } mhd_assert (NULL == end_key || NULL != start_key); break; /* end PP_ProcessKey */ case PP_ProcessValue: if (NULL == start_value) start_value = &post_data[poff]; switch (post_data[poff]) { case '=': /* case 'key==' */ pp->state = PP_Error; continue; case '&': /* case 'value&' */ end_value = &post_data[poff]; poff++; if (pp->must_ikvi || (start_value != end_value) ) { pp->state = PP_Callback; } else { pp->buffer_pos = 0; pp->value_offset = 0; pp->state = PP_Init; start_value = NULL; end_value = NULL; } continue; case '\n': case '\r': /* Case: 'value\n' or 'value\r' */ end_value = &post_data[poff]; if (pp->must_ikvi || (start_value != end_value) ) pp->state = PP_Callback; /* No poff advance here to set PP_Done in the next iteration */ else { poff++; pp->state = PP_Done; } break; case '%': last_escape = &post_data[poff]; poff++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* character, may be part of escaping */ poff++; continue; default: /* normal character, no more escaping! */ last_escape = NULL; poff++; continue; } break; /* end PP_ProcessValue */ case PP_Done: switch (post_data[poff]) { case '\n': case '\r': poff++; continue; } /* unexpected data at the end, fail! */ pp->state = PP_Error; break; case PP_Callback: mhd_assert ((NULL != end_key) || (NULL == start_key)); if (1) { const size_t key_len = (size_t) (end_key - start_key); mhd_assert (end_key >= start_key); if (0 != key_len) { if ( (pp->buffer_pos + key_len >= pp->buffer_size) || (pp->buffer_pos + key_len < pp->buffer_pos) ) { /* key too long, cannot parse! */ pp->state = PP_Error; continue; } /* compute key, if we have not already */ memcpy (&kbuf[pp->buffer_pos], start_key, key_len); pp->buffer_pos += key_len; start_key = NULL; end_key = NULL; pp->must_unescape_key = true; } } #ifdef _DEBUG else mhd_assert (0 != pp->buffer_pos); #endif /* _DEBUG */ if (pp->must_unescape_key) { kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */ MHD_unescape_plus (kbuf); MHD_http_unescape (kbuf); pp->must_unescape_key = false; } process_value (pp, start_value, end_value, NULL); if (PP_Error == pp->state) continue; pp->value_offset = 0; start_value = NULL; end_value = NULL; pp->buffer_pos = 0; pp->state = PP_Init; break; case PP_NextBoundary: case PP_ProcessEntryHeaders: case PP_PerformCheckMultipart: case PP_ProcessValueToBoundary: case PP_PerformCleanup: case PP_Nested_Init: case PP_Nested_PerformMarking: case PP_Nested_ProcessEntryHeaders: case PP_Nested_ProcessValueToBoundary: case PP_Nested_PerformCleanup: default: MHD_PANIC (_ ("internal error.\n")); /* should never happen! */ } mhd_assert ((end_key == NULL) || (start_key != NULL)); mhd_assert ((end_value == NULL) || (start_value != NULL)); } mhd_assert (PP_Callback != pp->state); if (PP_Error == pp->state) { /* State in error, returning failure */ return MHD_NO; } /* save remaining data for next iteration */ if (NULL != start_key) { size_t key_len; mhd_assert ((PP_ProcessKey == pp->state) || (NULL != end_key)); if (NULL == end_key) end_key = &post_data[poff]; mhd_assert (end_key >= start_key); key_len = (size_t) (end_key - start_key); mhd_assert (0 != key_len); /* it must be always non-zero here */ if (pp->buffer_pos + key_len >= pp->buffer_size) { pp->state = PP_Error; return MHD_NO; } memcpy (&kbuf[pp->buffer_pos], start_key, key_len); pp->buffer_pos += key_len; pp->must_unescape_key = true; start_key = NULL; end_key = NULL; } if ( (NULL != start_value) && (PP_ProcessValue == pp->state) ) { /* compute key, if we have not already */ if (pp->must_unescape_key) { kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */ MHD_unescape_plus (kbuf); MHD_http_unescape (kbuf); pp->must_unescape_key = false; } if (NULL == end_value) end_value = &post_data[poff]; if ( (NULL != last_escape) && (2 < (end_value - last_escape)) ) last_escape = NULL; process_value (pp, start_value, end_value, last_escape); pp->must_ikvi = false; } if (PP_Error == pp->state) { /* State in error, returning failure */ return MHD_NO; } return MHD_YES; } /** * If the given line matches the prefix, strdup the * rest of the line into the suffix ptr. * * @param prefix prefix to match * @param prefix_len length of @a prefix * @param line line to match prefix in * @param suffix set to a copy of the rest of the line, starting at the end of the match * @return #MHD_YES if there was a match, #MHD_NO if not */ static int try_match_header (const char *prefix, size_t prefix_len, char *line, char **suffix) { if (NULL != *suffix) return MHD_NO; while (0 != *line) { if (MHD_str_equal_caseless_n_ (prefix, line, prefix_len)) { *suffix = strdup (&line[prefix_len]); return MHD_YES; } ++line; } return MHD_NO; } /** * * @param pp post processor context * @param boundary boundary to look for * @param blen number of bytes in boundary * @param ioffptr set to the end of the boundary if found, * otherwise incremented by one (FIXME: quirky API!) * @param next_state state to which we should advance the post processor * if the boundary is found * @param next_dash_state dash_state to which we should advance the * post processor if the boundary is found * @return #MHD_NO if the boundary is not found, #MHD_YES if we did find it */ static int find_boundary (struct MHD_PostProcessor *pp, const char *boundary, size_t blen, size_t *ioffptr, enum PP_State next_state, enum PP_State next_dash_state) { char *buf = (char *) &pp[1]; const char *dash; if (pp->buffer_pos < 2 + blen) { if (pp->buffer_pos == pp->buffer_size) pp->state = PP_Error; /* out of memory */ /* ++(*ioffptr); */ return MHD_NO; /* not enough data */ } if ( (0 != memcmp ("--", buf, 2)) || (0 != memcmp (&buf[2], boundary, blen))) { if (pp->state != PP_Init) { /* garbage not allowed */ pp->state = PP_Error; } else { /* skip over garbage (RFC 2046, 5.1.1) */ dash = memchr (buf, '-', pp->buffer_pos); if (NULL == dash) (*ioffptr) += pp->buffer_pos; /* skip entire buffer */ else if (dash == buf) (*ioffptr)++; /* at least skip one byte */ else (*ioffptr) += (size_t) (dash - buf); /* skip to first possible boundary */ } return MHD_NO; /* expected boundary */ } /* remove boundary from buffer */ (*ioffptr) += 2 + blen; /* next: start with headers */ pp->skip_rn = RN_Dash; pp->state = next_state; pp->dash_state = next_dash_state; return MHD_YES; } /** * In buf, there maybe an expression '$key="$value"'. If that is the * case, copy a copy of $value to destination. * * If destination is already non-NULL, do nothing. */ static void try_get_value (const char *buf, const char *key, char **destination) { const char *spos; const char *bpos; const char *endv; size_t klen; size_t vlen; if (NULL != *destination) return; bpos = buf; klen = strlen (key); while (NULL != (spos = strstr (bpos, key))) { if ( (spos[klen] != '=') || ( (spos != buf) && (spos[-1] != ' ') ) ) { /* no match */ bpos = spos + 1; continue; } if (spos[klen + 1] != '"') return; /* not quoted */ if (NULL == (endv = strchr (&spos[klen + 2], '\"'))) return; /* no end-quote */ vlen = (size_t) (endv - spos) - klen - 1; *destination = malloc (vlen); if (NULL == *destination) return; /* out of memory */ (*destination)[vlen - 1] = '\0'; memcpy (*destination, &spos[klen + 2], vlen - 1); return; /* success */ } } /** * Go over the headers of the part and update * the fields in "pp" according to what we find. * If we are at the end of the headers (as indicated * by an empty line), transition into next_state. * * @param pp post processor context * @param ioffptr set to how many bytes have been * processed * @param next_state state to which the post processor should * be advanced if we find the end of the headers * @return #MHD_YES if we can continue processing, * #MHD_NO on error or if we do not have * enough data yet */ static int process_multipart_headers (struct MHD_PostProcessor *pp, size_t *ioffptr, enum PP_State next_state) { char *buf = (char *) &pp[1]; size_t newline; newline = 0; while ( (newline < pp->buffer_pos) && (buf[newline] != '\r') && (buf[newline] != '\n') ) newline++; if (newline == pp->buffer_size) { pp->state = PP_Error; return MHD_NO; /* out of memory */ } if (newline == pp->buffer_pos) return MHD_NO; /* will need more data */ if (0 == newline) { /* empty line - end of headers */ pp->skip_rn = RN_Full; pp->state = next_state; return MHD_YES; } /* got an actual header */ if (buf[newline] == '\r') pp->skip_rn = RN_OptN; buf[newline] = '\0'; if (MHD_str_equal_caseless_n_ ("Content-disposition: ", buf, MHD_STATICSTR_LEN_ ("Content-disposition: "))) { try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")], "name", &pp->content_name); try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")], "filename", &pp->content_filename); } else { try_match_header ("Content-type: ", MHD_STATICSTR_LEN_ ("Content-type: "), buf, &pp->content_type); try_match_header ("Content-Transfer-Encoding: ", MHD_STATICSTR_LEN_ ("Content-Transfer-Encoding: "), buf, &pp->content_transfer_encoding); } (*ioffptr) += newline + 1; return MHD_YES; } /** * We have the value until we hit the given boundary; * process accordingly. * * @param pp post processor context * @param ioffptr incremented based on the number of bytes processed * @param boundary the boundary to look for * @param blen strlen(boundary) * @param next_state what state to go into after the * boundary was found * @param next_dash_state state to go into if the next * boundary ends with "--" * @return #MHD_YES if we can continue processing, * #MHD_NO on error or if we do not have * enough data yet */ static int process_value_to_boundary (struct MHD_PostProcessor *pp, size_t *ioffptr, const char *boundary, size_t blen, enum PP_State next_state, enum PP_State next_dash_state) { char *buf = (char *) &pp[1]; size_t newline; const char *r; /* all data in buf until the boundary (\r\n--+boundary) is part of the value */ newline = 0; while (1) { while (newline + 4 < pp->buffer_pos) { r = memchr (&buf[newline], '\r', pp->buffer_pos - newline - 4); if (NULL == r) { newline = pp->buffer_pos - 4; break; } newline = (size_t) (r - buf); if (0 == memcmp ("\r\n--", &buf[newline], 4)) break; newline++; } if (newline + blen + 4 <= pp->buffer_pos) { /* can check boundary */ if (0 != memcmp (&buf[newline + 4], boundary, blen)) { /* no boundary, "\r\n--" is part of content, skip */ newline += 4; continue; } else { /* boundary found, process until newline then skip boundary and go back to init */ pp->skip_rn = RN_Dash; pp->state = next_state; pp->dash_state = next_dash_state; (*ioffptr) += blen + 4; /* skip boundary as well */ buf[newline] = '\0'; break; } } else { /* cannot check for boundary, process content that we have and check again later; except, if we have no content, abort (out of memory) */ if ( (0 == newline) && (pp->buffer_pos == pp->buffer_size) ) { pp->state = PP_Error; return MHD_NO; } break; } } /* newline is either at beginning of boundary or at least at the last character that we are sure is not part of the boundary */ if ( ( (pp->must_ikvi) || (0 != newline) ) && (MHD_NO == pp->ikvi (pp->cls, MHD_POSTDATA_KIND, pp->content_name, pp->content_filename, pp->content_type, pp->content_transfer_encoding, buf, pp->value_offset, newline)) ) { pp->state = PP_Error; return MHD_NO; } pp->must_ikvi = false; pp->value_offset += newline; (*ioffptr) += newline; return MHD_YES; } /** * * @param pp post processor context */ static void free_unmarked (struct MHD_PostProcessor *pp) { if ( (NULL != pp->content_name) && (0 == (pp->have & NE_content_name)) ) { free (pp->content_name); pp->content_name = NULL; } if ( (NULL != pp->content_type) && (0 == (pp->have & NE_content_type)) ) { free (pp->content_type); pp->content_type = NULL; } if ( (NULL != pp->content_filename) && (0 == (pp->have & NE_content_filename)) ) { free (pp->content_filename); pp->content_filename = NULL; } if ( (NULL != pp->content_transfer_encoding) && (0 == (pp->have & NE_content_transfer_encoding)) ) { free (pp->content_transfer_encoding); pp->content_transfer_encoding = NULL; } } /** * Decode multipart POST data. * * @param pp post processor context * @param post_data data to decode * @param post_data_len number of bytes in @a post_data * @return #MHD_NO on error, */ static enum MHD_Result post_process_multipart (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { char *buf; size_t max; size_t ioff; size_t poff; int state_changed; buf = (char *) &pp[1]; ioff = 0; poff = 0; state_changed = 1; while ( (poff < post_data_len) || ( (pp->buffer_pos > 0) && (0 != state_changed) ) ) { /* first, move as much input data as possible to our internal buffer */ max = pp->buffer_size - pp->buffer_pos; if (max > post_data_len - poff) max = post_data_len - poff; memcpy (&buf[pp->buffer_pos], &post_data[poff], max); poff += max; pp->buffer_pos += max; if ( (0 == max) && (0 == state_changed) && (poff < post_data_len) ) { pp->state = PP_Error; return MHD_NO; /* out of memory */ } state_changed = 0; /* first state machine for '\r'-'\n' and '--' handling */ switch (pp->skip_rn) { case RN_Inactive: break; case RN_OptN: if (buf[0] == '\n') { ioff++; pp->skip_rn = RN_Inactive; goto AGAIN; } /* fall-through! */ case RN_Dash: if (buf[0] == '-') { ioff++; pp->skip_rn = RN_Dash2; goto AGAIN; } pp->skip_rn = RN_Full; /* fall-through! */ case RN_Full: if (buf[0] == '\r') { if ( (pp->buffer_pos > 1) && ('\n' == buf[1]) ) { pp->skip_rn = RN_Inactive; ioff += 2; } else { pp->skip_rn = RN_OptN; ioff++; } goto AGAIN; } if (buf[0] == '\n') { ioff++; pp->skip_rn = RN_Inactive; goto AGAIN; } pp->skip_rn = RN_Inactive; pp->state = PP_Error; return MHD_NO; /* no '\r\n' */ case RN_Dash2: if (buf[0] == '-') { ioff++; pp->skip_rn = RN_Full; pp->state = pp->dash_state; goto AGAIN; } pp->state = PP_Error; break; } /* main state engine */ switch (pp->state) { case PP_Error: return MHD_NO; case PP_Done: /* did not expect to receive more data */ pp->state = PP_Error; return MHD_NO; case PP_Init: /** * Per RFC2046 5.1.1 NOTE TO IMPLEMENTORS, consume anything * prior to the first multipart boundary: * * > There appears to be room for additional information prior * > to the first boundary delimiter line and following the * > final boundary delimiter line. These areas should * > generally be left blank, and implementations must ignore * > anything that appears before the first boundary delimiter * > line or after the last one. */ (void) find_boundary (pp, pp->boundary, pp->blen, &ioff, PP_ProcessEntryHeaders, PP_Done); break; case PP_NextBoundary: if (MHD_NO == find_boundary (pp, pp->boundary, pp->blen, &ioff, PP_ProcessEntryHeaders, PP_Done)) { if (pp->state == PP_Error) return MHD_NO; goto END; } break; case PP_ProcessEntryHeaders: pp->must_ikvi = true; if (MHD_NO == process_multipart_headers (pp, &ioff, PP_PerformCheckMultipart)) { if (pp->state == PP_Error) return MHD_NO; else goto END; } state_changed = 1; break; case PP_PerformCheckMultipart: if ( (NULL != pp->content_type) && (MHD_str_equal_caseless_n_ (pp->content_type, "multipart/mixed", MHD_STATICSTR_LEN_ ("multipart/mixed")))) { pp->nested_boundary = strstr (pp->content_type, "boundary="); if (NULL == pp->nested_boundary) { pp->state = PP_Error; return MHD_NO; } pp->nested_boundary = strdup (&pp->nested_boundary[MHD_STATICSTR_LEN_ ("boundary=")]); if (NULL == pp->nested_boundary) { /* out of memory */ pp->state = PP_Error; return MHD_NO; } /* free old content type, we will need that field for the content type of the nested elements */ free (pp->content_type); pp->content_type = NULL; pp->nlen = strlen (pp->nested_boundary); pp->state = PP_Nested_Init; state_changed = 1; break; } pp->state = PP_ProcessValueToBoundary; pp->value_offset = 0; state_changed = 1; break; case PP_ProcessValueToBoundary: if (MHD_NO == process_value_to_boundary (pp, &ioff, pp->boundary, pp->blen, PP_PerformCleanup, PP_Done)) { if (pp->state == PP_Error) return MHD_NO; break; } break; case PP_PerformCleanup: /* clean up state of one multipart form-data element! */ pp->have = NE_none; free_unmarked (pp); if (NULL != pp->nested_boundary) { free (pp->nested_boundary); pp->nested_boundary = NULL; } pp->state = PP_ProcessEntryHeaders; state_changed = 1; break; case PP_Nested_Init: if (NULL == pp->nested_boundary) { pp->state = PP_Error; return MHD_NO; } if (MHD_NO == find_boundary (pp, pp->nested_boundary, pp->nlen, &ioff, PP_Nested_PerformMarking, PP_NextBoundary /* or PP_Error? */)) { if (pp->state == PP_Error) return MHD_NO; goto END; } break; case PP_Nested_PerformMarking: /* remember what headers were given globally */ pp->have = NE_none; if (NULL != pp->content_name) pp->have |= NE_content_name; if (NULL != pp->content_type) pp->have |= NE_content_type; if (NULL != pp->content_filename) pp->have |= NE_content_filename; if (NULL != pp->content_transfer_encoding) pp->have |= NE_content_transfer_encoding; pp->state = PP_Nested_ProcessEntryHeaders; state_changed = 1; break; case PP_Nested_ProcessEntryHeaders: pp->value_offset = 0; if (MHD_NO == process_multipart_headers (pp, &ioff, PP_Nested_ProcessValueToBoundary)) { if (pp->state == PP_Error) return MHD_NO; else goto END; } state_changed = 1; break; case PP_Nested_ProcessValueToBoundary: if (MHD_NO == process_value_to_boundary (pp, &ioff, pp->nested_boundary, pp->nlen, PP_Nested_PerformCleanup, PP_NextBoundary)) { if (pp->state == PP_Error) return MHD_NO; break; } break; case PP_Nested_PerformCleanup: free_unmarked (pp); pp->state = PP_Nested_ProcessEntryHeaders; state_changed = 1; break; case PP_ProcessKey: case PP_ProcessValue: case PP_Callback: default: MHD_PANIC (_ ("internal error.\n")); /* should never happen! */ } AGAIN: if (ioff > 0) { memmove (buf, &buf[ioff], pp->buffer_pos - ioff); pp->buffer_pos -= ioff; ioff = 0; state_changed = 1; } } END: if (0 != ioff) { memmove (buf, &buf[ioff], pp->buffer_pos - ioff); pp->buffer_pos -= ioff; } if (poff < post_data_len) { pp->state = PP_Error; return MHD_NO; /* serious error */ } return MHD_YES; } _MHD_EXTERN enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { if (0 == post_data_len) return MHD_YES; if (NULL == pp) return MHD_NO; if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, pp->encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_FORM_URLENCODED))) return post_process_urlencoded (pp, post_data, post_data_len); if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, pp->encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))) return post_process_multipart (pp, post_data, post_data_len); /* this should never be reached */ return MHD_NO; } _MHD_EXTERN enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp) { enum MHD_Result ret; if (NULL == pp) return MHD_YES; if (PP_ProcessValue == pp->state) { /* key without terminated value left at the end of the buffer; fake receiving a termination character to ensure it is also processed */ post_process_urlencoded (pp, "\n", 1); } /* These internal strings need cleaning up since the post-processing may have been interrupted at any stage */ if ( (pp->xbuf_pos > 0) || ( (pp->state != PP_Done) && (pp->state != PP_Init) ) ) ret = MHD_NO; else ret = MHD_YES; pp->have = NE_none; free_unmarked (pp); if (NULL != pp->nested_boundary) free (pp->nested_boundary); free (pp); return ret; } /* end of postprocessor.c */ libmicrohttpd-1.0.2/src/microhttpd/mhd_threads.c0000644000175000017500000002751115035214301016671 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_threads.c * @brief Implementation for thread functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_threads.h" #ifdef MHD_USE_W32_THREADS #include "mhd_limits.h" #include #endif #ifdef MHD_USE_THREAD_NAME_ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #ifdef HAVE_PTHREAD_NP_H #include #endif /* HAVE_PTHREAD_NP_H */ #endif /* MHD_USE_THREAD_NAME_ */ #include #include "mhd_assert.h" #ifndef MHD_USE_THREAD_NAME_ #define MHD_set_thread_name_(t, n) (void) #define MHD_set_cur_thread_name_(n) (void) #else /* MHD_USE_THREAD_NAME_ */ #if defined(MHD_USE_POSIX_THREADS) #if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) # define MHD_USE_THREAD_ATTR_SETNAME 1 #endif /* HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD || \ HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */ #if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \ defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) \ || defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) /** * Set thread name * * @param thread_id ID of thread * @param thread_name name to set * @return non-zero on success, zero otherwise */ static int MHD_set_thread_name_ (const MHD_thread_ID_native_ thread_id, const char *thread_name) { if (NULL == thread_name) return 0; #if defined(HAVE_PTHREAD_SETNAME_NP_GNU) return ! pthread_setname_np (thread_id, thread_name); #elif defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) /* FreeBSD and OpenBSD use different function name and void return type */ pthread_set_name_np (thread_id, thread_name); return ! 0; #elif defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) /* NetBSD use 3 arguments: second argument is string in printf-like format, * third argument is a single argument for printf(); * OSF1 use 3 arguments too, but last one always must be zero (NULL). * MHD doesn't use '%' in thread names, so both form are used in same way. */ return ! pthread_setname_np (thread_id, thread_name, 0); #endif /* HAVE_PTHREAD_SETNAME_NP_NETBSD */ } #ifndef __QNXNTO__ /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (pthread_self (),(n)) #else /* __QNXNTO__ */ /* Special case for QNX Neutrino - using zero for thread ID sets name faster. */ #define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (0,(n)) #endif /* __QNXNTO__ */ #elif defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) (! (pthread_setname_np ((n)))) #endif /* HAVE_PTHREAD_SETNAME_NP_DARWIN */ #elif defined(MHD_USE_W32_THREADS) #ifndef _MSC_FULL_VER /* Thread name available only for VC-compiler */ #else /* _MSC_FULL_VER */ /** * Set thread name * * @param thread_id ID of thread, -1 for current thread * @param thread_name name to set * @return non-zero on success, zero otherwise */ static int MHD_set_thread_name_ (const MHD_thread_ID_native_ thread_id, const char *thread_name) { static const DWORD VC_SETNAME_EXC = 0x406D1388; #pragma pack(push,8) struct thread_info_struct { DWORD type; /* Must be 0x1000. */ LPCSTR name; /* Pointer to name (in user address space). */ DWORD ID; /* Thread ID (-1 = caller thread). */ DWORD flags; /* Reserved for future use, must be zero. */ } thread_info; #pragma pack(pop) if (NULL == thread_name) return 0; thread_info.type = 0x1000; thread_info.name = thread_name; thread_info.ID = thread_id; thread_info.flags = 0; __try { /* This exception is intercepted by debugger */ RaiseException (VC_SETNAME_EXC, 0, sizeof (thread_info) / sizeof(ULONG_PTR), (ULONG_PTR *) &thread_info); } __except (EXCEPTION_EXECUTE_HANDLER) {} return ! 0; } /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) \ MHD_set_thread_name_ ((MHD_thread_ID_native_) -1,(n)) #endif /* _MSC_FULL_VER */ #endif /* MHD_USE_W32_THREADS */ #endif /* MHD_USE_THREAD_NAME_ */ /** * Create a thread and set the attributes according to our options. * * If thread is created, thread handle must be freed by MHD_join_thread_(). * * @param handle_id handle to initialise * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_thread_ (MHD_thread_handle_ID_ *handle_id, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg) { #if defined(MHD_USE_POSIX_THREADS) int res; #if defined(MHD_thread_handle_ID_get_native_handle_ptr_) pthread_t *const new_tid_ptr = MHD_thread_handle_ID_get_native_handle_ptr_ (handle_id); #else /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ pthread_t new_tid; pthread_t *const new_tid_ptr = &new_tid; #endif /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (*handle_id)); if (0 != stack_size) { pthread_attr_t attr; res = pthread_attr_init (&attr); if (0 == res) { res = pthread_attr_setstacksize (&attr, stack_size); if (0 == res) res = pthread_create (new_tid_ptr, &attr, start_routine, arg); pthread_attr_destroy (&attr); } } else res = pthread_create (new_tid_ptr, NULL, start_routine, arg); if (0 != res) { errno = res; MHD_thread_handle_ID_set_invalid_ (handle_id); } #if ! defined(MHD_thread_handle_ID_get_native_handle_ptr_) else MHD_thread_handle_ID_set_native_handle_ (handle_id, new_tid); #endif /* ! MHD_thread_handle_ID_set_current_thread_ID_ */ return ! res; #elif defined(MHD_USE_W32_THREADS) uintptr_t thr_handle; #if SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (*handle_id)); if (stack_size > UINT_MAX) { errno = EINVAL; return 0; } #endif /* SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT */ thr_handle = (uintptr_t) _beginthreadex (NULL, (unsigned int) stack_size, start_routine, arg, 0, NULL); if ((MHD_thread_handle_native_) 0 == (MHD_thread_handle_native_) thr_handle) return 0; MHD_thread_handle_ID_set_native_handle_ (handle_id, \ (MHD_thread_handle_native_) \ thr_handle); return ! 0; #endif } #ifdef MHD_USE_THREAD_NAME_ #ifndef MHD_USE_THREAD_ATTR_SETNAME struct MHD_named_helper_param_ { /** * Real thread start routine */ MHD_THREAD_START_ROUTINE_ start_routine; /** * Argument for thread start routine */ void *arg; /** * Name for thread */ const char *name; }; static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ named_thread_starter (void *data) { struct MHD_named_helper_param_ *const param = (struct MHD_named_helper_param_ *) data; void *arg; MHD_THREAD_START_ROUTINE_ thr_func; if (NULL == data) return (MHD_THRD_RTRN_TYPE_) 0; MHD_set_cur_thread_name_ (param->name); arg = param->arg; thr_func = param->start_routine; free (data); return thr_func (arg); } #endif /* ! MHD_USE_THREAD_ATTR_SETNAME */ /** * Create a named thread and set the attributes according to our options. * * @param handle_id handle to initialise * @param thread_name name for new thread * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_named_thread_ (MHD_thread_handle_ID_ *handle_id, const char *thread_name, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg) { #if defined(MHD_USE_THREAD_ATTR_SETNAME) int res; pthread_attr_t attr; #if defined(MHD_thread_handle_ID_get_native_handle_ptr_) pthread_t *const new_tid_ptr = MHD_thread_handle_ID_get_native_handle_ptr_ (handle_id); #else /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ pthread_t new_tid; pthread_t *const new_tid_ptr = &new_tid; #endif /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ res = pthread_attr_init (&attr); if (0 == res) { #if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) /* NetBSD uses 3 arguments: second argument is string in printf-like format, * third argument is single argument for printf; * OSF1 uses 3 arguments too, but last one always must be zero (NULL). * MHD doesn't use '%' in thread names, so both forms are used in same way. */ res = pthread_attr_setname_np (&attr, thread_name, 0); #elif defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) res = pthread_attr_setname_np (&attr, thread_name); #else #error No pthread_attr_setname_np() function. #endif if ((res == 0) && (0 != stack_size) ) res = pthread_attr_setstacksize (&attr, stack_size); if (0 == res) res = pthread_create (new_tid_ptr, &attr, start_routine, arg); pthread_attr_destroy (&attr); } if (0 != res) { errno = res; MHD_thread_handle_ID_set_invalid_ (handle_id); } #if ! defined(MHD_thread_handle_ID_get_native_handle_ptr_) else MHD_thread_handle_ID_set_native_handle_ (handle_id, new_tid); #endif /* ! MHD_thread_handle_ID_set_current_thread_ID_ */ return ! res; #else /* ! MHD_USE_THREAD_ATTR_SETNAME */ struct MHD_named_helper_param_ *param; if (NULL == thread_name) { errno = EINVAL; return 0; } param = malloc (sizeof (struct MHD_named_helper_param_)); if (NULL == param) return 0; param->start_routine = start_routine; param->arg = arg; param->name = thread_name; /* Set thread name in thread itself to avoid problems with * threads which terminated before name is set in other thread. */ if (! MHD_create_thread_ (handle_id, stack_size, &named_thread_starter, (void *) param)) { int err_num; err_num = errno; free (param); errno = err_num; return 0; } return ! 0; #endif /* ! MHD_USE_THREAD_ATTR_SETNAME */ } #endif /* MHD_USE_THREAD_NAME_ */ libmicrohttpd-1.0.2/src/microhttpd/mhd_sockets.c0000644000175000017500000004174014760713574016736 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2024 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_sockets.c * @brief Implementation for sockets functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_sockets.h" #ifdef MHD_WINSOCK_SOCKETS /** * Return pointer to string description of specified WinSock error * @param err the WinSock error code. * @return pointer to string description of specified WinSock error. */ const char * MHD_W32_strerror_winsock_ (int err) { switch (err) { case 0: return "No error"; case WSA_INVALID_HANDLE: return "Specified event object handle is invalid"; case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available"; case WSA_INVALID_PARAMETER: return "One or more parameters are invalid"; case WSA_OPERATION_ABORTED: return "Overlapped operation aborted"; case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state"; case WSA_IO_PENDING: return "Overlapped operations will complete later"; case WSAEINTR: return "Interrupted function call"; case WSAEBADF: return "File handle is not valid"; case WSAEACCES: return "Permission denied"; case WSAEFAULT: return "Bad address"; case WSAEINVAL: return "Invalid argument"; case WSAEMFILE: return "Too many open files"; case WSAEWOULDBLOCK: return "Resource temporarily unavailable"; case WSAEINPROGRESS: return "Operation now in progress"; case WSAEALREADY: return "Operation already in progress"; case WSAENOTSOCK: return "Socket operation on nonsocket"; case WSAEDESTADDRREQ: return "Destination address required"; case WSAEMSGSIZE: return "Message too long"; case WSAEPROTOTYPE: return "Protocol wrong type for socket"; case WSAENOPROTOOPT: return "Bad protocol option"; case WSAEPROTONOSUPPORT: return "Protocol not supported"; case WSAESOCKTNOSUPPORT: return "Socket type not supported"; case WSAEOPNOTSUPP: return "Operation not supported"; case WSAEPFNOSUPPORT: return "Protocol family not supported"; case WSAEAFNOSUPPORT: return "Address family not supported by protocol family"; case WSAEADDRINUSE: return "Address already in use"; case WSAEADDRNOTAVAIL: return "Cannot assign requested address"; case WSAENETDOWN: return "Network is down"; case WSAENETUNREACH: return "Network is unreachable"; case WSAENETRESET: return "Network dropped connection on reset"; case WSAECONNABORTED: return "Software caused connection abort"; case WSAECONNRESET: return "Connection reset by peer"; case WSAENOBUFS: return "No buffer space available"; case WSAEISCONN: return "Socket is already connected"; case WSAENOTCONN: return "Socket is not connected"; case WSAESHUTDOWN: return "Cannot send after socket shutdown"; case WSAETOOMANYREFS: return "Too many references"; case WSAETIMEDOUT: return "Connection timed out"; case WSAECONNREFUSED: return "Connection refused"; case WSAELOOP: return "Cannot translate name"; case WSAENAMETOOLONG: return "Name too long"; case WSAEHOSTDOWN: return "Host is down"; case WSAEHOSTUNREACH: return "No route to host"; case WSAENOTEMPTY: return "Directory not empty"; case WSAEPROCLIM: return "Too many processes"; case WSAEUSERS: return "User quota exceeded"; case WSAEDQUOT: return "Disk quota exceeded"; case WSAESTALE: return "Stale file handle reference"; case WSAEREMOTE: return "Item is remote"; case WSASYSNOTREADY: return "Network subsystem is unavailable"; case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range"; case WSANOTINITIALISED: return "Successful WSAStartup not yet performed"; case WSAEDISCON: return "Graceful shutdown in progress"; case WSAENOMORE: return "No more results"; case WSAECANCELLED: return "Call has been canceled"; case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid"; case WSAEINVALIDPROVIDER: return "Service provider is invalid"; case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize"; case WSASYSCALLFAILURE: return "System call failure"; case WSASERVICE_NOT_FOUND: return "Service not found"; case WSATYPE_NOT_FOUND: return "Class type not found"; case WSA_E_NO_MORE: return "No more results"; case WSA_E_CANCELLED: return "Call was canceled"; case WSAEREFUSED: return "Database query was refused"; case WSAHOST_NOT_FOUND: return "Host not found"; case WSATRY_AGAIN: return "Nonauthoritative host not found"; case WSANO_RECOVERY: return "This is a nonrecoverable error"; case WSANO_DATA: return "Valid name, no data record of requested type"; case WSA_QOS_RECEIVERS: return "QoS receivers"; case WSA_QOS_SENDERS: return "QoS senders"; case WSA_QOS_NO_SENDERS: return "No QoS senders"; case WSA_QOS_NO_RECEIVERS: return "QoS no receivers"; case WSA_QOS_REQUEST_CONFIRMED: return "QoS request confirmed"; case WSA_QOS_ADMISSION_FAILURE: return "QoS admission error"; case WSA_QOS_POLICY_FAILURE: return "QoS policy failure"; case WSA_QOS_BAD_STYLE: return "QoS bad style"; case WSA_QOS_BAD_OBJECT: return "QoS bad object"; case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QoS traffic control error"; case WSA_QOS_GENERIC_ERROR: return "QoS generic error"; case WSA_QOS_ESERVICETYPE: return "QoS service type error"; case WSA_QOS_EFLOWSPEC: return "QoS flowspec error"; case WSA_QOS_EPROVSPECBUF: return "Invalid QoS provider buffer"; case WSA_QOS_EFILTERSTYLE: return "Invalid QoS filter style"; case WSA_QOS_EFILTERTYPE: return "Invalid QoS filter type"; case WSA_QOS_EFILTERCOUNT: return "Incorrect QoS filter count"; case WSA_QOS_EOBJLENGTH: return "Invalid QoS object length"; case WSA_QOS_EFLOWCOUNT: return "Incorrect QoS flow count"; case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QoS object"; case WSA_QOS_EPOLICYOBJ: return "Invalid QoS policy object"; case WSA_QOS_EFLOWDESC: return "Invalid QoS flow descriptor"; case WSA_QOS_EPSFLOWSPEC: return "Invalid QoS provider-specific flowspec"; case WSA_QOS_EPSFILTERSPEC: return "Invalid QoS provider-specific filterspec"; case WSA_QOS_ESDMODEOBJ: return "Invalid QoS shape discard mode object"; case WSA_QOS_ESHAPERATEOBJ: return "Invalid QoS shaping rate object"; case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QoS element type"; } return "Unknown winsock error"; } /** * Create pair of mutually connected TCP/IP sockets on loopback address * @param sockets_pair array to receive resulted sockets * @param non_blk if set to non-zero value, sockets created in non-blocking mode * otherwise sockets will be in blocking mode * @return non-zero if succeeded, zero otherwise */ int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk) { int i; if (! sockets_pair) { WSASetLastError (WSAEFAULT); return 0; } #define PAIRMAXTRYIES 800 for (i = 0; i < PAIRMAXTRYIES; i++) { struct sockaddr_in listen_addr; SOCKET listen_s; static const int c_addinlen = sizeof(struct sockaddr_in); /* help compiler to optimize */ int addr_len = c_addinlen; unsigned long on_val = 1; unsigned long off_val = 0; listen_s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == listen_s) break; /* can't create even single socket */ listen_addr.sin_family = AF_INET; listen_addr.sin_port = 0; /* same as htons(0) */ listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if ( ((0 == bind (listen_s, (struct sockaddr *) &listen_addr, c_addinlen)) && (0 == listen (listen_s, 1) ) && (0 == getsockname (listen_s, (struct sockaddr *) &listen_addr, &addr_len))) ) { SOCKET client_s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in accepted_from_addr; struct sockaddr_in client_addr; SOCKET server_s; if (INVALID_SOCKET == client_s) { /* try again */ closesocket (listen_s); continue; } if ( (0 != ioctlsocket (client_s, (int) FIONBIO, &on_val)) || ( (0 != connect (client_s, (struct sockaddr *) &listen_addr, c_addinlen)) && (WSAGetLastError () != WSAEWOULDBLOCK)) ) { /* try again */ closesocket (listen_s); closesocket (client_s); continue; } addr_len = c_addinlen; server_s = accept (listen_s, (struct sockaddr *) &accepted_from_addr, &addr_len); if (INVALID_SOCKET == server_s) { /* try again */ closesocket (listen_s); closesocket (client_s); continue; } addr_len = c_addinlen; if ( (0 == getsockname (client_s, (struct sockaddr *) &client_addr, &addr_len)) && (accepted_from_addr.sin_port == client_addr.sin_port) && (accepted_from_addr.sin_addr.s_addr == client_addr.sin_addr.s_addr) && (accepted_from_addr.sin_family == client_addr.sin_family) && ( (0 != non_blk) ? (0 == ioctlsocket (server_s, (int) FIONBIO, &on_val)) : (0 == ioctlsocket (client_s, (int) FIONBIO, &off_val)) ) && (0 == setsockopt (server_s, IPPROTO_TCP, TCP_NODELAY, (const void *) (&on_val), sizeof (on_val))) && (0 == setsockopt (client_s, IPPROTO_TCP, TCP_NODELAY, (const void *) (&on_val), sizeof (on_val))) ) { closesocket (listen_s); sockets_pair[0] = server_s; sockets_pair[1] = client_s; return ! 0; } closesocket (server_s); closesocket (client_s); } closesocket (listen_s); } sockets_pair[0] = INVALID_SOCKET; sockets_pair[1] = INVALID_SOCKET; WSASetLastError (WSAECONNREFUSED); return 0; } #endif /* MHD_WINSOCK_SOCKETS */ /** * Add @a fd to the @a set. If @a fd is * greater than @a max_fd, set @a max_fd to @a fd. * * @param fd file descriptor to add to the @a set * @param set set to modify * @param max_fd maximum value to potentially update * @param fd_setsize value of FD_SETSIZE * @return non-zero if succeeded, zero otherwise */ int MHD_add_to_fd_set_ (MHD_socket fd, fd_set *set, MHD_socket *max_fd, int fd_setsize) { if ( (NULL == set) || (MHD_INVALID_SOCKET == fd) ) return 0; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (! MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (fd, set, fd_setsize)) return 0; MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_ (fd, set, fd_setsize); if ( (NULL != max_fd) && ( (fd > *max_fd) || (MHD_INVALID_SOCKET == *max_fd) ) ) *max_fd = fd; return ! 0; } /** * Change socket options to be non-blocking. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_socket_nonblocking_ (MHD_socket sock) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (sock, F_GETFL); if (-1 == flags) return 0; if ( ((flags | O_NONBLOCK) != flags) && (0 != fcntl (sock, F_SETFL, flags | O_NONBLOCK)) ) return 0; #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (sock, (int) FIONBIO, &flags)) return 0; #endif /* MHD_WINSOCK_SOCKETS */ return ! 0; } /** * Change socket options to be non-inheritable. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise * @warning Does not set socket error on W32. */ int MHD_socket_noninheritable_ (MHD_socket sock) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (sock, F_GETFD); if (-1 == flags) return 0; if ( ((flags | FD_CLOEXEC) != flags) && (0 != fcntl (sock, F_SETFD, flags | FD_CLOEXEC)) ) return 0; #elif defined(MHD_WINSOCK_SOCKETS) if (! SetHandleInformation ((HANDLE) sock, HANDLE_FLAG_INHERIT, 0)) return 0; #endif /* MHD_WINSOCK_SOCKETS */ return ! 0; } /** * Disable Nagle's algorithm on @a sock. This is what we do by default for * all TCP sockets in MHD, unless the platform does not support the MSG_MORE * or MSG_CORK or MSG_NOPUSH options. * * @param sock socket to manipulate * @param on value to use * @return 0 on success */ int MHD_socket_set_nodelay_ (MHD_socket sock, bool on) { #ifdef TCP_NODELAY { const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; /* Disable Nagle's algorithm for normal buffering */ return setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (const void *) ((on) ? &on_val : &off_val), sizeof (on_val)); } #else (void) sock; return 0; #endif /* TCP_NODELAY */ } /** * Create a listen socket, with noninheritable flag if possible. * * @param pf protocol family to use * @return created socket or MHD_INVALID_SOCKET in case of errors */ MHD_socket MHD_socket_create_listen_ (int pf) { MHD_socket fd; int cloexec_set; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) int nosigpipe_set; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #if defined(MHD_POSIX_SOCKETS) && (defined(SOCK_CLOEXEC) || \ defined(SOCK_NOSIGPIPE) ) fd = socket (pf, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NOSIGPIPE_OR_ZERO, 0); cloexec_set = (SOCK_CLOEXEC_OR_ZERO != 0); #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = (SOCK_NOSIGPIPE_OR_ZERO != 0); #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT) fd = WSASocketW (pf, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); cloexec_set = ! 0; #else /* No special socket init function / flags */ fd = MHD_INVALID_SOCKET; cloexec_set = 0; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = 0; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #endif /* No special socket init function / flags */ if (MHD_INVALID_SOCKET == fd) { fd = socket (pf, SOCK_STREAM, 0); cloexec_set = 0; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = 0; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ } if (MHD_INVALID_SOCKET == fd) return MHD_INVALID_SOCKET; #if defined(MHD_socket_nosignal_) if ( (! nosigpipe_set) && (0 == MHD_socket_nosignal_ (fd)) && (0 == MSG_NOSIGNAL_OR_ZERO) ) { /* SIGPIPE disable is possible on this platform * (so application expect that it will be disabled), * but failed to be disabled here and it is not * possible to disable SIGPIPE by MSG_NOSIGNAL. */ const int err = MHD_socket_get_error_ (); (void) MHD_socket_close_ (fd); MHD_socket_fset_error_ (err); return MHD_INVALID_SOCKET; } #endif /* defined(MHD_socket_nosignal_) */ if (! cloexec_set) (void) MHD_socket_noninheritable_ (fd); return fd; } libmicrohttpd-1.0.2/src/microhttpd/connection_https.c0000644000175000017500000001542614760713574020016 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2008, 2010 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection_https.c * @brief Methods for managing SSL/TLS connections. This file is only * compiled if ENABLE_HTTPS is set. * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "connection.h" #include "connection_https.h" #include "memorypool.h" #include "response.h" #include "mhd_mono_clock.h" #include #include "mhd_send.h" /** * Callback for receiving data from the socket. * * @param connection the MHD_Connection structure * @param other where to write received data to * @param i maximum size of other (in bytes) * @return positive value for number of bytes actually received or * negative value for error number MHD_ERR_xxx_ */ static ssize_t recv_tls_adapter (struct MHD_Connection *connection, void *other, size_t i) { ssize_t res; if (i > SSIZE_MAX) i = SSIZE_MAX; res = gnutls_record_recv (connection->tls_session, other, i); if ( (GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res) ) { #ifdef EPOLL_SUPPORT if (GNUTLS_E_AGAIN == res) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* Any network errors means that buffer is empty. */ connection->tls_read_ready = false; return MHD_ERR_AGAIN_; } if (res < 0) { connection->tls_read_ready = false; if ( (GNUTLS_E_DECRYPTION_FAILED == res) || (GNUTLS_E_INVALID_SESSION == res) || (GNUTLS_E_DECOMPRESSION_FAILED == res) || (GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER == res) || (GNUTLS_E_UNSUPPORTED_VERSION_PACKET == res) || (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res) || (GNUTLS_E_UNEXPECTED_PACKET == res) || (GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET == res) || (GNUTLS_E_EXPIRED == res) || (GNUTLS_E_REHANDSHAKE == res) ) return MHD_ERR_TLS_; if ( (GNUTLS_E_PULL_ERROR == res) || (GNUTLS_E_INTERNAL_ERROR == res) || (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == res) || (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == res) ) return MHD_ERR_PIPE_; #if defined(GNUTLS_E_PREMATURE_TERMINATION) if (GNUTLS_E_PREMATURE_TERMINATION == res) return MHD_ERR_CONNRESET_; #elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH) if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res) return MHD_ERR_CONNRESET_; #endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */ if (GNUTLS_E_MEMORY_ERROR == res) return MHD_ERR_NOMEM_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT /* Unlike non-TLS connections, do not reset "read-ready" if * received amount smaller than provided amount, as TLS * connections may receive data by fixed-size chunks. */ #endif /* EPOLL_SUPPORT */ /* Check whether TLS buffers still have some unread data. */ connection->tls_read_ready = ( ((size_t) res == i) && (0 != gnutls_record_check_pending (connection->tls_session)) ); return res; } /** * Give gnuTLS chance to work on the TLS handshake. * * @param connection connection to handshake on * @return true if the handshake has completed successfully * and we should start to read/write data, * false is handshake in progress or in case * of error */ bool MHD_run_tls_handshake_ (struct MHD_Connection *connection) { int ret; if ((MHD_TLS_CONN_INIT == connection->tls_state) || (MHD_TLS_CONN_HANDSHAKING == connection->tls_state)) { #if 0 /* According to real-live testing, Nagel's Algorithm is not blocking * partial packets on just connected sockets on modern OSes. As TLS setup * is performed as the fist action upon socket connection, the next * optimisation typically is not required. If any specific OS will * require this optimization, it could be enabled by allowing the next * lines for this specific OS. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); #endif ret = gnutls_handshake (connection->tls_session); if (ret == GNUTLS_E_SUCCESS) { /* set connection TLS state to enable HTTP processing */ connection->tls_state = MHD_TLS_CONN_CONNECTED; MHD_update_last_activity_ (connection); return true; } if ( (GNUTLS_E_AGAIN == ret) || (GNUTLS_E_INTERRUPTED == ret) ) { connection->tls_state = MHD_TLS_CONN_HANDSHAKING; /* handshake not done */ return false; } /* handshake failed */ connection->tls_state = MHD_TLS_CONN_TLS_FAILED; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Error: received handshake message out of context.\n")); #endif MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); return false; } return true; } /** * Set connection callback function to be used through out * the processing of this secure connection. * * @param connection which callbacks should be modified */ void MHD_set_https_callbacks (struct MHD_Connection *connection) { connection->recv_cls = &recv_tls_adapter; } /** * Initiate shutdown of TLS layer of connection. * * @param connection to use * @return true if succeed, false otherwise. */ bool MHD_tls_connection_shutdown (struct MHD_Connection *connection) { if (MHD_TLS_CONN_WR_CLOSED > connection->tls_state) { const int res = gnutls_bye (connection->tls_session, GNUTLS_SHUT_WR); if (GNUTLS_E_SUCCESS == res) { connection->tls_state = MHD_TLS_CONN_WR_CLOSED; return true; } if ((GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res)) { connection->tls_state = MHD_TLS_CONN_WR_CLOSING; return true; } else connection->tls_state = MHD_TLS_CONN_TLS_FAILED; } return false; } /* end of connection_https.c */ libmicrohttpd-1.0.2/src/microhttpd/sysfdsetsize.c0000644000175000017500000000450014760713574017163 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/sysfdsetsize.c * @brief Helper for obtaining FD_SETSIZE system default value * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #ifndef MHD_SYS_FD_SETSIZE_ #include "sysfdsetsize.h" #ifdef FD_SETSIZE /* FD_SETSIZE was defined before system headers. */ /* To get system value of FD_SETSIZE, undefine FD_SETSIZE here. */ #undef FD_SETSIZE #endif /* FD_SETSIZE */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #include #endif /* OS_VXWORKS */ #ifdef HAVE_SYS_SELECT_H #include #endif /* HAVE_SYS_SELECT_H */ #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_TIME_H #include #endif /* HAVE_SYS_TIME_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif /* _WIN32 && !__CYGWIN__ */ #ifndef FD_SETSIZE #error FD_SETSIZE must be defined in system headers #endif /* !FD_SETSIZE */ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ unsigned int get_system_fdsetsize_value (void) { return (unsigned int) FD_SETSIZE; } #endif /* ! MHD_SYS_FD_SETSIZE_ */ libmicrohttpd-1.0.2/src/microhttpd/basicauth.c0000644000175000017500000002424414760713574016376 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file basicauth.c * @brief Implements HTTP basic authentication methods * @author Amr Ali * @author Matthieu Speder * @author Karlson2k (Evgeny Grin) */ #include "basicauth.h" #include "gen_auth.h" #include "platform.h" #include "mhd_limits.h" #include "internal.h" #include "mhd_compat.h" #include "mhd_str.h" /** * Get the username and password from the Basic Authorisation header * sent by the client * * @param connection the MHD connection structure * @return NULL if no valid Basic Authentication header is present in * current request, or * pointer to structure with username and password, which must be * freed by #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_BasicAuthInfo * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection) { const struct MHD_RqBAuth *params; size_t decoded_max_len; struct MHD_BasicAuthInfo *ret; params = MHD_get_rq_bauth_params_ (connection); if (NULL == params) return NULL; if ((NULL == params->token68.str) || (0 == params->token68.len)) return NULL; decoded_max_len = MHD_base64_max_dec_size_ (params->token68.len); ret = (struct MHD_BasicAuthInfo *) malloc (sizeof(struct MHD_BasicAuthInfo) + decoded_max_len + 1); if (NULL != ret) { size_t decoded_len; char *decoded; decoded = (char *) (ret + 1); decoded_len = MHD_base64_to_bin_n (params->token68.str, params->token68.len, decoded, decoded_max_len); mhd_assert (decoded_max_len >= decoded_len); if (0 != decoded_len) { size_t username_len; char *colon; colon = memchr (decoded, ':', decoded_len); if (NULL != colon) { size_t password_pos; size_t password_len; username_len = (size_t) (colon - decoded); password_pos = username_len + 1; password_len = decoded_len - password_pos; ret->password = decoded + password_pos; ret->password[password_len] = 0; /* Zero-terminate the string */ ret->password_len = password_len; } else { username_len = decoded_len; ret->password = NULL; ret->password_len = 0; } ret->username = decoded; ret->username[username_len] = 0; /* Zero-terminate the string */ ret->username_len = username_len; return ret; /* Success exit point */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Error decoding Basic Authorization authentication.\n")); #endif /* HAVE_MESSAGES */ free (ret); } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Failed to allocate memory to process " \ "Basic Authorization authentication.\n")); } #endif /* HAVE_MESSAGES */ return NULL; /* Failure exit point */ } /** * Get the username and password from the basic authorization header sent by the client * * @param connection The MHD connection structure * @param[out] password a pointer for the password, free using #MHD_free(). * @return NULL if no username could be found, a pointer * to the username if found, free using #MHD_free(). * @deprecated use #MHD_basic_auth_get_username_password3() * @ingroup authentication */ _MHD_EXTERN char * MHD_basic_auth_get_username_password (struct MHD_Connection *connection, char **password) { struct MHD_BasicAuthInfo *info; info = MHD_basic_auth_get_username_password3 (connection); if (NULL == info) return NULL; /* For backward compatibility this function must return NULL if * no password is provided */ if (NULL != info->password) { char *username; username = malloc (info->username_len + 1); if (NULL != username) { memcpy (username, info->username, info->username_len + 1); mhd_assert (0 == username[info->username_len]); if (NULL != password) { *password = malloc (info->password_len + 1); if (NULL != *password) { memcpy (*password, info->password, info->password_len + 1); mhd_assert (0 == (*password)[info->password_len]); free (info); return username; /* Success exit point */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Failed to allocate memory.\n")); #endif /* HAVE_MESSAGES */ } else { free (info); return username; /* Success exit point */ } free (username); } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Failed to allocate memory.\n")); #endif /* HAVE_MESSAGES */ } free (info); if (NULL != password) *password = NULL; return NULL; /* Failure exit point */ } /** * Queues a response to request basic authentication from the client. * * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * See RFC 7617#section-2 for details. * * The @a response is modified by this function. The modified response object * can be used to respond subsequent requests by #MHD_queue_response() * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again * with MHD_queue_basic_auth_required_response3() function. The response could * be destroyed right after call of this function. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will * be added, indicating for client that UTF-8 encoding * is preferred * @param response the response object to modify and queue; the NULL * is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097704 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_required_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response) { static const char prefix[] = "Basic realm=\""; static const char suff_charset[] = "\", charset=\"UTF-8\""; static const size_t prefix_len = MHD_STATICSTR_LEN_ (prefix); static const size_t suff_simple_len = MHD_STATICSTR_LEN_ ("\""); static const size_t suff_charset_len = MHD_STATICSTR_LEN_ (suff_charset); enum MHD_Result ret; char *h_str; size_t h_maxlen; size_t suffix_len; size_t realm_len; size_t realm_quoted_len; size_t pos; if (NULL == response) return MHD_NO; suffix_len = (0 == prefer_utf8) ? suff_simple_len : suff_charset_len; realm_len = strlen (realm); h_maxlen = prefix_len + realm_len * 2 + suffix_len; h_str = (char *) malloc (h_maxlen + 1); if (NULL == h_str) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, "Failed to allocate memory for Basic Authentication header.\n"); #endif /* HAVE_MESSAGES */ return MHD_NO; } memcpy (h_str, prefix, prefix_len); pos = prefix_len; realm_quoted_len = MHD_str_quote (realm, realm_len, h_str + pos, h_maxlen - prefix_len - suffix_len); pos += realm_quoted_len; mhd_assert (pos + suffix_len <= h_maxlen); if (0 == prefer_utf8) { h_str[pos++] = '\"'; h_str[pos++] = 0; /* Zero terminate the result */ mhd_assert (pos <= h_maxlen + 1); } else { /* Copy with the final zero-termination */ mhd_assert (pos + suff_charset_len <= h_maxlen); memcpy (h_str + pos, suff_charset, suff_charset_len + 1); mhd_assert (0 == h_str[pos + suff_charset_len]); } ret = MHD_add_response_header (response, MHD_HTTP_HEADER_WWW_AUTHENTICATE, h_str); free (h_str); if (MHD_NO != ret) { ret = MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response); } else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to add Basic Authentication header.\n")); #endif /* HAVE_MESSAGES */ } return ret; } /** * Queues a response to request basic authentication from the client * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param response response object to modify and queue; the NULL is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_basic_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection, const char *realm, struct MHD_Response *response) { return MHD_queue_basic_auth_required_response3 (connection, realm, MHD_NO, response); } /* end of basicauth.c */ libmicrohttpd-1.0.2/src/microhttpd/test_client_put_stop.c0000644000175000017500000020767214760713574020715 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021-2024 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_client_put_stop.c * @brief Testcase for handling of clients aborts * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_SYSCTL #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SYSCTL_H #include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_SYSTM_H #include #endif /* HAVE_NETINET_IN_SYSTM_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #ifdef HAVE_NETINET_IP_ICMP_H #include #endif /* HAVE_NETINET_IP_ICMP_H */ #ifdef HAVE_NETINET_ICMP_VAR_H #include #endif /* HAVE_NETINET_ICMP_VAR_H */ #endif /* HAVE_SYSCTL */ #include #include "mhd_sockets.h" /* only macros used */ #include "test_helpers.h" #include "mhd_assert.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Time in ms to wait for final packets to be delivered */ #define FINAL_PACKETS_MS 20 #define EXPECTED_URI_BASE_PATH "/a" #define REQ_HOST "localhost" #define REQ_METHOD "PUT" #define REQ_BODY "Some content data." #define REQ_LINE_END "\r\n" /* Mandatory request headers */ #define REQ_HEADER_HOST_NAME "Host" #define REQ_HEADER_HOST_VALUE REQ_HOST #define REQ_HEADER_HOST \ REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END #define REQ_HEADER_UA_NAME "User-Agent" #define REQ_HEADER_UA_VALUE "dummyclient/0.9" #define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END /* Optional request headers */ #define REQ_HEADER_CT_NAME "Content-Type" #define REQ_HEADER_CT_VALUE "text/plain" #define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Global generic functions */ void _MHD_sleep (uint32_t ms); /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) externalErrorExit (); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else externalErrorExitDesc ("No sleep function available on this system"); #endif } /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int use_shutdown; /**< Use shutdown at client side */ static int use_close; /**< Use socket close at client side */ static int use_hard_close; /**< Use socket close with RST at client side */ static int use_stress_os; /**< Stress OS by RST before getting ACKs for sent packets */ static int by_step; /**< Send request byte-by-byte */ static int upl_chunked; /**< Use chunked encoding for request body */ static unsigned int rate_limiter; /**< Maximum number of checks per second */ static void test_global_init (void) { rate_limiter = 0; if (use_hard_close) { #ifdef HAVE_SYSCTLBYNAME if (1) { int blck_hl; size_t blck_hl_size = sizeof (blck_hl); if (0 == sysctlbyname ("net.inet.tcp.blackhole", &blck_hl, &blck_hl_size, NULL, 0)) { if (2 <= blck_hl) { fprintf (stderr, "'sysctl net.inet.tcp.blackhole = %d', test is " "unreliable with this system setting, skipping.\n", blck_hl); exit (77); } } else { if (ENOENT != errno) externalErrorExitDesc ("Cannot get 'net.inet.tcp.blackhole' value"); } } #endif #if defined(HAVE_SYSCTL) && defined(HAVE_DECL_CTL_NET) && \ defined(HAVE_DECL_PF_INET) && defined(HAVE_DECL_IPPROTO_ICMP) && \ defined(HAVE_DECL_ICMPCTL_ICMPLIM) /* Macros may have zero values */ #if HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \ HAVE_DECL_ICMPCTL_ICMPLIM if (1) { int mib[4]; int limit; size_t limit_size = sizeof(limit); mib[0] = CTL_NET; mib[1] = PF_INET; mib[2] = IPPROTO_ICMP; mib[3] = ICMPCTL_ICMPLIM; if (0 != sysctl (mib, 4, &limit, &limit_size, NULL, 0)) { if (ENOENT == errno) limit = 0; /* No such parameter (new Darwin versions) */ else externalErrorExitDesc ("Cannot get RST rate limit value"); } else if (sizeof(limit) != limit_size) externalErrorExitDesc ("Cannot get RST rate limit value"); if (limit > 0) { #ifndef _MHD_HEAVY_TESTS fprintf (stderr, "This system has limits on number of RST packets" " per second (%d).\nThis test will be used only if configured " "with '--enable-heavy-test'.\n", limit); exit (77); #else /* _MHD_HEAVY_TESTS */ int test_limit; /**< Maximum number of checks per second */ if (use_stress_os) { fprintf (stderr, "This system has limits on number of RST packet" " per second (%d).\n'_stress_os' is not possible.\n", limit); exit (77); } test_limit = limit - limit / 10; /* Add some space to not hit the limiter */ test_limit /= 4; /* Assume that all four tests with 'hard_close' run in parallel */ test_limit -= 5; /* Add some more space to not hit the limiter */ test_limit /= 3; /* Use only one third of available limit */ if (test_limit <= 0) { fprintf (stderr, "System limit for 'net.inet.icmp.icmplim' is " "too strict for this test (value: %d).\n", limit); exit (77); } if (verbose) { printf ("Limiting number of checks to %d checks/second.\n", test_limit); fflush (stdout); } rate_limiter = (unsigned int) test_limit; #if ! defined(HAVE_USLEEP) && ! defined(HAVE_NANOSLEEP) && ! defined(_WIN32) fprintf (stderr, "Sleep function is required for this test, " "but not available on this system.\n"); exit (77); #endif #endif /* _MHD_HEAVY_TESTS */ } } #endif /* HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \ HAVE_DECL_ICMPCTL_ICMPLIM */ #endif /* HAVE_SYSCTL && HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && HAVE_DECL_ICMPCTL_ICMPLIM */ } if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) externalErrorExitDesc ("Error suppressing SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif } } static void test_global_cleanup (void) { } /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags & ~O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags | O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /* DumbClient API */ struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked); void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send); void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt); /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt); void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es); /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es); /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt); /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt); /* DumbClient implementation */ enum _MHD_clientStage { DUMB_CLIENT_INIT = 0, DUMB_CLIENT_CONNECTING, DUMB_CLIENT_CONNECTED, DUMB_CLIENT_REQ_SENDING, DUMB_CLIENT_REQ_SENT, DUMB_CLIENT_HEADER_RECVEIVING, DUMB_CLIENT_HEADER_RECVEIVED, DUMB_CLIENT_BODY_RECVEIVING, DUMB_CLIENT_BODY_RECVEIVED, DUMB_CLIENT_FINISHING, DUMB_CLIENT_FINISHED }; struct _MHD_dumbClient { MHD_socket sckt; /**< the socket to communicate */ int sckt_nonblock; /**< non-zero if socket is non-blocking */ uint16_t port; /**< the port to connect to */ const char *send_buf; /**< the buffer for the request, malloced */ void *buf; /**< the buffer location */ size_t req_size; /**< the size of the request, including header */ size_t send_off; /**< the number of bytes already sent */ enum _MHD_clientStage stage; /* the test-specific variables */ size_t single_send_size; /**< the maximum number of bytes to be sent by single send() */ size_t send_size_limit; /**< the total number of send bytes limit */ }; struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked) { struct _MHD_dumbClient *clnt; size_t method_size; size_t url_size; size_t add_hdrs_size; size_t buf_alloc_size; char *send_buf; mhd_assert (0 != port); mhd_assert (NULL != req_body || 0 == req_body_size); mhd_assert (0 == req_body_size || NULL != req_body); clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient)); if (NULL == clnt) externalErrorExit (); memset (clnt, 0, sizeof(struct _MHD_dumbClient)); clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == clnt->sckt) externalErrorExitDesc ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (clnt->sckt)) externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ clnt->sckt_nonblock = 0; if (clnt->sckt_nonblock) make_nonblocking (clnt->sckt); else make_blocking (clnt->sckt); if (1) { /* Always set TCP NODELAY */ const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) externalErrorExitDesc ("Cannot set TCP_NODELAY option"); } clnt->port = port; if (NULL != method) method_size = strlen (method); else { method = MHD_HTTP_METHOD_GET; method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET); } mhd_assert (0 != method_size); if (NULL != url) url_size = strlen (url); else { url = "/"; url_size = 1; } mhd_assert (0 != url_size); add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers); buf_alloc_size = 1024 + method_size + url_size + add_hdrs_size + req_body_size; send_buf = (char *) malloc (buf_alloc_size); if (NULL == send_buf) externalErrorExit (); clnt->req_size = 0; /* Form the request line */ memcpy (send_buf + clnt->req_size, method, method_size); clnt->req_size += method_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, url, url_size); clnt->req_size += url_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1, MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1); send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Form the header */ memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST, MHD_STATICSTR_LEN_ (REQ_HEADER_HOST)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST); memcpy (send_buf + clnt->req_size, REQ_HEADER_UA, MHD_STATICSTR_LEN_ (REQ_HEADER_UA)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA); if ((NULL != req_body) || chunked) { if (! chunked) { int prn_size; memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%u", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } else { memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n"); } } if (0 != add_hdrs_size) { memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size); clnt->req_size += add_hdrs_size; } /* Terminate header */ send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Add body (if any) */ if (! chunked) { if (0 != req_body_size) { memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; } } else { if (0 != req_body_size) { int prn_size; prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%x", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } send_buf[clnt->req_size++] = '0'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } mhd_assert (clnt->req_size < buf_alloc_size); clnt->buf = send_buf; clnt->send_buf = send_buf; return clnt; } void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send) { clnt->single_send_size = step_size; clnt->send_size_limit = max_total_send; } /* internal */ static void _MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt) { struct sockaddr_in sa; mhd_assert (DUMB_CLIENT_INIT == clnt->stage); sa.sin_family = AF_INET; sa.sin_port = htons ((uint16_t) clnt->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa))) { const int err = MHD_socket_get_error_ (); if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) || (MHD_SCKT_ERR_IS_EAGAIN_ (err))) clnt->stage = DUMB_CLIENT_CONNECTING; else externalErrorExitDesc ("Cannot 'connect()' the client socket"); } else clnt->stage = DUMB_CLIENT_CONNECTED; } void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt) { mhd_assert (DUMB_CLIENT_INIT == clnt->stage); _MHD_dumbClient_connect_init (clnt); } /* internal */ static void _MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt) { int err = 0; socklen_t err_size = sizeof(err); mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage); if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR, (void *) &err, &err_size)) externalErrorExitDesc ("'getsockopt()' call failed"); if (0 != err) externalErrorExitDesc ("Socket connect() failed"); clnt->stage = DUMB_CLIENT_CONNECTED; } /* internal */ static void _MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt) { size_t send_size; ssize_t res; mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage); mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage); mhd_assert (clnt->req_size > clnt->send_off); send_size = (((0 != clnt->send_size_limit) && (clnt->req_size > clnt->send_size_limit)) ? clnt->send_size_limit : clnt->req_size) - clnt->send_off; mhd_assert (0 != send_size); if ((0 != clnt->single_send_size) && (clnt->single_send_size < send_size)) send_size = clnt->single_send_size; res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size); if (res < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) return; if (MHD_SCKT_ERR_IS_EINTR_ (err)) return; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("The connection was aborted by MHD"); if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) mhdErrorExitDesc ("The connection was shut down on MHD side"); externalErrorExitDesc ("Unexpected network error"); } clnt->send_off += (size_t) res; mhd_assert (clnt->send_off <= clnt->req_size); mhd_assert (clnt->send_off <= clnt->send_size_limit || \ 0 == clnt->send_size_limit); if (clnt->req_size == clnt->send_off) clnt->stage = DUMB_CLIENT_REQ_SENT; if ((0 != clnt->send_size_limit) && (clnt->send_size_limit == clnt->send_off)) clnt->stage = DUMB_CLIENT_FINISHING; } /* internal */ _MHD_NORETURN /* Declared as 'noreturn' until it is implemented */ static void _MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt) { (void) clnt; externalErrorExitDesc ("Not implemented for this test"); } int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt) { return DUMB_CLIENT_REQ_SENT <= clnt->stage; } /* internal */ static void _MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (use_hard_close) { #ifdef SO_LINGER static const struct linger hard_close = {1, 0}; mhd_assert (0 == hard_close.l_linger); if (0 != setsockopt (clnt->sckt, SOL_SOCKET, SO_LINGER, (const void *) &hard_close, sizeof (hard_close))) #endif /* SO_LINGER */ externalErrorExitDesc ("Failed to set SO_LINGER option"); } if (! MHD_socket_close_ (clnt->sckt)) externalErrorExitDesc ("Unexpected error while closing " \ "the client socket"); clnt->sckt = MHD_INVALID_SOCKET; } } /* internal */ static void _MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (use_shutdown) { if (0 != shutdown (clnt->sckt, SHUT_WR)) { const int err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) && ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("Unexpected error when shutting down " \ "the client socket"); } } else if (use_close) { _MHD_dumbClient_socket_close (clnt); } else mhd_assert (0); } clnt->stage = DUMB_CLIENT_FINISHED; } /* internal */ static int _MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt) { return ((DUMB_CLIENT_CONNECTING <= clnt->stage) && (DUMB_CLIENT_REQ_SENT > clnt->stage)) || (DUMB_CLIENT_FINISHING == clnt->stage); } /* internal */ static int _MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt) { return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) && (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage); } /* internal */ /** * Check whether the client needs unconditionally process the data. * @param clnt the client to check * @return non-zero if client needs unconditionally process the data, * zero otherwise. */ static int _MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt) { switch (clnt->stage) { case DUMB_CLIENT_INIT: case DUMB_CLIENT_REQ_SENT: case DUMB_CLIENT_HEADER_RECVEIVED: case DUMB_CLIENT_BODY_RECVEIVED: case DUMB_CLIENT_FINISHED: return ! 0; case DUMB_CLIENT_CONNECTING: case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: case DUMB_CLIENT_HEADER_RECVEIVING: case DUMB_CLIENT_BODY_RECVEIVING: case DUMB_CLIENT_FINISHING: default: break; } return 0; } /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt) { do { switch (clnt->stage) { case DUMB_CLIENT_INIT: _MHD_dumbClient_connect_init (clnt); break; case DUMB_CLIENT_CONNECTING: _MHD_dumbClient_connect_finish (clnt); break; case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: _MHD_dumbClient_send_req (clnt); break; case DUMB_CLIENT_REQ_SENT: mhd_assert (0); clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING; break; case DUMB_CLIENT_HEADER_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_HEADER_RECVEIVED: clnt->stage = DUMB_CLIENT_BODY_RECVEIVING; break; case DUMB_CLIENT_BODY_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_BODY_RECVEIVED: clnt->stage = DUMB_CLIENT_FINISHING; break; case DUMB_CLIENT_FINISHING: _MHD_dumbClient_finalize (clnt); break; case DUMB_CLIENT_FINISHED: return ! 0; default: mhd_assert (0); mhdErrorExit (); } } while (_MHD_dumbClient_needs_process (clnt)); return DUMB_CLIENT_FINISHED == clnt->stage; } void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es) { mhd_assert (NULL != rs); mhd_assert (NULL != ws); mhd_assert (NULL != es); if (DUMB_CLIENT_FINISHED > clnt->stage) { if (MHD_INVALID_SOCKET != clnt->sckt) { if ( (MHD_INVALID_SOCKET == *maxsckt) || (clnt->sckt > *maxsckt) ) *maxsckt = clnt->sckt; if (_MHD_dumbClient_needs_recv (clnt)) FD_SET (clnt->sckt, rs); if (_MHD_dumbClient_needs_send (clnt)) FD_SET (clnt->sckt, ws); FD_SET (clnt->sckt, es); } } } /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es) { if (_MHD_dumbClient_needs_process (clnt)) return _MHD_dumbClient_process (clnt); else if (MHD_INVALID_SOCKET != clnt->sckt) { if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs)) return _MHD_dumbClient_process (clnt); else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws)) return _MHD_dumbClient_process (clnt); else if (FD_ISSET (clnt->sckt, es)) return _MHD_dumbClient_process (clnt); } return DUMB_CLIENT_FINISHED == clnt->stage; } /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt) { time_t start; time_t now; start = time (NULL); now = start; do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; struct timeval tv; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! _MHD_dumbClient_needs_process (clnt)) { maxMhdSk = MHD_INVALID_SOCKET; _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); mhd_assert (now >= start); #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1); #else /* Native W32 */ tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1); #endif /* Native W32 */ tv.tv_usec = 250 * 1000; if (-1 == select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else /* ! MHD_POSIX_SOCKETS */ mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \ (0 != es.fd_count)); externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif /* ! MHD_POSIX_SOCKETS */ continue; } if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) return 0; } /* Use double timeout value here as MHD must catch timeout situations * in this test. Timeout in client as a last resort. */ } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2)); return 1; } /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt) { if (DUMB_CLIENT_FINISHED != clnt->stage) _MHD_dumbClient_finalize (clnt); _MHD_dumbClient_socket_close (clnt); if (NULL != clnt->send_buf) { mhd_assert (clnt->send_buf == clnt->buf); free (clnt->buf); clnt->buf = NULL; clnt->send_buf = NULL; } free (clnt); } struct sckt_notif_cb_param { volatile unsigned int num_started; volatile unsigned int num_finished; }; static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { struct sckt_notif_cb_param *param = (struct sckt_notif_cb_param *) cls; if (NULL == socket_context) mhdErrorExitDesc ("'socket_context' pointer is NULL"); if (NULL == c) mhdErrorExitDesc ("'connection' pointer is NULL"); if (NULL == param) mhdErrorExitDesc ("'cls' pointer is NULL"); if (MHD_CONNECTION_NOTIFY_STARTED == toe) param->num_started++; else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) param->num_finished++; else mhdErrorExitDesc ("Unknown 'toe' value"); } struct term_notif_cb_param { volatile int term_reason; volatile unsigned int num_called; }; static void term_cb (void *cls, struct MHD_Connection *c, void **req_cls, enum MHD_RequestTerminationCode term_code) { struct term_notif_cb_param *param = (struct term_notif_cb_param *) cls; if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' pointer is NULL"); if (NULL == c) mhdErrorExitDesc ("'connection' pointer is NULL"); if (NULL == param) mhdErrorExitDesc ("'cls' pointer is NULL"); param->term_reason = (int) term_code; param->num_called++; } static const char * term_reason_str (enum MHD_RequestTerminationCode term_code) { switch ((int) term_code) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: return "COMPLETED_OK"; case MHD_REQUEST_TERMINATED_WITH_ERROR: return "TERMINATED_WITH_ERROR"; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: return "TIMEOUT_REACHED"; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: return "DAEMON_SHUTDOWN"; case MHD_REQUEST_TERMINATED_READ_ERROR: return "READ_ERROR"; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: return "CLIENT_ABORT"; case -1: return "(not called)"; default: break; } return "(unknown code)"; } struct check_uri_cls { const char *volatile uri; volatile unsigned int cb_called; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; if (NULL == con) mhdErrorExitDesc ("The 'con' pointer is NULL"); param->cb_called++; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: '%s'\n", uri); mhdErrorExit (); } return NULL; } struct mhd_header_checker_param { int found_header_host; /**< the number of 'Host' headers */ int found_header_ua; /**< the number of 'User-Agent' headers */ int found_header_ct; /**< the number of 'Content-Type' headers */ int found_header_cl; /**< the number of 'Content-Length' headers */ int found_header_te; /**< the number of 'Transfer-Encoding' headers */ }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((strlen (REQ_HEADER_HOST_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_HOST_NAME, key_size))) { if ((strlen (REQ_HEADER_HOST_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_HOST_VALUE, value_size))) param->found_header_host++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_HOST_VALUE); } else if ((strlen (REQ_HEADER_UA_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_UA_NAME, key_size))) { if ((strlen (REQ_HEADER_UA_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_UA_VALUE, value_size))) param->found_header_ua++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_UA_VALUE); } else if ((strlen (REQ_HEADER_CT_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_CT_NAME, key_size))) { if ((strlen (REQ_HEADER_CT_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_CT_VALUE, value_size))) param->found_header_ct++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_CT_VALUE); } else if ((strlen (MHD_HTTP_HEADER_CONTENT_LENGTH) == key_size) && (0 == memcmp (key, MHD_HTTP_HEADER_CONTENT_LENGTH, key_size))) { /* do not check value of the header here for simplicity */ param->found_header_cl++; } else if ((strlen (MHD_HTTP_HEADER_TRANSFER_ENCODING) == key_size) && (0 == memcmp (key, MHD_HTTP_HEADER_TRANSFER_ENCODING, key_size))) { if ((strlen ("chunked") == value_size) && (0 == memcmp (value, "chunked", value_size))) param->found_header_te++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, "chunked"); } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; const char *volatile rq_method; const char *volatile rq_url; const char *volatile req_body; volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */ size_t req_body_size; /**< The number of bytes in @a req_body */ size_t req_body_uploaded; /* Updated by callback */ }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; struct mhd_header_checker_param header_check_param; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); param->cb_called++; if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) { const char *const upload_body = param->req_body; if (NULL == upload_data) mhdErrorExitDesc ("'upload_data' is NULL while " \ "'*upload_data_size' value is not zero"); if (NULL == upload_body) mhdErrorExitDesc ("'*upload_data_size' value is not zero " \ "while no request body is expected"); if (param->req_body_uploaded + *upload_data_size > param->req_body_size) { fprintf (stderr, "Too large upload body received. Got %u, expected %u", (unsigned int) (param->req_body_uploaded + *upload_data_size), (unsigned int) param->req_body_size); mhdErrorExit (); } if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded, *upload_data_size)) { fprintf (stderr, "Unexpected request body at offset %u: " \ "'%.*s', expected: '%.*s'\n", (unsigned int) param->req_body_uploaded, (int) *upload_data_size, upload_data, (int) *upload_data_size, upload_body + param->req_body_uploaded); mhdErrorExit (); } param->req_body_uploaded += *upload_data_size; *upload_data_size = 0; } if (&marker != *req_cls) { /* The first call of the callback for this connection */ mhd_assert (NULL == upload_data); param->req_body_uploaded = 0; *req_cls = ▮ return MHD_YES; } memset (&header_check_param, 0, sizeof(header_check_param)); if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, &header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); if (1 != header_check_param.found_header_host) mhdErrorExitDesc ("'Host' header has not been detected in request"); if (1 != header_check_param.found_header_ua) mhdErrorExitDesc ("'User-Agent' header has not been detected in request"); if (1 != header_check_param.found_header_ct) mhdErrorExitDesc ("'Content-Type' header has not been detected in request"); if (! upl_chunked && (1 != header_check_param.found_header_cl)) mhdErrorExitDesc ("'Content-Length' header has not been detected " "in request"); if (upl_chunked && (1 != header_check_param.found_header_te)) mhdErrorExitDesc ("'Transfer-Encoding' header has not been detected " "in request"); if (NULL != upload_data) return MHD_YES; /* Full request has not been received so far */ #if 0 /* Code unused in this test */ struct MHD_Response *response; response = MHD_create_response_from_buffer (param->rp_data_size, (void *) param->rp_data, MHD_RESPMEM_MUST_COPY); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); #else if (NULL == upload_data) mhdErrorExitDesc ("Full request received, " \ "while incomplete request expected"); ret = MHD_NO; #endif return ret; } struct simpleQueryParams { /* Destination path for HTTP query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for HTTP query */ uint16_t queryPort; /* Additional request headers, static */ const char *headers; /* NULL for request without body */ const uint8_t *req_body; size_t req_body_size; /* Non-zero to use chunked encoding for request body */ int chunked; /* Max size of data for single 'send()' call */ size_t step_size; /* Limit for total amount of sent data */ size_t total_send_max; /* HTTP query result error flag */ volatile int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* returns non-zero if timed-out */ static int performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt) { time_t start; struct timeval tv; int ret; const union MHD_DaemonInfo *di; MHD_socket lstn_sk; int client_accepted; int full_req_recieved; int full_req_sent; int some_data_recieved; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (NULL == di) mhdErrorExitDesc ("Cannot get lister socket"); lstn_sk = di->listen_fd; ret = 1; /* will be replaced with real result */ client_accepted = 0; _MHD_dumbClient_start_connect (clnt); full_req_recieved = 0; some_data_recieved = 0; start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int num_ready; int do_client; /**< Process data in client */ maxMhdSk = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL == clnt) { /* client has finished, check whether MHD is still * processing any connections */ full_req_sent = 1; do_client = 0; if (client_accepted && (0 > MHD_get_timeout64s (d))) { ret = 0; break; /* MHD finished as well */ } } else { full_req_sent = _MHD_dumbClient_is_req_sent (clnt); if (! full_req_sent) do_client = 1; /* Request hasn't been sent yet, send the data */ else { /* All request data has been sent. * Client will close the socket as the next step. */ if (full_req_recieved) { /* All data has been received by the MHD */ do_client = 1; /* Close the client socket */ } else if (some_data_recieved && (! use_hard_close || ((0 == rate_limiter) && use_stress_os))) { /* No RST rate limiter or no "hard close", no need to avoid extra RST * and at least something was received by the MHD */ /* In case of 'hard close' this can stress the OS, especially * if 'by_step' is enabled as several ACKs (for delivered packets * containing the request) from the server may arrive to the client * when the client has closed port and may be reflected by several * RSTs from the client side to the server side (when ACK received * without active connection then RST packet should be sent). * When listening socket receives RST packets, it may block * the sender preventing the next connection. */ do_client = 1; /* Proceed with the closure of the client socket */ } else { /* When rate limiter is enabled, all sent packets must be received * before client closes connection to avoid RST for every ACK. * When rate limiter is not enabled, the MHD must receive at * least something before closing the connection. */ do_client = 0; /* Do not close the client socket yet */ } } if (do_client) _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); if (do_client) { tv.tv_sec = 1; tv.tv_usec = 250 * 1000; } else { /* Request completely sent but not yet fully received */ tv.tv_sec = 0; tv.tv_usec = FINAL_PACKETS_MS * 1000; } num_ready = select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv); if (-1 == num_ready) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif continue; } if (0 == num_ready) { /* select() finished by timeout, looks like no more packets are pending */ if (do_client) externalErrorExitDesc ("Timeout waiting for sockets"); if (full_req_sent && (! full_req_recieved)) full_req_recieved = 1; } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); if (! client_accepted) client_accepted = FD_ISSET (lstn_sk, &rs); else { /* Client connection was already accepted by MHD */ if (! some_data_recieved) { if (! do_client) { if (0 != num_ready) { /* Connection was accepted before, "ready" socket means data */ some_data_recieved = 1; } } else { if (2 == num_ready) some_data_recieved = 1; else if ((1 == num_ready) && ((MHD_INVALID_SOCKET == clnt->sckt) || ! FD_ISSET (clnt->sckt, &ws))) some_data_recieved = 1; } } } if (do_client) { if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) clnt = NULL; } /* Use double timeout value here so MHD would be able to catch timeout * internally */ } while (time (NULL) - start <= (TIMEOUTS_VAL * 2)); return ret; } /* Returns zero for successful response and non-zero for failed response */ static int doClientQueryInThread (struct MHD_Daemon *d, struct simpleQueryParams *p) { const union MHD_DaemonInfo *dinfo; struct _MHD_dumbClient *c; int errornum; int use_external_poll; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (0 == p->queryPort) externalErrorExit (); c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); _MHD_dumbClient_set_send_limits (c, p->step_size, p->total_send_max); /* 'internal' polling should not be used in this test */ mhd_assert (use_external_poll); if (! use_external_poll) errornum = _MHD_dumbClient_perform (c); else errornum = performQueryExternal (d, c); if (errornum) fprintf (stderr, "Request timeout out.\n"); _MHD_dumbClient_close (c); return errornum; } static void printTestResults (FILE *stream, struct simpleQueryParams *qParam, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param, struct term_notif_cb_param *term_result, struct sckt_notif_cb_param *sckt_result) { if (stderr != stream) fflush (stderr); fprintf (stream, " Request aborted at %u byte%s.", (unsigned int) qParam->total_send_max, 1 == qParam->total_send_max ? "" : "s"); if ((1 == sckt_result->num_started) && (1 == sckt_result->num_finished)) fprintf (stream, " One socket has been accepted and then closed."); else fprintf (stream, " Sockets have been accepted %u time%s" " and closed %u time%s.", sckt_result->num_started, (1 == sckt_result->num_started) ? "" : "s", sckt_result->num_finished, (1 == sckt_result->num_finished) ? "" : "s"); if (0 == uri_cb_param->cb_called) fprintf (stream, " URI callback has NOT been called."); else fprintf (stream, " URI callback has been called %u time%s.", uri_cb_param->cb_called, 1 == uri_cb_param->cb_called ? "" : "s"); if (0 == ahc_param->cb_called) fprintf (stream, " Access handler callback has NOT been called."); else fprintf (stream, " Access handler callback has been called %u time%s.", ahc_param->cb_called, 1 == ahc_param->cb_called ? "" : "s"); if (0 == term_result->num_called) fprintf (stream, " Final notification callback has NOT been called."); else fprintf (stream, " Final notification callback has been called %u time%s " "with %s code.", term_result->num_called, (1 == term_result->num_called) ? "" : "s", term_reason_str ((enum MHD_RequestTerminationCode) term_result->term_reason)); fprintf (stream, "\n"); fflush (stream); } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param, struct term_notif_cb_param *term_result, struct sckt_notif_cb_param *sckt_result) { struct simpleQueryParams qParam; time_t start; unsigned int ret = 0; /* Return value */ size_t req_total_size; size_t limit_send_size; size_t inc_size; int expected_reason; int found_right_reason; /* Common parameters, to be individually overridden by specific test cases * if needed */ qParam.queryPort = d_port; qParam.method = MHD_HTTP_METHOD_PUT; qParam.queryPath = EXPECTED_URI_BASE_PATH; qParam.headers = REQ_HEADER_CT; qParam.req_body = (const uint8_t *) REQ_BODY; qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY); qParam.chunked = upl_chunked; qParam.step_size = by_step ? 1 : 0; uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = MHD_HTTP_METHOD_PUT; ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->req_body = (const char *) qParam.req_body; ahc_param->req_body_size = qParam.req_body_size; do { struct _MHD_dumbClient *test_c; struct simpleQueryParams *p = &qParam; test_c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); req_total_size = test_c->req_size; _MHD_dumbClient_close (test_c); } while (0); expected_reason = use_hard_close ? MHD_REQUEST_TERMINATED_READ_ERROR : MHD_REQUEST_TERMINATED_CLIENT_ABORT; found_right_reason = 0; if (0 != rate_limiter) { if (verbose) { printf ("Pausing for rate limiter..."); fflush (stdout); } _MHD_sleep (1150); /* Just a bit more than one second */ if (verbose) { printf (" OK\n"); fflush (stdout); } inc_size = ((req_total_size - 1) + (rate_limiter - 1)) / rate_limiter; if (0 == inc_size) inc_size = 1; } else inc_size = 1; start = time (NULL); for (limit_send_size = 1; limit_send_size < req_total_size; limit_send_size += inc_size) { int test_succeed; test_succeed = 0; /* Make sure that maximum size is tested */ if (req_total_size - inc_size < limit_send_size) limit_send_size = req_total_size - 1; qParam.total_send_max = limit_send_size; /* To be updated by callbacks */ ahc_param->cb_called = 0; uri_cb_param->cb_called = 0; term_result->num_called = 0; term_result->term_reason = -1; sckt_result->num_started = 0; sckt_result->num_finished = 0; if (0 != doClientQueryInThread (d, &qParam)) fprintf (stderr, "FAILED: connection has NOT been closed by MHD."); else { if ((-1 != term_result->term_reason) && (MHD_REQUEST_TERMINATED_READ_ERROR != term_result->term_reason) && (MHD_REQUEST_TERMINATED_CLIENT_ABORT != term_result->term_reason) ) fprintf (stderr, "FAILED: Wrong termination code."); else if ((0 == term_result->num_called) && ((0 != uri_cb_param->cb_called) || (0 != ahc_param->cb_called))) fprintf (stderr, "FAILED: Missing required call of final notification " "callback."); else if (1 < uri_cb_param->cb_called) fprintf (stderr, "FAILED: Too many URI callbacks."); else if ((0 != ahc_param->cb_called) && (0 == uri_cb_param->cb_called)) fprintf (stderr, "FAILED: URI callback has NOT been called " "while Access Handler callback has been called."); else if (1 < term_result->num_called) fprintf (stderr, "FAILED: Too many final callbacks."); else if (1 != sckt_result->num_started) fprintf (stderr, "FAILED: Wrong number of sockets accepted."); else if (1 != sckt_result->num_finished) fprintf (stderr, "FAILED: Wrong number of sockets closed."); else { test_succeed = 1; if (expected_reason == term_result->term_reason) found_right_reason = 1; } } if (! test_succeed) { ret = 1; printTestResults (stderr, &qParam, ahc_param, uri_cb_param, term_result, sckt_result); } else if (verbose) { printf ("SUCCEED:"); printTestResults (stdout, &qParam, ahc_param, uri_cb_param, term_result, sckt_result); } if (time (NULL) - start > (time_t) ((TIMEOUTS_VAL * 25) + (rate_limiter * FINAL_PACKETS_MS) / 1000 + 1)) { ret |= 1 << 2; fprintf (stderr, "FAILED: Test total time exceeded.\n"); break; } } MHD_stop_daemon (d); free (uri_cb_param); free (ahc_param); free (term_result); free (sckt_result); if (! found_right_reason) { #ifndef __gnu_hurd__ fprintf (stderr, "FAILED: termination callback was not called with " "expected (%s) reason.\n", term_reason_str ((enum MHD_RequestTerminationCode) expected_reason)); fflush (stderr); ret |= 1 << 1; #endif /* ! __gnu_hurd__ */ (void) 0; } return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param, struct term_notif_cb_param **term_result, struct sckt_notif_cb_param **sckt_result) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param) || (NULL == term_result)) externalErrorExit (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); *term_result = (struct term_notif_cb_param *) malloc (sizeof(struct term_notif_cb_param)); if (NULL == *term_result) externalErrorExit (); *sckt_result = (struct sckt_notif_cb_param *) malloc (sizeof(struct sckt_notif_cb_param)); if (NULL == *sckt_result) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4170; if (use_shutdown) *pport = (uint16_t) (*pport + 0); if (use_close) *pport = (uint16_t) (*pport + 1); if (use_hard_close) *pport = (uint16_t) (*pport + 1); if (by_step) *pport = (uint16_t) (*pport + (1 << 2)); if (upl_chunked) *pport = (uint16_t) (*pport + (1 << 3)); if (! oneone) *pport = (uint16_t) (*pport + (1 << 4)); } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); if (NULL == d) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; struct sckt_notif_cb_param *sckt_result; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param, &term_result, &sckt_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result, sckt_result); } #if 0 /* disabled runners, not suitable for this test */ static int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param, &term_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } #endif /* disabled runners, not suitable for this test */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); use_shutdown = has_in_name (argv[0], "_shutdown") ? 1 : 0; use_close = has_in_name (argv[0], "_close") ? 1 : 0; use_hard_close = has_in_name (argv[0], "_hard_close") ? 1 : 0; use_stress_os = has_in_name (argv[0], "_stress_os") ? 1 : 0; by_step = has_in_name (argv[0], "_steps") ? 1 : 0; upl_chunked = has_in_name (argv[0], "_chunked") ? 1 : 0; #ifndef SO_LINGER if (use_hard_close) { fprintf (stderr, "This test requires SO_LINGER socket option support.\n"); return 77; } #endif /* ! SO_LINGER */ if (1 != use_shutdown + use_close) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (use_stress_os && ! use_hard_close) return 99; test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; #if 0 /* disabled runners, not suitable for this test */ if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } #endif /* disabled runners, not suitable for this test */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/gen_auth.h0000644000175000017500000000511715035214301016204 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/gen_auth.h * @brief Declarations for HTTP authorisation general functions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_GET_AUTH_H #define MHD_GET_AUTH_H 1 #include "mhd_options.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ struct MHD_Connection; /* Forward declaration to avoid include of the large headers */ #ifdef BAUTH_SUPPORT /* Forward declaration to avoid additional headers inclusion */ struct MHD_RqBAuth; /** * Return request's Basic Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqBAuth * MHD_get_rq_bauth_params_ (struct MHD_Connection *connection); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /* Forward declaration to avoid additional headers inclusion */ struct MHD_RqDAuth; /** * Return request's Digest Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqDAuth * MHD_get_rq_dauth_params_ (struct MHD_Connection *connection); #endif /* DAUTH_SUPPORT */ #endif /* MHD_GET_AUTH_H */ libmicrohttpd-1.0.2/src/microhttpd/test_postprocessor_md.c0000644000175000017500000011311014760713574021066 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2020 Christian Grothoff Copyright (C) 2020-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor_md.c * @brief Testcase for postprocessor, keys with no value * @author Markus Doppelbauer * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "microhttpd.h" #include "internal.h" #include "postprocessor.h" #if 0 #include "mhd_panic.c" #include "mhd_str.c" #include "internal.c" #endif #define DEBUG 0 /* local replacement for MHD functions */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) { (void) connection; (void) kind; (void) key; /* Mute compiler warnings */ (void) key_size; *value_ptr = ""; if (NULL != value_size_ptr) *value_size_ptr = 0; return MHD_NO; } #define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0])) static unsigned int found; static enum MHD_Result post_data_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (0 == strcmp (key, "xxxx")) { if ( (4 != size) || (0 != memcmp (data, "xxxx", 4)) ) exit (1); found |= 1; } if (0 == strcmp (key, "yyyy")) { if ( (4 != size) || (0 != memcmp (data, "yyyy", 4)) ) exit (1); found |= 2; } if (0 == strcmp (key, "zzzz")) { if (0 != size) exit (1); found |= 4; } if (0 == strcmp (key, "aaaa")) { if (0 != size) exit (1); found |= 8; } return MHD_YES; } static enum MHD_Result post_data_iterator2 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { static char seen[16]; (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; #if DEBUG printf ("%s\t%s@ %" PRIu64 "\n", key, data, off); #endif if (0 == strcmp (key, "text")) { if (off + size > sizeof (seen)) exit (6); memcpy (&seen[off], data, size); if ( (10 == off + size) && (0 == memcmp (seen, "text, text", 10)) ) found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator3 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (0 == strcmp (key, "y")) { if ( (1 != size) || (0 != memcmp (data, "y", 1)) ) exit (1); found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator4 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (NULL != memchr (data, 'M', size)) { found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator5 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) data; (void) off; (void) size; found++; return MHD_YES; } int main (int argc, char *argv[]) { struct MHD_PostProcessor *postprocessor; (void) argc; (void) argv; if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = &post_data_iterator; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; if (MHD_YES != MHD_post_process (postprocessor, "xxxx=xxxx", 9)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "&yyyy=yyyy&zzzz=&aaaa=", 22)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (3); if (found != 15) exit (2); } if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator2; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; if (MHD_YES != MHD_post_process (postprocessor, "text=text%2", 11)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "C+text", 6)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) exit (4); } if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator3; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; { const char *chunk = "x=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxx%2C%2Cxxxxxx" "%2Cxxxx%2C%2Cxxxxx%2Cxxxxxxxxx%2C%2Cxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxx" "%2Cxxxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2Cxx%2C%2Cxxxx%2Cxxx" "%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C" "%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx" "xx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxx%2Cxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cx" "xxxxxxxx%2Cxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2" "Cxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2" "C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxx" "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2" "C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cx%2C%" "2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cx" "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cx" "xxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx" "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx" "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2C" "xxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxx" "xxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxx%2Cxxxxx%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxx" "xx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxx" "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxx" "x%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxx" "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxx%2Cxxx" "xxxx%2Cxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%" "2C%2C%2Cxxxxxxxxx%2Cxxxxxxxx%2C" "&y=y&z=z"; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) exit (5); } if (1) { unsigned i; const char *chunks[] = { "t=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxx" "xxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%" "2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2" "Cxx%2C%2Cxxxx%2Cxxx%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxx%2C%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2C" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C" "%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxx" "xxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2" "C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2" "C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxx", /* one chunk: second line is dropped */ "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxx%2Cx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx" "xxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cx%2C%2C" "%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxx%2C%2C%2C%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxx" "%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "x%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx" "xx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxx" "x%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%" "2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2C%2C%2C%2Cxxxxxxxxxxx%2C%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2" "C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxZZZZZZZZZZZZZ%2C%2C%2C%2C" "%E2%80%A2MMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMM" "MMMMM%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMM" "zz", "", }; postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator4; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 131076; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; for (i = 0; i < ARRAY_LENGTH (chunks); ++i) { const char *chunk = chunks[i]; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) return 6; } if (1) { unsigned i; const char *chunks[] = { "XXXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&XXXXXX=&XXXXXXXXXXXXXX=X" "XXX+&XXXXXXXXXXXXXXX=XXXXXXXXX&XXXXXXXXXXXXX=XXXX%XX%XXXXXX&XXXXXXXXXX" "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXXXXXX&XXXXXXXXXXXXXXX=XX&XXXXXXXXXXXXXX" "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXX&XXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXX", "&XXXXXXXX=XXXX", "", }; postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1); found = 0; if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator5; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 131076; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; for (i = 0; i < ARRAY_LENGTH (chunks); ++i) { const char *chunk = chunks[i]; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 12) return 7; } return EXIT_SUCCESS; } libmicrohttpd-1.0.2/src/microhttpd/internal.c0000644000175000017500000001761114760713574016247 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/internal.c * @brief internal shared structures * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "mhd_str.h" #ifdef HAVE_MESSAGES #if DEBUG_STATES /** * State to string dictionary. */ const char * MHD_state_to_string (enum MHD_CONNECTION_STATE state) { switch (state) { case MHD_CONNECTION_INIT: return "connection init"; case MHD_CONNECTION_REQ_LINE_RECEIVING: return "receiving request line"; case MHD_CONNECTION_REQ_LINE_RECEIVED: return "request line received"; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: return "headers receiving"; case MHD_CONNECTION_HEADERS_RECEIVED: return "headers received"; case MHD_CONNECTION_HEADERS_PROCESSED: return "headers processed"; case MHD_CONNECTION_CONTINUE_SENDING: return "continue sending"; case MHD_CONNECTION_BODY_RECEIVING: return "body receiving"; case MHD_CONNECTION_BODY_RECEIVED: return "body received"; case MHD_CONNECTION_FOOTERS_RECEIVING: return "footers receiving"; case MHD_CONNECTION_FOOTERS_RECEIVED: return "footers received"; case MHD_CONNECTION_FULL_REQ_RECEIVED: return "full request received"; case MHD_CONNECTION_START_REPLY: return "start sending reply"; case MHD_CONNECTION_HEADERS_SENDING: return "headers sending"; case MHD_CONNECTION_HEADERS_SENT: return "headers sent"; case MHD_CONNECTION_NORMAL_BODY_UNREADY: return "normal body unready"; case MHD_CONNECTION_NORMAL_BODY_READY: return "normal body ready"; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: return "chunked body unready"; case MHD_CONNECTION_CHUNKED_BODY_READY: return "chunked body ready"; case MHD_CONNECTION_CHUNKED_BODY_SENT: return "chunked body sent"; case MHD_CONNECTION_FOOTERS_SENDING: return "footers sending"; case MHD_CONNECTION_FULL_REPLY_SENT: return "reply sent completely"; case MHD_CONNECTION_CLOSED: return "closed"; default: return "unrecognized connection state"; } } #endif #endif #ifdef HAVE_MESSAGES /** * fprintf-like helper function for logging debug * messages. */ void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...) { va_list va; if (0 == (daemon->options & MHD_USE_ERROR_LOG)) return; va_start (va, format); daemon->custom_error_log (daemon->custom_error_log_cls, format, va); va_end (va); } #endif /** * Convert all occurrences of '+' to ' '. * * @param arg string that is modified (in place), must be 0-terminated */ void MHD_unescape_plus (char *arg) { char *p; for (p = strchr (arg, '+'); NULL != p; p = strchr (p + 1, '+')) *p = ' '; } /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result is still be 0-terminated. * * @param val value to unescape (modified in the process) * @return length of the resulting val (`strlen(val)` may be * shorter afterwards due to elimination of escape sequences) */ _MHD_EXTERN size_t MHD_http_unescape (char *val) { return MHD_str_pct_decode_in_place_lenient_ (val, NULL); } /** * Parse and unescape the arguments given by the client * as part of the HTTP request URI. * * @param kind header kind to pass to @a cb * @param connection connection to add headers to * @param[in,out] args argument URI string (after "?" in URI), * clobbered in the process! * @param cb function to call on each key-value pair found * @param cls the iterator context * @return #MHD_NO on failure (@a cb returned #MHD_NO), * #MHD_YES for success (parsing succeeded, @a cb always * returned #MHD_YES) */ enum MHD_Result MHD_parse_arguments_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, char *args, MHD_ArgumentIterator_ cb, void *cls) { struct MHD_Daemon *daemon = connection->daemon; char *equals; char *amper; while ( (NULL != args) && ('\0' != args[0]) ) { size_t key_len; size_t value_len; equals = strchr (args, '='); amper = strchr (args, '&'); if (NULL == amper) { /* last argument */ if (NULL == equals) { /* last argument, without '=' */ MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); if (MHD_NO == cb (cls, args, key_len, NULL, 0, kind)) return MHD_NO; break; } /* got 'foo=bar' */ equals[0] = '\0'; equals++; MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); MHD_unescape_plus (equals); value_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, equals); if (MHD_NO == cb (cls, args, key_len, equals, value_len, kind)) return MHD_NO; break; } /* amper is non-NULL here */ amper[0] = '\0'; amper++; if ( (NULL == equals) || (equals >= amper) ) { /* got 'foo&bar' or 'foo&bar=val', add key 'foo' with NULL for value */ MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); if (MHD_NO == cb (cls, args, key_len, NULL, 0, kind)) return MHD_NO; /* continue with 'bar' */ args = amper; continue; } /* equals and amper are non-NULL here, and equals < amper, so we got regular 'foo=value&bar...'-kind of argument */ equals[0] = '\0'; equals++; MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); MHD_unescape_plus (equals); value_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, equals); if (MHD_NO == cb (cls, args, key_len, equals, value_len, kind)) return MHD_NO; args = amper; } return MHD_YES; } /* end of internal.c */ libmicrohttpd-1.0.2/src/microhttpd/md5.h0000644000175000017500000000637215035214301015103 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/md5.h * @brief Calculation of MD5 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_H #define MHD_MD5_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Number of bits in single MD5 word. */ #define MD5_WORD_SIZE_BITS 32 /** * Number of bytes in single MD5 word. */ #define MD5_BYTES_IN_WORD (MD5_WORD_SIZE_BITS / 8) /** * Hash is kept internally as four 32-bit words. * This is intermediate hash size, used during computing the final digest. */ #define MD5_HASH_SIZE_WORDS 4 /** * Size of MD5 resulting digest in bytes. * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE_WORDS MD5_HASH_SIZE_WORDS /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (MD5_DIGEST_SIZE_WORDS * MD5_BYTES_IN_WORD) /** * Size of MD5 digest string in chars including termination NUL. */ #define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1) /** * Size of MD5 single processing block in bits. */ #define MD5_BLOCK_SIZE_BITS 512 /** * Size of MD5 single processing block in bytes. */ #define MD5_BLOCK_SIZE (MD5_BLOCK_SIZE_BITS / 8) /** * Size of MD5 single processing block in words. */ #define MD5_BLOCK_SIZE_WORDS (MD5_BLOCK_SIZE_BITS / MD5_WORD_SIZE_BITS) /** * MD5 calculation context */ struct Md5Ctx { uint32_t H[MD5_HASH_SIZE_WORDS]; /**< Intermediate hash value / digest at end of calculation */ uint32_t buffer[MD5_BLOCK_SIZE_WORDS]; /**< MD5 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for MD5 calculation. * * @param ctx the calculation context */ void MHD_MD5_init (struct Md5Ctx *ctx); /** * MD5 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise MD5 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish (struct Md5Ctx *ctx, uint8_t digest[MD5_DIGEST_SIZE]); /** * Indicates that function MHD_MD5_finish() (without context reset) is available */ #define MHD_MD5_HAS_FINISH 1 #endif /* MHD_MD5_H */ libmicrohttpd-1.0.2/src/microhttpd/mhd_send.h0000644000175000017500000001244515035214301016175 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) Copyright (C) 2019 ng0 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file mhd_send.h * @brief Declarations of send() wrappers. * @author ng0 * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SEND_H #define MHD_SEND_H #include "platform.h" #include "internal.h" #if defined(HAVE_STDBOOL_H) #include #endif /* HAVE_STDBOOL_H */ #include #include "mhd_sockets.h" #include "connection.h" #ifdef HTTPS_SUPPORT #include "connection_https.h" #endif #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) || \ defined(MHD_WINSOCK_SOCKETS) #define MHD_VECT_SEND 1 #endif /* HAVE_SENDMSG || HAVE_WRITEV || MHD_WINSOCK_SOCKETS */ /** * Initialises static variables */ void MHD_send_init_static_vars_ (void); /** * Send buffer to the client, push data from network buffer if requested * and full buffer is sent. * * @param connection the MHD_Connection structure * @param buffer content of the buffer to send * @param buffer_size the size of the @a buffer (in bytes) * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return sum of the number of bytes sent from both buffers or * error code (negative) */ ssize_t MHD_send_data_ (struct MHD_Connection *connection, const char *buffer, size_t buffer_size, bool push_data); /** * Send reply header with optional reply body. * * @param connection the MHD_Connection structure * @param header content of header to send * @param header_size the size of the @a header (in bytes) * @param never_push_hdr set to true to disable internal algorithm * that can push automatically header data * alone to the network * @param body content of the body to send (optional, may be NULL) * @param body_size the size of the @a body (in bytes) * @param complete_response set to true if complete response * is provided by @a header and @a body, * set to false if additional body data * will be sent later * @return sum of the number of bytes sent from both buffers or * error code (negative) */ ssize_t MHD_send_hdr_and_body_ (struct MHD_Connection *connection, const char *header, size_t header_size, bool never_push_hdr, const char *body, size_t body_size, bool complete_response); #if defined(_MHD_HAVE_SENDFILE) /** * Function for sending responses backed by file FD. * * @param connection the MHD connection structure * @return actual number of bytes sent */ ssize_t MHD_send_sendfile_ (struct MHD_Connection *connection); #endif /** * Set required TCP_NODELAY state for connection socket * * The function automatically updates sk_nodelay state. * @param connection the connection to manipulate * @param nodelay_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection, bool nodelay_state); /** * Set required cork state for connection socket * * The function automatically updates sk_corked state. * * @param connection the connection to manipulate * @param cork_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_cork_state_ (struct MHD_Connection *connection, bool cork_state); /** * Function for sending responses backed by a an array of memory buffers. * * @param connection the MHD connection structure * @param r_iov the pointer to iov response structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ ssize_t MHD_send_iovec_ (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data); #endif /* MHD_SEND_H */ libmicrohttpd-1.0.2/src/microhttpd/mhd_md5_wrap.h0000644000175000017500000000553015035214301016757 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_md5_wrap.h * @brief Simple wrapper for selection of built-in/external MD5 implementation * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_WRAP_H #define MHD_MD5_WRAP_H 1 #include "mhd_options.h" #ifndef MHD_MD5_SUPPORT #error This file must be used only when MD5 is enabled #endif #ifndef MHD_MD5_TLSLIB #include "md5.h" #else /* MHD_MD5_TLSLIB */ #include "md5_ext.h" #endif /* MHD_MD5_TLSLIB */ #ifndef MD5_DIGEST_SIZE /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (16) #endif /* ! MD5_DIGEST_SIZE */ #ifndef MD5_DIGEST_STRING_SIZE /** * Size of MD5 digest string in chars including termination NUL. */ #define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1) #endif /* ! MD5_DIGEST_STRING_SIZE */ #ifndef MHD_MD5_TLSLIB /** * Universal ctx type mapped for chosen implementation */ #define Md5CtxWr Md5Ctx #else /* MHD_MD5_TLSLIB */ /** * Universal ctx type mapped for chosen implementation */ #define Md5CtxWr Md5CtxExt #endif /* MHD_MD5_TLSLIB */ #ifndef MHD_MD5_HAS_INIT_ONE_TIME /** * Setup and prepare ctx for hash calculation */ #define MHD_MD5_init_one_time(ctx) MHD_MD5_init(ctx) #endif /* ! MHD_MD5_HAS_INIT_ONE_TIME */ #ifndef MHD_MD5_HAS_FINISH_RESET /** * Re-use the same ctx for the new hashing after digest calculated */ #define MHD_MD5_reset(ctx) MHD_MD5_init(ctx) /** * Finalise MD5 calculation, return digest, reset hash calculation. */ #define MHD_MD5_finish_reset(ctx,digest) MHD_MD5_finish(ctx,digest), \ MHD_MD5_reset(ctx) #else /* MHD_MD5_HAS_FINISH_RESET */ #define MHD_MD5_reset(ctx) (void)0 #endif /* MHD_MD5_HAS_FINISH_RESET */ #ifndef MHD_MD5_HAS_DEINIT #define MHD_MD5_deinit(ignore) (void)0 #endif /* HAVE_MD5_DEINIT */ /* Sanity checks */ #if ! defined(MHD_MD5_HAS_FINISH_RESET) && ! defined(MHD_MD5_HAS_FINISH) #error Required at least one of MHD_MD5_finish_reset(), MHD_MD5_finish_reset() #endif /* ! MHD_MD5_HAS_FINISH_RESET && ! MHD_MD5_HAS_FINISH */ #endif /* MHD_MD5_WRAP_H */ libmicrohttpd-1.0.2/src/microhttpd/test_dauth_userdigest.c0000644000175000017500000005145514760713574021041 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_dauth_userdigest.c * @brief Tests for Digest Auth calculations of userdigest * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "microhttpd.h" #include "test_helpers.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ static int verbose = 1; /* verbose level (0-1)*/ /* Declarations and data */ struct data_md5 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_MD5_DIGEST_SIZE]; }; static const struct data_md5 md5_tests[] = { {__LINE__, "u", "r", "p", {0x44, 0xad, 0xd2, 0x2b, 0x6f, 0x31, 0x79, 0xb7, 0x51, 0xea, 0xfd, 0x68, 0xee, 0x37, 0x0f, 0x7d}}, {__LINE__, "testuser", "testrealm", "testpass", {0xeb, 0xff, 0x22, 0x5e, 0x1c, 0xeb, 0x73, 0xe0, 0x26, 0xfc, 0xc6, 0x45, 0xaf, 0x3e, 0x84, 0xf6}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, 0x67, 0x94, 0xea, 0x66, 0x86, 0x03, 0x6b, 0x43}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x7e, 0xbe, 0xcc, 0x07, 0x18, 0xa5, 0x4a, 0xb4, 0x7e, 0x21, 0x65, 0x69, 0x07, 0x66, 0x41, 0x6a}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0x6a, 0x6d, 0x4e, 0x7c, 0xd7, 0x15, 0x18, 0x68, 0xf9, 0xb8, 0xc7, 0xc8, 0xd1, 0xcd, 0xd4, 0xe0}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0x3d, 0x78, 0x80, 0x7d, 0xef, 0xe7, 0xde, 0x21, 0x57, 0xe2, 0xb0, 0xb6, 0x57, 0x3a, 0x85, 0x5f}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0x83, 0xa3, 0xf7, 0xf6, 0xb8, 0x3f, 0x71, 0xc5, 0xc2, 0xeb, 0x7c, 0x6d, 0xd2, 0xdd, 0x4c, 0x4b}} }; struct data_sha256 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_SHA256_DIGEST_SIZE]; }; static const struct data_sha256 sha256_tests[] = { {__LINE__, "u", "r", "p", {0xdc, 0xb0, 0x21, 0x10, 0x2e, 0x49, 0x1e, 0x70, 0x1a, 0x4a, 0x23, 0x6d, 0xaa, 0x89, 0x23, 0xaf, 0x21, 0x61, 0x44, 0x7b, 0xce, 0x7b, 0xb7, 0x26, 0x0a, 0x35, 0x1e, 0xe8, 0x3e, 0x9f, 0x81, 0x54}}, {__LINE__, "testuser", "testrealm", "testpass", {0xa9, 0x2e, 0xf6, 0x3b, 0x3d, 0xec, 0x38, 0x95, 0xb0, 0x8f, 0x3d, 0x4d, 0x67, 0x33, 0xf0, 0x70, 0x74, 0xcb, 0xe6, 0xd4, 0xa0, 0x01, 0x27, 0xf5, 0x74, 0x1a, 0x77, 0x4f, 0x05, 0xf9, 0xd4, 0x99}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, 0xac, 0x04, 0xf1, 0x6e, 0x46, 0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, 0x8f, 0x66, 0xa6, 0xd6, 0x3f, 0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, 0x6d}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x8e, 0x64, 0x1f, 0xaa, 0x71, 0x7d, 0x20, 0x70, 0x5a, 0xd7, 0x3c, 0x54, 0xfb, 0x04, 0x9e, 0x32, 0x6a, 0xe1, 0x1c, 0x80, 0xd6, 0x05, 0x9f, 0xc3, 0x7e, 0xbb, 0x2d, 0x7b, 0x60, 0x6c, 0x11, 0xb9}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0x8b, 0xc5, 0xa8, 0xed, 0xe3, 0x02, 0x15, 0x6b, 0x9f, 0x51, 0xce, 0x97, 0x81, 0xb5, 0x26, 0xff, 0x99, 0x29, 0x0b, 0xb2, 0xc3, 0xe4, 0x41, 0x71, 0x8e, 0xa3, 0xa1, 0x7e, 0x5a, 0xd9, 0xd6, 0x49}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0x79, 0x87, 0xc6, 0x4c, 0x30, 0xe2, 0x5f, 0x1b, 0x74, 0xbe, 0x53, 0xf9, 0x66, 0xb4, 0x9b, 0x90, 0xf2, 0x80, 0x8a, 0xa9, 0x2f, 0xaf, 0x9a, 0x00, 0x26, 0x23, 0x92, 0xd7, 0xb4, 0x79, 0x42, 0x32}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0xfd, 0x0b, 0xe3, 0x93, 0x9d, 0xca, 0x4b, 0x5c, 0x2d, 0x46, 0xe8, 0xfa, 0x6a, 0x3d, 0x16, 0xdb, 0xea, 0x82, 0x47, 0x4c, 0xb9, 0xa5, 0x88, 0xd4, 0xcb, 0x14, 0x9c, 0x54, 0xf3, 0x7c, 0xff, 0x37}} }; struct data_sha512_256 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE]; }; static const struct data_sha512_256 sha512_256_tests[] = { {__LINE__, "u", "r", "p", {0xd5, 0xe8, 0xe7, 0x3b, 0xa3, 0x47, 0xb9, 0xad, 0xf0, 0xe4, 0x7a, 0x9a, 0xce, 0x43, 0xb7, 0x08, 0x2a, 0xbc, 0x8d, 0x27, 0x27, 0x2e, 0x38, 0x7d, 0x1d, 0x9c, 0xe2, 0x44, 0x25, 0x68, 0x74, 0x04}}, {__LINE__, "testuser", "testrealm", "testpass", {0x41, 0x7d, 0xf9, 0x60, 0x7c, 0xc9, 0x60, 0x28, 0x44, 0x74, 0x75, 0xf7, 0x7b, 0x78, 0xe7, 0x60, 0xec, 0x9a, 0xe1, 0x62, 0xd4, 0x95, 0x82, 0x61, 0x68, 0xa7, 0x94, 0xe8, 0x3b, 0xdf, 0x8d, 0x59}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xe7, 0xa1, 0x9e, 0x27, 0xf6, 0x73, 0x88, 0xb2, 0xde, 0xa4, 0xe2, 0x66, 0xc5, 0x16, 0x37, 0x17, 0x4d, 0x29, 0xcc, 0xa3, 0xc1, 0xf5, 0xb2, 0x49, 0x20, 0xc1, 0x05, 0xc9, 0x20, 0x13, 0x3c, 0x3d}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x44, 0xbc, 0xd2, 0xb1, 0x1f, 0x6f, 0x7d, 0xd3, 0xae, 0xa6, 0x66, 0x8a, 0x24, 0x84, 0x4b, 0x87, 0x7d, 0xe1, 0x80, 0x24, 0x9a, 0x26, 0x6b, 0xe6, 0xdb, 0x7f, 0xe3, 0xc8, 0x7a, 0xf9, 0x75, 0x64}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0xd5, 0xf6, 0x25, 0x7c, 0x64, 0xe4, 0x01, 0xd2, 0x87, 0xd5, 0xaa, 0x19, 0xae, 0xf0, 0xa2, 0xa2, 0xce, 0x4e, 0x5d, 0xfc, 0x77, 0x70, 0x0b, 0x72, 0x90, 0x43, 0x96, 0xd2, 0x95, 0x6e, 0x83, 0x0a}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0xfb, 0x17, 0x4f, 0x5c, 0x3c, 0x78, 0x02, 0x72, 0x15, 0x17, 0xca, 0xe1, 0x3b, 0x98, 0xe2, 0xb8, 0xda, 0xe2, 0xe0, 0x11, 0x8c, 0xb7, 0x05, 0xd9, 0x4e, 0xe2, 0x99, 0x46, 0x31, 0x92, 0x04, 0xce}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0x2d, 0x3d, 0x9f, 0x12, 0xc9, 0xf3, 0xd3, 0x00, 0x11, 0x25, 0x9d, 0xc5, 0xfe, 0xce, 0xe0, 0x05, 0xae, 0x24, 0xde, 0x40, 0xe3, 0xe1, 0xf6, 0x18, 0x06, 0xd0, 0x3e, 0x65, 0xf1, 0xe6, 0x02, 0x4f}} }; /* * Helper functions */ /** * Print bin as lower case hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0')); } *hex = 0; } /* Tests */ static unsigned int check_md5 (const struct data_md5 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_md5 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++) num_failed += check_md5 (md5_tests + i); return num_failed; } static unsigned int test_md5_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha256 (const struct data_sha256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++) num_failed += check_sha256 (sha256_tests + i); return num_failed; } static unsigned int test_sha256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha512_256 (const struct data_sha512_256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha512_256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++) num_failed += check_sha512_256 (sha512_256_tests + i); return num_failed; } static unsigned int test_sha512_256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } int main (int argc, char *argv[]) { unsigned int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")) verbose = 0; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) num_failed += test_md5 (); num_failed += test_md5_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) num_failed += test_sha256 (); num_failed += test_sha256_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256)) num_failed += test_sha512_256 (); num_failed += test_sha512_256_failure (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/tsearch.h0000644000175000017500000000113614760713577016067 00000000000000/*- * Written by J.T. Conklin * Public domain. * * $NetBSD: search.h,v 1.12 1999/02/22 10:34:28 christos Exp $ */ #ifndef _TSEARCH_H_ #define _TSEARCH_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void *tdelete (const void *, void **, int (*)(const void *, const void *)); void *tfind (const void *, void * const *, int (*)(const void *, const void *)); void *tsearch (const void *, void **, int (*)(const void *, const void *)); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !_TSEARCH_H_ */ libmicrohttpd-1.0.2/src/microhttpd/mhd_compat.c0000644000175000017500000000545514760713574016551 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_compat.c * @brief Implementation of platform missing functions. * @author Karlson2k (Evgeny Grin) */ #include "mhd_compat.h" #if defined(_WIN32) && ! defined(__CYGWIN__) #include #include #ifndef HAVE_SNPRINTF #include #include #endif /* HAVE_SNPRINTF */ #endif /* _WIN32 && !__CYGWIN__ */ #ifndef HAVE_CALLOC #include /* for memset() */ #endif /* ! HAVE_CALLOC */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef HAVE_SNPRINTF /* Emulate snprintf function on W32 */ int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format, ...) { int ret; va_list args; if ( (0 != n) && (NULL != s) ) { va_start (args, format); ret = _vsnprintf (s, n, format, args); va_end (args); if ((int) n == ret) s[n - 1] = 0; if (ret >= 0) return ret; } va_start (args, format); ret = _vscprintf (format, args); va_end (args); if ( (0 <= ret) && (0 != n) && (NULL == s) ) return -1; return ret; } #endif /* HAVE_SNPRINTF */ #endif /* _WIN32 && !__CYGWIN__ */ #ifndef HAVE_CALLOC #ifdef __has_builtin # if __has_builtin (__builtin_mul_overflow) # define MHD_HAVE_NUL_OVERFLOW 1 # endif #elif __GNUC__ + 0 >= 5 # define MHD_HAVE_NUL_OVERFLOW 1 #endif /* __GNUC__ >= 5 */ void * MHD_calloc_ (size_t nelem, size_t elsize) { size_t alloc_size; void *ptr; #ifdef MHD_HAVE_NUL_OVERFLOW if (__builtin_mul_overflow (nelem, elsize, &alloc_size) || (0 == alloc_size)) return NULL; #else /* ! MHD_HAVE_NUL_OVERFLOW */ alloc_size = nelem * elsize; if ((0 == alloc_size) || (elsize != alloc_size / nelem)) return NULL; #endif /* ! MHD_HAVE_NUL_OVERFLOW */ ptr = malloc (alloc_size); if (NULL == ptr) return NULL; memset (ptr, 0, alloc_size); return ptr; } #endif /* ! HAVE_CALLOC */ libmicrohttpd-1.0.2/src/microhttpd/daemon.c0000644000175000017500000116205315035215712015663 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/daemon.c * @brief A minimal-HTTP server library * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_threads.h" #endif #include "internal.h" #include "response.h" #include "connection.h" #include "memorypool.h" #include "mhd_limits.h" #include "autoinit_funcs.h" #include "mhd_mono_clock.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_locks.h" #endif #include "mhd_sockets.h" #include "mhd_itc.h" #include "mhd_compat.h" #include "mhd_send.h" #include "mhd_align.h" #include "mhd_str.h" #ifdef MHD_USE_SYS_TSEARCH #include #else /* ! MHD_USE_SYS_TSEARCH */ #include "tsearch.h" #endif /* ! MHD_USE_SYS_TSEARCH */ #ifdef HTTPS_SUPPORT #include "connection_https.h" #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #endif /* HTTPS_SUPPORT */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifdef MHD_USE_POSIX_THREADS #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #endif /* MHD_USE_POSIX_THREADS */ /** * Default connection limit. */ #ifdef MHD_POSIX_SOCKETS #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 3 - 1 - MHD_ITC_NUM_FDS_) #else #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2) #endif /** * Default memory allowed per connection. */ #define MHD_POOL_SIZE_DEFAULT (32 * 1024) /* Forward declarations. */ /** * Global initialisation function. */ void MHD_init (void); /** * Global deinitialisation function. */ void MHD_fini (void); /** * Close all connections for the daemon. * Must only be called when MHD_Daemon::shutdown was set to true. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to close down */ static void close_all_connections (struct MHD_Daemon *daemon); #ifdef EPOLL_SUPPORT /** * Do epoll()-based processing. * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_epoll (struct MHD_Daemon *daemon, int32_t millisec); #endif /* EPOLL_SUPPORT */ #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED /** * Do nothing - global initialisation is * performed by library constructor. */ #define MHD_check_global_init_() (void) 0 #else /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ /** * Track global initialisation */ volatile int global_init_count = 0; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ /** * Global initialisation mutex */ MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif /** * Check whether global initialisation was performed * and call initialiser if necessary. */ void MHD_check_global_init_ (void) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ MHD_mutex_lock_chk_ (&global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif if (0 == global_init_count++) MHD_init (); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ MHD_mutex_unlock_chk_ (&global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif } #endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ #ifdef HAVE_MESSAGES /** * Default logger function */ static void MHD_default_logger_ (void *cls, const char *fm, va_list ap) { vfprintf ((FILE *) cls, fm, ap); #ifdef _DEBUG fflush ((FILE *) cls); #endif /* _DEBUG */ } #endif /* HAVE_MESSAGES */ /** * Free the memory allocated by MHD. * * If any MHD function explicitly mentions that returned pointer must be * freed by this function, then no other method must be used to free * the memory. * * @param ptr the pointer to free. * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3() * @sa #MHD_basic_auth_get_username_password() * @note Available since #MHD_VERSION 0x00095600 * @ingroup specialized */ _MHD_EXTERN void MHD_free (void *ptr) { free (ptr); } /** * Maintain connection count for single address. */ struct MHD_IPCount { /** * Address family. AF_INET or AF_INET6 for now. */ int family; /** * Actual address. */ union { /** * IPv4 address. */ struct in_addr ipv4; #ifdef HAVE_INET6 /** * IPv6 address. */ struct in6_addr ipv6; #endif } addr; /** * Counter. */ unsigned int count; }; /** * Lock shared structure for IP connection counts and connection DLLs. * * @param daemon handle to daemon where lock is */ static void MHD_ip_count_lock (struct MHD_Daemon *daemon) { mhd_assert (NULL == daemon->master); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->per_ip_connection_mutex); #else (void) daemon; #endif } /** * Unlock shared structure for IP connection counts and connection DLLs. * * @param daemon handle to daemon where lock is */ static void MHD_ip_count_unlock (struct MHD_Daemon *daemon) { mhd_assert (NULL == daemon->master); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->per_ip_connection_mutex); #else (void) daemon; #endif } /** * Tree comparison function for IP addresses (supplied to tsearch() family). * We compare everything in the struct up through the beginning of the * 'count' field. * * @param a1 first address to compare * @param a2 second address to compare * @return -1, 0 or 1 depending on result of compare */ static int MHD_ip_addr_compare (const void *a1, const void *a2) { return memcmp (a1, a2, offsetof (struct MHD_IPCount, count)); } /** * Parse address and initialize @a key using the address. * * @param addr address to parse * @param addrlen number of bytes in @a addr * @param key where to store the parsed address * @return #MHD_YES on success and #MHD_NO otherwise (e.g., invalid address type) */ static enum MHD_Result MHD_ip_addr_to_key (const struct sockaddr_storage *addr, socklen_t addrlen, struct MHD_IPCount *key) { memset (key, 0, sizeof(*key)); /* IPv4 addresses */ if (sizeof (struct sockaddr_in) <= (size_t) addrlen) { if (AF_INET == addr->ss_family) { key->family = AF_INET; memcpy (&key->addr.ipv4, &((const struct sockaddr_in *) addr)->sin_addr, sizeof(((const struct sockaddr_in *) NULL)->sin_addr)); return MHD_YES; } } #ifdef HAVE_INET6 if (sizeof (struct sockaddr_in6) <= (size_t) addrlen) { /* IPv6 addresses */ if (AF_INET6 == addr->ss_family) { key->family = AF_INET6; memcpy (&key->addr.ipv6, &((const struct sockaddr_in6 *) addr)->sin6_addr, sizeof(((const struct sockaddr_in6 *) NULL)->sin6_addr)); return MHD_YES; } } #endif /* Some other address */ return MHD_NO; } /** * Check if IP address is over its limit in terms of the number * of allowed concurrent connections. If the IP is still allowed, * increments the connection counter. * * @param daemon handle to daemon where connection counts are tracked * @param addr address to add (or increment counter) * @param addrlen number of bytes in @a addr * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit. * Also returns #MHD_NO if fails to allocate memory. */ static enum MHD_Result MHD_ip_limit_add (struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen) { struct MHD_IPCount *newkeyp; struct MHD_IPCount *keyp; struct MHD_IPCount **nodep; enum MHD_Result result; daemon = MHD_get_master (daemon); /* Ignore if no connection limit assigned */ if (0 == daemon->per_ip_connection_limit) return MHD_YES; newkeyp = (struct MHD_IPCount *) malloc (sizeof(struct MHD_IPCount)); if (NULL == newkeyp) return MHD_NO; /* Initialize key */ if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, newkeyp)) { free (newkeyp); return MHD_YES; /* Allow unhandled address types through */ } MHD_ip_count_lock (daemon); /* Search for the IP address */ nodep = (struct MHD_IPCount **) tsearch (newkeyp, &daemon->per_ip_connection_count, &MHD_ip_addr_compare); if (NULL == nodep) { MHD_ip_count_unlock (daemon); free (newkeyp); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to add IP connection count node.\n")); #endif return MHD_NO; } keyp = *nodep; /* Test if there is room for another connection; if so, * increment count */ result = (keyp->count < daemon->per_ip_connection_limit) ? MHD_YES : MHD_NO; if (MHD_NO != result) ++keyp->count; MHD_ip_count_unlock (daemon); /* If we got an existing node back, free the one we created */ if (keyp != newkeyp) free (newkeyp); return result; } /** * Decrement connection count for IP address, removing from table * count reaches 0. * * @param daemon handle to daemon where connection counts are tracked * @param addr address to remove (or decrement counter) * @param addrlen number of bytes in @a addr */ static void MHD_ip_limit_del (struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen) { struct MHD_IPCount search_key; struct MHD_IPCount *found_key; void **nodep; daemon = MHD_get_master (daemon); /* Ignore if no connection limit assigned */ if (0 == daemon->per_ip_connection_limit) return; /* Initialize search key */ if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, &search_key)) return; MHD_ip_count_lock (daemon); /* Search for the IP address */ if (NULL == (nodep = tfind (&search_key, &daemon->per_ip_connection_count, &MHD_ip_addr_compare))) { /* Something's wrong if we couldn't find an IP address * that was previously added */ MHD_PANIC (_ ("Failed to find previously-added IP address.\n")); } found_key = (struct MHD_IPCount *) *nodep; /* Validate existing count for IP address */ if (0 == found_key->count) { MHD_PANIC (_ ("Previously-added IP address had counter of zero.\n")); } /* Remove the node entirely if count reduces to 0 */ if (0 == --found_key->count) { tdelete (found_key, &daemon->per_ip_connection_count, &MHD_ip_addr_compare); MHD_ip_count_unlock (daemon); free (found_key); } else MHD_ip_count_unlock (daemon); } #ifdef HTTPS_SUPPORT /** * Read and setup our certificate and key. * * @param daemon handle to daemon to initialize * @return 0 on success */ static int MHD_init_daemon_certificate (struct MHD_Daemon *daemon) { gnutls_datum_t key; gnutls_datum_t cert; int ret; #if GNUTLS_VERSION_MAJOR >= 3 if (NULL != daemon->cert_callback) { gnutls_certificate_set_retrieve_function2 (daemon->x509_cred, daemon->cert_callback); } #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 else if (NULL != daemon->cert_callback2) { gnutls_certificate_set_retrieve_function3 (daemon->x509_cred, daemon->cert_callback2); } #endif if (NULL != daemon->https_mem_trust) { size_t paramlen; paramlen = strlen (daemon->https_mem_trust); if (UINT_MAX < paramlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Too long trust certificate.\n")); #endif return -1; } cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_trust); cert.size = (unsigned int) paramlen; if (gnutls_certificate_set_x509_trust_mem (daemon->x509_cred, &cert, GNUTLS_X509_FMT_PEM) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Bad trust certificate format.\n")); #endif return -1; } } if (daemon->have_dhparams) { gnutls_certificate_set_dh_params (daemon->x509_cred, daemon->https_mem_dhparams); } /* certificate & key loaded from memory */ if ( (NULL != daemon->https_mem_cert) && (NULL != daemon->https_mem_key) ) { size_t param1len; size_t param2len; param1len = strlen (daemon->https_mem_key); param2len = strlen (daemon->https_mem_cert); if ( (UINT_MAX < param1len) || (UINT_MAX < param2len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Too long key or certificate.\n")); #endif return -1; } key.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_key); key.size = (unsigned int) param1len; cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_cert); cert.size = (unsigned int) param2len; if (NULL != daemon->https_key_password) { #if GNUTLS_VERSION_NUMBER >= 0x030111 ret = gnutls_certificate_set_x509_key_mem2 (daemon->x509_cred, &cert, &key, GNUTLS_X509_FMT_PEM, daemon->https_key_password, 0); #else #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to setup x509 certificate/key: pre 3.X.X version " \ "of GnuTLS does not support setting key password.\n")); #endif return -1; #endif } else ret = gnutls_certificate_set_x509_key_mem (daemon->x509_cred, &cert, &key, GNUTLS_X509_FMT_PEM); #ifdef HAVE_MESSAGES if (0 != ret) MHD_DLOG (daemon, _ ("GnuTLS failed to setup x509 certificate/key: %s\n"), gnutls_strerror (ret)); #endif return ret; } #if GNUTLS_VERSION_MAJOR >= 3 if (NULL != daemon->cert_callback) return 0; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 else if (NULL != daemon->cert_callback2) return 0; #endif #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("You need to specify a certificate and key location.\n")); #endif return -1; } /** * Initialize security aspects of the HTTPS daemon * * @param daemon handle to daemon to initialize * @return 0 on success */ static int MHD_TLS_init (struct MHD_Daemon *daemon) { switch (daemon->cred_type) { case GNUTLS_CRD_CERTIFICATE: if (0 != gnutls_certificate_allocate_credentials (&daemon->x509_cred)) return GNUTLS_E_MEMORY_ERROR; return MHD_init_daemon_certificate (daemon); case GNUTLS_CRD_PSK: if (0 != gnutls_psk_allocate_server_credentials (&daemon->psk_cred)) return GNUTLS_E_MEMORY_ERROR; return 0; case GNUTLS_CRD_ANON: case GNUTLS_CRD_SRP: case GNUTLS_CRD_IA: default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error: invalid credentials type %d specified.\n"), daemon->cred_type); #endif return -1; } } #endif /* HTTPS_SUPPORT */ #undef MHD_get_fdset /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. FD_SETSIZE is assumed * to be platform's default. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd) { return MHD_get_fdset2 (daemon, read_fd_set, write_fd_set, except_fd_set, max_fd, #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size_set_by_app ? ((unsigned int) daemon->fdset_size) : ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ); } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Obtain the select() file descriptor sets for the * given @a urh. * * @param urh upgrade handle to wait for * @param[out] rs read set to initialize * @param[out] ws write set to initialize * @param[out] es except set to initialize * @param[out] max_fd maximum FD to update * @param fd_setsize value of FD_SETSIZE * @return true on success, false on error */ static bool urh_to_fdset (struct MHD_UpgradeResponseHandle *urh, fd_set *rs, fd_set *ws, fd_set *es, MHD_socket *max_fd, int fd_setsize) { const MHD_socket conn_sckt = urh->connection->socket_fd; const MHD_socket mhd_sckt = urh->mhd.socket; bool res = true; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /* Do not add to 'es' only if socket is closed * or not used anymore. */ if (MHD_INVALID_SOCKET != conn_sckt) { if ( (urh->in_buffer_used < urh->in_buffer_size) && (! MHD_add_to_fd_set_ (conn_sckt, rs, max_fd, fd_setsize)) ) res = false; if ( (0 != urh->out_buffer_used) && (! MHD_add_to_fd_set_ (conn_sckt, ws, max_fd, fd_setsize)) ) res = false; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used)) && (NULL != es)) (void) MHD_add_to_fd_set_ (conn_sckt, es, max_fd, fd_setsize); } if (MHD_INVALID_SOCKET != mhd_sckt) { if ( (urh->out_buffer_used < urh->out_buffer_size) && (! MHD_add_to_fd_set_ (mhd_sckt, rs, max_fd, fd_setsize)) ) res = false; if ( (0 != urh->in_buffer_used) && (! MHD_add_to_fd_set_ (mhd_sckt, ws, max_fd, fd_setsize)) ) res = false; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->out_buffer_size) || (0 != urh->in_buffer_size) || (0 != urh->in_buffer_used)) && (NULL != es)) MHD_add_to_fd_set_ (mhd_sckt, es, max_fd, fd_setsize); } return res; } /** * Update the @a urh based on the ready FDs in * the @a rs, @a ws, and @a es. * * @param urh upgrade handle to update * @param rs read result from select() * @param ws write result from select() * @param es except result from select() * @param fd_setsize value of FD_SETSIZE used when fd_sets were created */ static void urh_from_fdset (struct MHD_UpgradeResponseHandle *urh, const fd_set *rs, const fd_set *ws, const fd_set *es, int fd_setsize) { const MHD_socket conn_sckt = urh->connection->socket_fd; const MHD_socket mhd_sckt = urh->mhd.socket; /* Reset read/write ready, preserve error state. */ urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); mhd_assert (urh->connection->sk_nonblck); #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ mhd_assert (((int) FD_SETSIZE) <= fd_setsize); fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (MHD_INVALID_SOCKET != conn_sckt) { if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (conn_sckt, NULL, fd_setsize)) { if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (rs))) urh->app.celi |= MHD_EPOLL_STATE_READ_READY; if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (ws))) urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; if ((NULL != es) && FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (es))) urh->app.celi |= MHD_EPOLL_STATE_ERROR; } else { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ urh->app.celi |= MHD_EPOLL_STATE_READ_READY; urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; } } if ((MHD_INVALID_SOCKET != mhd_sckt)) { if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (mhd_sckt, NULL, fd_setsize)) { if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (rs))) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (ws))) urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; if ((NULL != es) && FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (es))) urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; } else { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; } } } #ifdef HAVE_POLL /** * Set required 'event' members in 'pollfd' elements, * assuming that @a p[0].fd is MHD side of socketpair * and @a p[1].fd is TLS connected socket. * * @param urh upgrade handle to watch for * @param p pollfd array to update */ static void urh_update_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { p[0].events = 0; p[1].events = 0; if (urh->in_buffer_used < urh->in_buffer_size) p[0].events |= POLLIN; if (0 != urh->out_buffer_used) p[0].events |= POLLOUT; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used))) p[0].events |= MHD_POLL_EVENTS_ERR_DISC; if (urh->out_buffer_used < urh->out_buffer_size) p[1].events |= POLLIN; if (0 != urh->in_buffer_used) p[1].events |= POLLOUT; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->out_buffer_size) || (0 != urh->in_buffer_size) || (0 != urh->in_buffer_used))) p[1].events |= MHD_POLL_EVENTS_ERR_DISC; } /** * Set @a p to watch for @a urh. * * @param urh upgrade handle to watch for * @param p pollfd array to set */ static void urh_to_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { p[0].fd = urh->connection->socket_fd; p[1].fd = urh->mhd.socket; urh_update_pollfd (urh, p); } /** * Update ready state in @a urh based on pollfd. * @param urh upgrade handle to update * @param p 'poll()' processed pollfd. */ static void urh_from_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { /* Reset read/write ready, preserve error state. */ urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); if (0 != (p[0].revents & POLLIN)) urh->app.celi |= MHD_EPOLL_STATE_READ_READY; if (0 != (p[0].revents & POLLOUT)) urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[0].revents & POLLHUP)) urh->app.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[0].revents & MHD_POLL_REVENTS_ERRROR)) urh->app.celi |= MHD_EPOLL_STATE_ERROR; if (0 != (p[1].revents & POLLIN)) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; if (0 != (p[1].revents & POLLOUT)) urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[1].revents & POLLHUP)) urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; if (0 != (p[1].revents & MHD_POLL_REVENTS_ERRROR)) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; } #endif /* HAVE_POLL */ #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /** * Internal version of #MHD_get_fdset2(). * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if any FD didn't * fit fd_set. * @ingroup event */ static enum MHD_Result internal_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, int fd_setsize) { struct MHD_Connection *pos; struct MHD_Connection *posn; enum MHD_Result result = MHD_YES; MHD_socket ls; bool itc_added; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (daemon->shutdown) return MHD_YES; /* The order of FDs added is important for W32 sockets as W32 fd_set has limits for number of added FDs instead of the limit for the higher FD value. */ /* Add ITC FD first. The daemon must be able to respond on application commands issued in other threads. */ itc_added = false; if (MHD_ITC_IS_VALID_ (daemon->itc)) { itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), read_fd_set, max_fd, fd_setsize); if (! itc_added) result = MHD_NO; } ls = daemon->was_quiesced ? MHD_INVALID_SOCKET : daemon->listen_fd; if (! itc_added && (MHD_INVALID_SOCKET != ls)) { /* Add listen FD if ITC was not added. Listen FD could be used to signal the daemon shutdown. */ if (MHD_add_to_fd_set_ (ls, read_fd_set, max_fd, fd_setsize)) ls = MHD_INVALID_SOCKET; /* Already added */ else result = MHD_NO; } /* Add all sockets to 'except_fd_set' as well to watch for * out-of-band data. However, ignore errors if INFO_READ * or INFO_WRITE sockets will not fit 'except_fd_set'. */ /* Start from oldest connections. Make sense for W32 FDSETs. */ for (pos = daemon->connections_tail; NULL != pos; pos = posn) { posn = pos->prev; switch (pos->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: if (! MHD_add_to_fd_set_ (pos->socket_fd, read_fd_set, max_fd, fd_setsize)) result = MHD_NO; #ifdef MHD_POSIX_SOCKETS if (NULL != except_fd_set) (void) MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); #endif /* MHD_POSIX_SOCKETS */ break; case MHD_EVENT_LOOP_INFO_WRITE: if (! MHD_add_to_fd_set_ (pos->socket_fd, write_fd_set, max_fd, fd_setsize)) result = MHD_NO; #ifdef MHD_POSIX_SOCKETS if (NULL != except_fd_set) (void) MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); #endif /* MHD_POSIX_SOCKETS */ break; case MHD_EVENT_LOOP_INFO_PROCESS: if ( (NULL == except_fd_set) || ! MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize)) result = MHD_NO; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* this should never happen */ break; } } #ifdef MHD_WINSOCK_SOCKETS /* W32 use limited array for fd_set so add INFO_READ/INFO_WRITE sockets * only after INFO_BLOCK sockets to ensure that INFO_BLOCK sockets will * not be pushed out. */ if (NULL != except_fd_set) { for (pos = daemon->connections_tail; NULL != pos; pos = posn) { posn = pos->prev; MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); } } #endif /* MHD_WINSOCK_SOCKETS */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (1) { struct MHD_UpgradeResponseHandle *urh; for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) { if (MHD_NO == urh_to_fdset (urh, read_fd_set, write_fd_set, except_fd_set, max_fd, fd_setsize)) result = MHD_NO; } } #endif if (MHD_INVALID_SOCKET != ls) { /* The listen socket is present and hasn't been added */ if ((daemon->connections < daemon->connection_limit) && ! daemon->at_limit) { if (! MHD_add_to_fd_set_ (ls, read_fd_set, max_fd, fd_setsize)) result = MHD_NO; } } #if _MHD_DEBUG_CONNECT #ifdef HAVE_MESSAGES if (NULL != max_fd) MHD_DLOG (daemon, _ ("Maximum socket in select set: %d\n"), *max_fd); #endif #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ return result; } /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. * * Passing custom FD_SETSIZE as @a fd_setsize allow usage of * larger/smaller than platform's default fd_sets. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize) { if ( (NULL == daemon) || (NULL == read_fd_set) || (NULL == write_fd_set) || MHD_D_IS_USING_THREADS_ (daemon) || MHD_D_IS_USING_POLL_ (daemon)) return MHD_NO; #ifdef HAVE_MESSAGES if (NULL == except_fd_set) { MHD_DLOG (daemon, _ ("MHD_get_fdset2() called with except_fd_set " "set to NULL. Such behavior is unsupported.\n")); } #endif #ifdef HAS_FD_SETSIZE_OVERRIDABLE if (0 == fd_setsize) return MHD_NO; else if (((unsigned int) INT_MAX) < fd_setsize) fd_setsize = (unsigned int) INT_MAX; #ifdef HAVE_MESSAGES else if (daemon->fdset_size > ((int) fd_setsize)) { if (daemon->fdset_size_set_by_app) { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), "MHD_get_fdset2", fd_setsize, daemon->fdset_size); } else { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than FD_SETSIZE used by MHD (%d). " \ "Some socket FDs may be not processed. " \ "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), "MHD_get_fdset2", fd_setsize, daemon->fdset_size); } } #endif /* HAVE_MESSAGES */ #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (((unsigned int) FD_SETSIZE) > fd_setsize) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than fixed FD_SETSIZE value (%d) used on the " \ "platform.\n"), "MHD_get_fdset2", fd_setsize, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return MHD_NO; } fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (daemon->shutdown) return MHD_YES; /* we're in epoll mode, use the epoll FD as a stand-in for the entire event set */ return MHD_add_to_fd_set_ (daemon->epoll_fd, read_fd_set, max_fd, (int) fd_setsize) ? MHD_YES : MHD_NO; } #endif return internal_get_fdset2 (daemon, read_fd_set, write_fd_set, except_fd_set, max_fd, (int) fd_setsize); } /** * Call the handlers for a connection in the appropriate order based * on the readiness as detected by the event loop. * * @param con connection to handle * @param read_ready set if the socket is ready for reading * @param write_ready set if the socket is ready for writing * @param force_close set if a hard error was detected on the socket; * if this information is not available, simply pass #MHD_NO * @return #MHD_YES to continue normally, * #MHD_NO if a serious error was encountered and the * connection is to be closed. */ static enum MHD_Result call_handlers (struct MHD_Connection *con, bool read_ready, bool write_ready, bool force_close) { enum MHD_Result ret; bool states_info_processed = false; /* Fast track flag */ bool on_fasttrack = (con->state == MHD_CONNECTION_INIT); ret = MHD_YES; mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (con->tid))); mhd_assert ((0 != (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (con->tid))); mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (con->tid))); #ifdef HTTPS_SUPPORT if (con->tls_read_ready) read_ready = true; #endif /* HTTPS_SUPPORT */ if ( (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) && (read_ready || (force_close && con->sk_nonblck)) ) { MHD_connection_handle_read (con, force_close); mhd_assert (! force_close || MHD_CONNECTION_CLOSED == con->state); ret = MHD_connection_handle_idle (con); if (force_close) return ret; states_info_processed = true; } if (! force_close) { /* No need to check value of 'ret' here as closed connection * cannot be in MHD_EVENT_LOOP_INFO_WRITE state. */ if ( (MHD_EVENT_LOOP_INFO_WRITE == con->event_loop_info) && write_ready) { MHD_connection_handle_write (con); ret = MHD_connection_handle_idle (con); states_info_processed = true; } } else { MHD_connection_close_ (con, MHD_REQUEST_TERMINATED_WITH_ERROR); return MHD_connection_handle_idle (con); } if (! states_info_processed) { /* Connection is not read or write ready, but external conditions * may be changed and need to be processed. */ ret = MHD_connection_handle_idle (con); } /* Fast track for fast connections. */ /* If full request was read by single read_handler() invocation and headers were completely prepared by single MHD_connection_handle_idle() then try not to wait for next sockets polling and send response immediately. As writeability of socket was not checked and it may have some data pending in system buffers, use this optimization only for non-blocking sockets. */ /* No need to check 'ret' as connection is always in * MHD_CONNECTION_CLOSED state if 'ret' is equal 'MHD_NO'. */ else if (on_fasttrack && con->sk_nonblck) { if (MHD_CONNECTION_HEADERS_SENDING == con->state) { MHD_connection_handle_write (con); /* Always call 'MHD_connection_handle_idle()' after each read/write. */ ret = MHD_connection_handle_idle (con); } /* If all headers were sent by single write_handler() and * response body is prepared by single MHD_connection_handle_idle() * call - continue. */ if ((MHD_CONNECTION_NORMAL_BODY_READY == con->state) || (MHD_CONNECTION_CHUNKED_BODY_READY == con->state)) { MHD_connection_handle_write (con); ret = MHD_connection_handle_idle (con); } } /* All connection's data and states are processed for this turn. * If connection already has more data to be processed - use * zero timeout for next select()/poll(). */ /* Thread-per-connection do not need global zero timeout as * connections are processed individually. */ /* Note: no need to check for read buffer availability for * TLS read-ready connection in 'read info' state as connection * without space in read buffer will be marked as 'info block'. */ if ( (! con->daemon->data_already_pending) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (con->daemon)) ) { if (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info)) con->daemon->data_already_pending = true; #ifdef HTTPS_SUPPORT else if ( (con->tls_read_ready) && (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) con->daemon->data_already_pending = true; #endif /* HTTPS_SUPPORT */ } return ret; } #ifdef UPGRADE_SUPPORT /** * Finally cleanup upgrade-related resources. It should * be called when TLS buffers have been drained and * application signaled MHD by #MHD_UPGRADE_ACTION_CLOSE. * * @param connection handle to the upgraded connection to clean */ static void cleanup_upgraded_connection (struct MHD_Connection *connection) { struct MHD_UpgradeResponseHandle *urh = connection->urh; if (NULL == urh) return; #ifdef HTTPS_SUPPORT /* Signal remote client the end of TLS connection by * gracefully closing TLS session. */ if (0 != (connection->daemon->options & MHD_USE_TLS)) gnutls_bye (connection->tls_session, GNUTLS_SHUT_WR); if (MHD_INVALID_SOCKET != urh->mhd.socket) MHD_socket_close_chk_ (urh->mhd.socket); if (MHD_INVALID_SOCKET != urh->app.socket) MHD_socket_close_chk_ (urh->app.socket); #endif /* HTTPS_SUPPORT */ connection->urh = NULL; free (urh); } #endif /* UPGRADE_SUPPORT */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Performs bi-directional forwarding on upgraded HTTPS connections * based on the readiness state stored in the @a urh handle. * @remark To be called only from thread that processes * connection's recv(), send() and response. * * @param urh handle to process */ static void process_urh (struct MHD_UpgradeResponseHandle *urh) { /* Help compiler to optimize: * pointers to 'connection' and 'daemon' are not changed * during this processing, so no need to chain dereference * each time. */ struct MHD_Connection *const connection = urh->connection; struct MHD_Daemon *const daemon = connection->daemon; /* Prevent data races: use same value of 'was_closed' throughout * this function. If 'was_closed' changed externally in the middle * of processing - it will be processed on next iteration. */ bool was_closed; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ mhd_assert (0 != (daemon->options & MHD_USE_TLS)); if (daemon->shutdown) { /* Daemon shutting down, application will not receive any more data. */ #ifdef HAVE_MESSAGES if (! urh->was_closed) { MHD_DLOG (daemon, _ ("Initiated daemon shutdown while \"upgraded\" " \ "connection was not closed.\n")); } #endif urh->was_closed = true; } was_closed = urh->was_closed; if (was_closed) { /* Application was closed connections: no more data * can be forwarded to application socket. */ if (0 < urh->in_buffer_used) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to application %" PRIu64 \ " bytes of data received from remote side: " \ "application closed data forwarding.\n"), (uint64_t) urh->in_buffer_used); #endif } /* Discard any data received form remote. */ urh->in_buffer_used = 0; /* Do not try to push data to application. */ urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } /* On some platforms (W32, possibly Darwin) failed send() (send() will * always fail after remote disconnect was detected) may discard data in * system buffers received by system but not yet read by recv(). So, before * trying send() on any socket, recv() must be performed at first otherwise * last part of incoming data may be lost. If disconnect or error was * detected - try to read from socket to dry data possibly pending is system * buffers. */ /* * handle reading from remote TLS client */ if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->app.celi)) || (connection->tls_read_ready)) && (urh->in_buffer_used < urh->in_buffer_size)) { ssize_t res; size_t buf_size; buf_size = urh->in_buffer_size - urh->in_buffer_used; if (buf_size > SSIZE_MAX) buf_size = SSIZE_MAX; res = gnutls_record_recv (connection->tls_session, &urh->in_buffer[urh->in_buffer_used], buf_size); if (0 >= res) { connection->tls_read_ready = false; if (GNUTLS_E_INTERRUPTED != res) { urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); if ((GNUTLS_E_AGAIN != res) || (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi))) { /* TLS unrecoverable error has been detected, socket error was detected and all data has been read, or socket was disconnected/shut down. */ /* Stop trying to read from this TLS socket. */ urh->in_buffer_size = 0; } } } else /* 0 < res */ { urh->in_buffer_used += (size_t) res; connection->tls_read_ready = (0 < gnutls_record_check_pending (connection->tls_session)); } } /* * handle reading from application */ /* If application signalled MHD about socket closure then * check for any pending data even if socket is not marked * as 'ready' (signal may arrive after poll()/select()). * Socketpair for forwarding is always in non-blocking mode * so no risk that recv() will block the thread. */ if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->mhd.celi)) || was_closed) /* Force last reading from app if app has closed the connection */ && (urh->out_buffer_used < urh->out_buffer_size)) { ssize_t res; size_t buf_size; buf_size = urh->out_buffer_size - urh->out_buffer_used; if (buf_size > MHD_SCKT_SEND_MAX_SIZE_) buf_size = MHD_SCKT_SEND_MAX_SIZE_; res = MHD_recv_ (urh->mhd.socket, &urh->out_buffer[urh->out_buffer_used], buf_size); if (0 >= res) { const int err = MHD_socket_get_error_ (); if ((0 == res) || ((! MHD_SCKT_ERR_IS_EINTR_ (err)) && (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)))) { urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); if ((0 == res) || (was_closed) || (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) || (! MHD_SCKT_ERR_IS_EAGAIN_ (err))) { /* Socket disconnect/shutdown was detected; * Application signalled about closure of 'upgraded' socket and * all data has been read from application; * or persistent / unrecoverable error. */ /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; } } } else /* 0 < res */ { urh->out_buffer_used += (size_t) res; if (buf_size > (size_t) res) urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } /* * handle writing to remote HTTPS client */ if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && (urh->out_buffer_used > 0) ) { ssize_t res; size_t data_size; data_size = urh->out_buffer_used; if (data_size > SSIZE_MAX) data_size = SSIZE_MAX; res = gnutls_record_send (connection->tls_session, urh->out_buffer, data_size); if (0 >= res) { if (GNUTLS_E_INTERRUPTED != res) { urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); if (GNUTLS_E_AGAIN != res) { /* TLS connection shut down or * persistent / unrecoverable error. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to remote client %" PRIu64 \ " bytes of data received from application: %s\n"), (uint64_t) urh->out_buffer_used, gnutls_strerror ((int) res)); #endif /* Discard any data unsent to remote. */ urh->out_buffer_used = 0; /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } } else /* 0 < res */ { const size_t next_out_buffer_used = urh->out_buffer_used - (size_t) res; if (0 != next_out_buffer_used) { memmove (urh->out_buffer, &urh->out_buffer[res], next_out_buffer_used); } urh->out_buffer_used = next_out_buffer_used; } if ( (0 == urh->out_buffer_used) && (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi)) ) { /* Unrecoverable error on socket was detected and all * pending data was sent to remote. */ /* Do not try to send to remote anymore. */ urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } /* * handle writing to application */ if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && (urh->in_buffer_used > 0) ) { ssize_t res; size_t data_size; data_size = urh->in_buffer_used; if (data_size > MHD_SCKT_SEND_MAX_SIZE_) data_size = MHD_SCKT_SEND_MAX_SIZE_; res = MHD_send_ (urh->mhd.socket, urh->in_buffer, data_size); if (0 >= res) { const int err = MHD_socket_get_error_ (); if ( (! MHD_SCKT_ERR_IS_EINTR_ (err)) && (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) ) { urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err)) { /* Socketpair connection shut down or * persistent / unrecoverable error. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to application %" PRIu64 \ " bytes of data received from remote side: %s\n"), (uint64_t) urh->in_buffer_used, MHD_socket_strerr_ (err)); #endif /* Discard any data received from remote. */ urh->in_buffer_used = 0; /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } } } else /* 0 < res */ { const size_t next_in_buffer_used = urh->in_buffer_used - (size_t) res; if (0 != next_in_buffer_used) { memmove (urh->in_buffer, &urh->in_buffer[res], next_in_buffer_used); if (data_size > (size_t) res) urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); } urh->in_buffer_used = next_in_buffer_used; } if ( (0 == urh->in_buffer_used) && (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ) { /* Do not try to push data to application. */ urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } } /* Check whether data is present in TLS buffers * and incoming forward buffer have some space. */ if ( (connection->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) daemon->data_already_pending = true; if ( (daemon->shutdown) && ( (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used) ) ) { /* Daemon shutting down, discard any remaining forward data. */ #ifdef HAVE_MESSAGES if (0 < urh->out_buffer_used) MHD_DLOG (daemon, _ ("Failed to forward to remote client %" PRIu64 \ " bytes of data received from application: daemon shut down.\n"), (uint64_t) urh->out_buffer_used); #endif /* Discard any data unsent to remote. */ urh->out_buffer_used = 0; /* Do not try to sent to remote anymore. */ urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } if (! was_closed && urh->was_closed) daemon->data_already_pending = true; /* Force processing again */ } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef UPGRADE_SUPPORT /** * Main function of the thread that handles an individual connection * after it was "upgraded" when #MHD_USE_THREAD_PER_CONNECTION is set. * @remark To be called only from thread that process * connection's recv(), send() and response. * * @param con the connection this thread will handle */ static void thread_main_connection_upgrade (struct MHD_Connection *con) { #ifdef HTTPS_SUPPORT struct MHD_UpgradeResponseHandle *urh = con->urh; struct MHD_Daemon *daemon = con->daemon; mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (con->tid) ); /* Here, we need to bi-directionally forward until the application tells us that it is done with the socket; */ if ( (0 != (daemon->options & MHD_USE_TLS)) && MHD_D_IS_USING_SELECT_ (daemon)) { while ( (0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->in_buffer_used) || (0 != urh->out_buffer_used) ) { /* use select */ fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd; int num_ready; bool result; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max_fd = MHD_INVALID_SOCKET; result = urh_to_fdset (urh, &rs, &ws, &es, &max_fd, FD_SETSIZE); if (! result) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error preparing select.\n")); #endif break; } /* FIXME: does this check really needed? */ if (MHD_INVALID_SOCKET != max_fd) { struct timeval *tvp; struct timeval tv; if (((con->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size)) || (daemon->shutdown)) { /* No need to wait if incoming data is already pending in TLS buffers. */ tv.tv_sec = 0; tv.tv_usec = 0; tvp = &tv; } else tvp = NULL; num_ready = MHD_SYS_select_ (max_fd + 1, &rs, &ws, &es, tvp); } else num_ready = 0; if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } urh_from_fdset (urh, &rs, &ws, &es, (int) FD_SETSIZE); process_urh (urh); } } #ifdef HAVE_POLL else if (0 != (daemon->options & MHD_USE_TLS)) { /* use poll() */ struct pollfd p[2]; memset (p, 0, sizeof (p)); p[0].fd = urh->connection->socket_fd; p[1].fd = urh->mhd.socket; while ( (0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->in_buffer_used) || (0 != urh->out_buffer_used) ) { int timeout; urh_update_pollfd (urh, p); if (((con->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size)) || (daemon->shutdown)) timeout = 0; /* No need to wait if incoming data is already pending in TLS buffers. */ else timeout = -1; if (MHD_sys_poll_ (p, 2, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_strerr_ (err)); #endif break; } urh_from_pollfd (urh, p); process_urh (urh); } } /* end POLL */ #endif /* end HTTPS */ #endif /* HTTPS_SUPPORT */ /* TLS forwarding was finished. Cleanup socketpair. */ MHD_connection_finish_forward_ (con); /* Do not set 'urh->clean_ready' yet as 'urh' will be used * in connection thread for a little while. */ } #endif /* UPGRADE_SUPPORT */ /** * Get maximum wait period for the connection (the amount of time left before * connection time out) * @param c the connection to check * @return the maximum number of millisecond before the connection must be * processed again. */ static uint64_t connection_get_wait (struct MHD_Connection *c) { const uint64_t now = MHD_monotonic_msec_counter (); const uint64_t since_actv = now - c->last_activity; const uint64_t timeout = c->connection_timeout_ms; uint64_t mseconds_left; mhd_assert (0 != timeout); /* Keep the next lines in sync with #connection_check_timedout() to avoid * undesired side-effects like busy-waiting. */ if (timeout < since_actv) { if (UINT64_MAX / 2 < since_actv) { const uint64_t jump_back = c->last_activity - now; /* Very unlikely that it is more than quarter-million years pause. * More likely that system clock jumps back. */ if (5000 >= jump_back) { /* Jump back is less than 5 seconds, try to recover. */ return 100; /* Set wait time to 0.1 seconds */ } /* Too large jump back */ } return 0; /* Connection has timed out */ } else if (since_actv == timeout) { /* Exact match for timeout and time from last activity. * Maybe this is just a precise match or this happens because the timer * resolution is too low. * Set wait time to 0.1 seconds to avoid busy-waiting with low * timer resolution as connection is not timed-out yet. */ return 100; } mseconds_left = timeout - since_actv; return mseconds_left; } /** * Main function of the thread that handles an individual * connection when #MHD_USE_THREAD_PER_CONNECTION is set. * * @param data the `struct MHD_Connection` this thread will handle * @return always 0 */ static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ thread_main_handle_connection (void *data) { struct MHD_Connection *con = data; struct MHD_Daemon *daemon = con->daemon; int num_ready; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef WINDOWS #ifdef HAVE_POLL unsigned int extra_slot; #endif /* HAVE_POLL */ #define EXTRA_SLOTS 1 #else /* !WINDOWS */ #define EXTRA_SLOTS 0 #endif /* !WINDOWS */ #ifdef HAVE_POLL struct pollfd p[1 + EXTRA_SLOTS]; #endif #undef EXTRA_SLOTS #ifdef HAVE_POLL const bool use_poll = MHD_D_IS_USING_POLL_ (daemon); #else /* ! HAVE_POLL */ const bool use_poll = 0; #endif /* ! HAVE_POLL */ bool was_suspended = false; MHD_thread_handle_ID_set_current_thread_ID_ (&(con->tid)); while ( (! daemon->shutdown) && (MHD_CONNECTION_CLOSED != con->state) ) { bool use_zero_timeout; #ifdef UPGRADE_SUPPORT struct MHD_UpgradeResponseHandle *const urh = con->urh; #else /* ! UPGRADE_SUPPORT */ static const void *const urh = NULL; #endif /* ! UPGRADE_SUPPORT */ if ( (con->suspended) && (NULL == urh) ) { /* Connection was suspended, wait for resume. */ was_suspended = true; if (! use_poll) { FD_ZERO (&rs); if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), &rs, NULL, FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Failed to add FD to fd_set.\n")); #endif goto exit; } if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (daemon->itc) + 1, &rs, NULL, NULL, NULL)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } } #ifdef HAVE_POLL else /* use_poll */ { p[0].events = POLLIN; p[0].fd = MHD_itc_r_fd_ (daemon->itc); p[0].revents = 0; if (0 > MHD_sys_poll_ (p, 1, -1)) { if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_last_strerr_ ()); #endif break; } } #endif /* HAVE_POLL */ MHD_itc_clear_ (daemon->itc); continue; /* Check again for resume. */ } /* End of "suspended" branch. */ if (was_suspended) { MHD_update_last_activity_ (con); /* Reset timeout timer. */ /* Process response queued during suspend and update states. */ MHD_connection_handle_idle (con); was_suspended = false; } use_zero_timeout = (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info) #ifdef HTTPS_SUPPORT || ( (con->tls_read_ready) && (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) #endif /* HTTPS_SUPPORT */ ); if (! use_poll) { /* use select */ bool err_state = false; struct timeval tv; struct timeval *tvp; if (use_zero_timeout) { tv.tv_sec = 0; tv.tv_usec = 0; tvp = &tv; } else if (con->connection_timeout_ms > 0) { const uint64_t mseconds_left = connection_get_wait (con); #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC if (mseconds_left / 1000 > TIMEVAL_TV_SEC_MAX) tv.tv_sec = TIMEVAL_TV_SEC_MAX; else #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) mseconds_left / 1000; tv.tv_usec = ((uint16_t) (mseconds_left % 1000)) * ((int32_t) 1000); tvp = &tv; } else tvp = NULL; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); maxsock = MHD_INVALID_SOCKET; switch (con->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: if (! MHD_add_to_fd_set_ (con->socket_fd, &rs, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_WRITE: if (! MHD_add_to_fd_set_ (con->socket_fd, &ws, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_PROCESS: if (! MHD_add_to_fd_set_ (con->socket_fd, &es, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* how did we get here!? */ goto exit; } #ifdef WINDOWS if (MHD_ITC_IS_VALID_ (daemon->itc) ) { if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), &rs, &maxsock, FD_SETSIZE)) err_state = 1; } #endif if (err_state) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Failed to add FD to fd_set.\n")); #endif goto exit; } num_ready = MHD_SYS_select_ (maxsock + 1, &rs, &ws, &es, tvp); if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } #ifdef WINDOWS /* Clear ITC before other processing so additional * signals will trigger select() again */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (FD_ISSET (MHD_itc_r_fd_ (daemon->itc), &rs)) ) MHD_itc_clear_ (daemon->itc); #endif if (MHD_NO == call_handlers (con, FD_ISSET (con->socket_fd, &rs), FD_ISSET (con->socket_fd, &ws), FD_ISSET (con->socket_fd, &es)) ) goto exit; } #ifdef HAVE_POLL else { int timeout_val; /* use poll */ if (use_zero_timeout) timeout_val = 0; else if (con->connection_timeout_ms > 0) { const uint64_t mseconds_left = connection_get_wait (con); #if SIZEOF_UINT64_T >= SIZEOF_INT if (mseconds_left >= INT_MAX) timeout_val = INT_MAX; else #endif /* SIZEOF_UINT64_T >= SIZEOF_INT */ timeout_val = (int) mseconds_left; } else timeout_val = -1; memset (&p, 0, sizeof (p)); p[0].fd = con->socket_fd; switch (con->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_WRITE: p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_PROCESS: p[0].events |= MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* how did we get here!? */ goto exit; } #ifdef WINDOWS extra_slot = 0; if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[1].events |= POLLIN; p[1].fd = MHD_itc_r_fd_ (daemon->itc); p[1].revents = 0; extra_slot = 1; } #endif if (MHD_sys_poll_ (p, #ifdef WINDOWS 1 + extra_slot, #else 1, #endif timeout_val) < 0) { if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_last_strerr_ ()); #endif break; } #ifdef WINDOWS /* Clear ITC before other processing so additional * signals will trigger poll() again */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) ) MHD_itc_clear_ (daemon->itc); #endif if (MHD_NO == call_handlers (con, (0 != (p[0].revents & POLLIN)), (0 != (p[0].revents & POLLOUT)), (0 != (p[0].revents & MHD_POLL_REVENTS_ERR_DISC)) )) goto exit; } #endif #ifdef UPGRADE_SUPPORT if (MHD_CONNECTION_UPGRADE == con->state) { /* Normal HTTP processing is finished, * notify application. */ if ( (NULL != daemon->notify_completed) && (con->rq.client_aware) ) daemon->notify_completed (daemon->notify_completed_cls, con, &con->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); con->rq.client_aware = false; thread_main_connection_upgrade (con); /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */ /* "Upgraded" data will not be used in this thread from this point. */ con->urh->clean_ready = true; /* If 'urh->was_closed' set to true, connection will be * moved immediately to cleanup list. Otherwise connection * will stay in suspended list until 'urh' will be marked * with 'was_closed' by application. */ MHD_resume_connection (con); /* skip usual clean up */ return (MHD_THRD_RTRN_TYPE_) 0; } #endif /* UPGRADE_SUPPORT */ } #if _MHD_DEBUG_CLOSE #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Processing thread terminating. Closing connection.\n")); #endif #endif if (MHD_CONNECTION_CLOSED != con->state) MHD_connection_close_ (con, (daemon->shutdown) ? MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN : MHD_REQUEST_TERMINATED_WITH_ERROR); MHD_connection_handle_idle (con); exit: if (NULL != con->rp.response) { MHD_destroy_response (con->rp.response); con->rp.response = NULL; } if (MHD_INVALID_SOCKET != con->socket_fd) { shutdown (con->socket_fd, SHUT_WR); /* 'socket_fd' can be used in other thread to signal shutdown. * To avoid data races, do not close socket here. Daemon will * use more connections only after cleanup anyway. */ } if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "t")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal thread termination via inter-thread " \ "communication channel.\n")); #endif } return (MHD_THRD_RTRN_TYPE_) 0; } #endif /** * Free resources associated with all closed connections. * (destroy responses, free buffers, etc.). All closed * connections are kept in the "cleanup" doubly-linked list. * * @param daemon daemon to clean up */ static void MHD_cleanup_connections (struct MHD_Daemon *daemon); #if defined(HTTPS_SUPPORT) #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \ ! defined(MHD_socket_nosignal_) && \ (GNUTLS_VERSION_NUMBER + 0 < 0x030402) && defined(MSG_NOSIGNAL) /** * Older version of GnuTLS do not support suppressing of SIGPIPE signal. * Use push function replacement with suppressing SIGPIPE signal where necessary * and if possible. */ #define MHD_TLSLIB_NEED_PUSH_FUNC 1 #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && ! MHD_socket_nosignal_ && (GNUTLS_VERSION_NUMBER+0 < 0x030402) && MSG_NOSIGNAL */ #ifdef MHD_TLSLIB_NEED_PUSH_FUNC /** * Data push function replacement with suppressing SIGPIPE signal * for TLS library. */ static ssize_t MHD_tls_push_func_ (gnutls_transport_ptr_t trnsp, const void *data, size_t data_size) { #if (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) if (data_size > MHD_SCKT_SEND_MAX_SIZE_) data_size = MHD_SCKT_SEND_MAX_SIZE_; #endif /* (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) */ return MHD_send_ ((MHD_socket) (intptr_t) (trnsp), data, data_size); } #endif /* MHD_TLSLIB_DONT_SUPPRESS_SIGPIPE */ /** * Function called by GNUtls to obtain the PSK for a given session. * * @param session the session to lookup PSK for * @param username username to lookup PSK for * @param[out] key where to write PSK * @return 0 on success, -1 on error */ static int psk_gnutls_adapter (gnutls_session_t session, const char *username, gnutls_datum_t *key) { struct MHD_Connection *connection; struct MHD_Daemon *daemon; #if GNUTLS_VERSION_MAJOR >= 3 void *app_psk; size_t app_psk_size; #endif /* GNUTLS_VERSION_MAJOR >= 3 */ connection = gnutls_session_get_ptr (session); if (NULL == connection) { #ifdef HAVE_MESSAGES /* Cannot use our logger, we don't even have "daemon" */ MHD_PANIC (_ ("Internal server error. This should be impossible.\n")); #endif return -1; } daemon = connection->daemon; #if GNUTLS_VERSION_MAJOR >= 3 if (NULL == daemon->cred_callback) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK not supported by this server.\n")); #endif return -1; } if (0 != daemon->cred_callback (daemon->cred_callback_cls, connection, username, &app_psk, &app_psk_size)) return -1; if (NULL == (key->data = gnutls_malloc (app_psk_size))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK authentication failed: gnutls_malloc failed to " \ "allocate memory.\n")); #endif free (app_psk); return -1; } if (UINT_MAX < app_psk_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK authentication failed: PSK too long.\n")); #endif free (app_psk); return -1; } key->size = (unsigned int) app_psk_size; memcpy (key->data, app_psk, app_psk_size); free (app_psk); return 0; #else (void) username; (void) key; /* Mute compiler warning */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK not supported by this server.\n")); #endif return -1; #endif } #endif /* HTTPS_SUPPORT */ /** * Do basic preparation work on the new incoming connection. * * This function do all preparation that is possible outside main daemon * thread. * @remark Could be called from any thread. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @param external_add indicate that socket has been added externally * @param non_blck indicate that socket in non-blocking mode * @param sk_spipe_supprs indicate that the @a client_socket has * set SIGPIPE suppression * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket * @return pointer to the connection on success, NULL if this daemon could * not handle the connection (i.e. malloc failed, etc). * The socket will be closed in case of error; 'errno' is * set to indicate further details about the error. */ static struct MHD_Connection * new_connection_prepare_ (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip) { struct MHD_Connection *connection; int eno = 0; #ifdef HAVE_MESSAGES #if _MHD_DEBUG_CONNECT MHD_DLOG (daemon, _ ("Accepted connection on socket %d.\n"), client_socket); #endif #endif if ( (daemon->connections == daemon->connection_limit) || (MHD_NO == MHD_ip_limit_add (daemon, addr, addrlen)) ) { /* above connection limit - reject */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Server reached connection limit. " \ "Closing inbound connection.\n")); #endif MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return NULL; } /* apply connection acceptance policy if present */ if ( (NULL != daemon->apc) && (MHD_NO == daemon->apc (daemon->apc_cls, (const struct sockaddr *) addr, addrlen)) ) { #if _MHD_DEBUG_CLOSE #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Connection rejected by application. Closing connection.\n")); #endif #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); #if defined(EACCESS) && (EACCESS + 0 != 0) errno = EACCESS; #endif return NULL; } if (NULL == (connection = MHD_calloc_ (1, sizeof (struct MHD_Connection)))) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); errno = eno; return NULL; } if (! external_add) { connection->sk_corked = _MHD_OFF; connection->sk_nodelay = _MHD_OFF; } else { connection->sk_corked = _MHD_UNKNOWN; connection->sk_nodelay = _MHD_UNKNOWN; } if (0 < addrlen) { if (NULL == (connection->addr = malloc ((size_t) addrlen))) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); free (connection); errno = eno; return NULL; } memcpy (connection->addr, addr, (size_t) addrlen); } else connection->addr = NULL; connection->addr_len = addrlen; connection->socket_fd = client_socket; connection->sk_nonblck = non_blck; connection->is_nonip = sk_is_nonip; connection->sk_spipe_suppress = sk_spipe_supprs; #ifdef MHD_USE_THREADS MHD_thread_handle_ID_set_invalid_ (&connection->tid); #endif /* MHD_USE_THREADS */ connection->daemon = daemon; connection->connection_timeout_ms = daemon->connection_timeout_ms; connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; if (0 != connection->connection_timeout_ms) connection->last_activity = MHD_monotonic_msec_counter (); if (0 == (daemon->options & MHD_USE_TLS)) { /* set default connection handlers */ MHD_set_http_callbacks_ (connection); } else { #ifdef HTTPS_SUPPORT #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030500) gnutls_init_flags_t #else unsigned int #endif flags; flags = GNUTLS_SERVER; #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402) flags |= GNUTLS_NO_SIGNAL; #endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */ #if GNUTLS_VERSION_MAJOR >= 3 flags |= GNUTLS_NONBLOCK; #endif /* GNUTLS_VERSION_MAJOR >= 3*/ #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030603) if (0 != (daemon->options & MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT)) flags |= GNUTLS_POST_HANDSHAKE_AUTH; #endif #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030605) if (0 != (daemon->options & MHD_USE_INSECURE_TLS_EARLY_DATA)) flags |= GNUTLS_ENABLE_EARLY_DATA; #endif connection->tls_state = MHD_TLS_CONN_INIT; MHD_set_https_callbacks (connection); if ((GNUTLS_E_SUCCESS != gnutls_init (&connection->tls_session, flags)) || (GNUTLS_E_SUCCESS != gnutls_priority_set (connection->tls_session, daemon->priority_cache))) { if (NULL != connection->tls_session) gnutls_deinit (connection->tls_session); MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); if (NULL != connection->addr) free (connection->addr); free (connection); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise TLS session.\n")); #endif #if defined(EPROTO) && (EPROTO + 0 != 0) errno = EPROTO; #endif return NULL; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030200) if (! daemon->disable_alpn) { static const char prt1[] = "http/1.1"; /* Registered code for HTTP/1.1 */ static const char prt2[] = "http/1.0"; /* Registered code for HTTP/1.0 */ static const gnutls_datum_t prts[2] = { {_MHD_DROP_CONST (prt1), MHD_STATICSTR_LEN_ (prt1)}, {_MHD_DROP_CONST (prt2), MHD_STATICSTR_LEN_ (prt2)} }; if (GNUTLS_E_SUCCESS != gnutls_alpn_set_protocols (connection->tls_session, prts, sizeof(prts) / sizeof(prts[0]), 0 /* | GNUTLS_ALPN_SERVER_PRECEDENCE */)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set ALPN protocols.\n")); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } } #endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */ gnutls_session_set_ptr (connection->tls_session, connection); switch (daemon->cred_type) { /* set needed credentials for certificate authentication. */ case GNUTLS_CRD_CERTIFICATE: gnutls_credentials_set (connection->tls_session, GNUTLS_CRD_CERTIFICATE, daemon->x509_cred); break; case GNUTLS_CRD_PSK: gnutls_credentials_set (connection->tls_session, GNUTLS_CRD_PSK, daemon->psk_cred); gnutls_psk_set_server_credentials_function (daemon->psk_cred, &psk_gnutls_adapter); break; case GNUTLS_CRD_ANON: case GNUTLS_CRD_SRP: case GNUTLS_CRD_IA: default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to setup TLS credentials: " \ "unknown credential type %d.\n"), daemon->cred_type); #endif gnutls_deinit (connection->tls_session); MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); if (NULL != connection->addr) free (connection->addr); free (connection); MHD_PANIC (_ ("Unknown credential type.\n")); #if defined(EINVAL) && (EINVAL + 0 != 0) errno = EINVAL; #endif return NULL; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (connection->tls_session, (int) (client_socket)); #else /* GnuTLS before 3.1.9 or Win x64 */ gnutls_transport_set_ptr (connection->tls_session, (gnutls_transport_ptr_t) \ (intptr_t) client_socket); #endif /* GnuTLS before 3.1.9 or Win x64 */ #ifdef MHD_TLSLIB_NEED_PUSH_FUNC gnutls_transport_set_push_function (connection->tls_session, MHD_tls_push_func_); #endif /* MHD_TLSLIB_NEED_PUSH_FUNC */ if (daemon->https_mem_trust) gnutls_certificate_server_set_request (connection->tls_session, GNUTLS_CERT_REQUEST); #else /* ! HTTPS_SUPPORT */ MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); free (connection->addr); free (connection); MHD_PANIC (_ ("TLS connection on non-TLS daemon.\n")); #if 0 /* Unreachable code */ eno = EINVAL; return NULL; #endif #endif /* ! HTTPS_SUPPORT */ } return connection; } #ifdef MHD_USE_THREADS /** * Close prepared, but not yet processed connection. * @param daemon the daemon * @param connection the connection to close */ static void new_connection_close_ (struct MHD_Daemon *daemon, struct MHD_Connection *connection) { mhd_assert (connection->daemon == daemon); mhd_assert (! connection->in_cleanup); mhd_assert (NULL == connection->next); mhd_assert (NULL == connection->nextX); #ifdef EPOLL_SUPPORT mhd_assert (NULL == connection->nextE); #endif /* EPOLL_SUPPORT */ #ifdef HTTPS_SUPPORT if (NULL != connection->tls_session) { mhd_assert (0 != (daemon->options & MHD_USE_TLS)); gnutls_deinit (connection->tls_session); } #endif /* HTTPS_SUPPORT */ MHD_socket_close_chk_ (connection->socket_fd); MHD_ip_limit_del (daemon, connection->addr, connection->addr_len); if (NULL != connection->addr) free (connection->addr); free (connection); } #endif /* MHD_USE_THREADS */ /** * Finally insert the new connection to the list of connections * served by the daemon and start processing. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon that manages the connection * @param connection the newly created connection * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result new_connection_process_ (struct MHD_Daemon *daemon, struct MHD_Connection *connection) { int eno = 0; mhd_assert (connection->daemon == daemon); #ifdef MHD_USE_THREADS /* Function manipulate connection and timeout DL-lists, * must be called only within daemon thread. */ mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ /* Allocate memory pool in the processing thread so * intensively used memory area is allocated in "good" * (for the thread) memory region. It is important with * NUMA and/or complex cache hierarchy. */ connection->pool = MHD_pool_create (daemon->pool_size); if (NULL == connection->pool) { /* 'pool' creation failed */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif #if defined(ENOMEM) && (ENOMEM + 0 != 0) eno = ENOMEM; #endif (void) 0; /* Mute possible compiler warning */ } else { /* 'pool' creation succeed */ MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); /* Firm check under lock. */ if (daemon->connections >= daemon->connection_limit) { /* Connections limit */ MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Server reached connection limit. " "Closing inbound connection.\n")); #endif #if defined(ENFILE) && (ENFILE + 0 != 0) eno = ENFILE; #endif (void) 0; /* Mute possible compiler warning */ } else { /* Have space for new connection */ daemon->connections++; DLL_insert (daemon->connections_head, daemon->connections_tail, connection); if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); } MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); MHD_connection_set_initial_state_ (connection); if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, connection, &connection->socket_context, MHD_CONNECTION_NOTIFY_STARTED); #ifdef MHD_USE_THREADS if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon)); if (! MHD_create_named_thread_ (&connection->tid, "MHD-connection", daemon->thread_stack_size, &thread_main_handle_connection, connection)) { eno = errno; #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == eno) MHD_DLOG (daemon, _ ("Failed to create a new thread because it would " "have exceeded the system limit on the number of " "threads or no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create a thread: %s\n"), MHD_strerror_ (eno)); #endif /* HAVE_MESSAGES */ } else /* New thread has been created successfully */ return MHD_YES; /* *** Function success exit point *** */ } else #else /* ! MHD_USE_THREADS */ if (1) #endif /* ! MHD_USE_THREADS */ { /* No 'thread-per-connection' */ #ifdef MHD_USE_THREADS connection->tid = daemon->tid; #endif /* MHD_USE_THREADS */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 == (daemon->options & MHD_USE_TURBO)) { struct epoll_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET | EPOLLRDHUP; event.data.ptr = connection; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } else { /* 'socket_fd' has been added to 'epool' */ connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET; return MHD_YES; /* *** Function success exit point *** */ } } else { connection->epoll_state |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY | MHD_EPOLL_STATE_IN_EREADY_EDLL; EDLL_insert (daemon->eready_head, daemon->eready_tail, connection); return MHD_YES; /* *** Function success exit point *** */ } } else /* No 'epoll' */ #endif /* EPOLL_SUPPORT */ return MHD_YES; /* *** Function success exit point *** */ } /* ** Below is a cleanup path ** */ if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, connection, &connection->socket_context, MHD_CONNECTION_NOTIFY_CLOSED); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); daemon->connections--; MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); } MHD_pool_destroy (connection->pool); } /* Free resources allocated before the call of this functions */ #ifdef HTTPS_SUPPORT if (NULL != connection->tls_session) gnutls_deinit (connection->tls_session); #endif /* HTTPS_SUPPORT */ MHD_ip_limit_del (daemon, connection->addr, connection->addr_len); if (NULL != connection->addr) free (connection->addr); MHD_socket_close_chk_ (connection->socket_fd); free (connection); if (0 != eno) errno = eno; #ifdef EINVAL else errno = EINVAL; #endif /* EINVAL */ return MHD_NO; /* *** Function failure exit point *** */ } /** * Add another client connection to the set of connections * managed by MHD. This API is usually not needed (since * MHD will accept inbound connections on the server socket). * Use this API in special cases, for example if your HTTP * server is behind NAT and needs to connect out to the * HTTP client. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @param external_add perform additional operations needed due * to the application calling us directly * @param non_blck indicate that socket in non-blocking mode * @param sk_spipe_supprs indicate that the @a client_socket has * set SIGPIPE suppression * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. malloc failed, etc). * The socket will be closed in any case; 'errno' is * set to indicate further details about the error. */ static enum MHD_Result internal_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip) { struct MHD_Connection *connection; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* Direct add to master daemon could never happen. */ mhd_assert (NULL == daemon->worker_pool); #endif if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (client_socket, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("New connection socket descriptor (%d) is not less " \ "than FD_SETSIZE (%d).\n"), (int) client_socket, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return MHD_NO; } if (MHD_D_IS_USING_EPOLL_ (daemon) && (! non_blck) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Epoll mode supports only non-blocking sockets\n")); #endif MHD_socket_close_chk_ (client_socket); #if defined(EINVAL) && (EINVAL + 0 != 0) errno = EINVAL; #endif return MHD_NO; } connection = new_connection_prepare_ (daemon, client_socket, addr, addrlen, external_add, non_blck, sk_spipe_supprs, sk_is_nonip); if (NULL == connection) return MHD_NO; if ((external_add) && MHD_D_IS_THREAD_SAFE_ (daemon)) { /* Connection is added externally and MHD is thread safe mode. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); DLL_insert (daemon->new_connections_head, daemon->new_connections_tail, connection); daemon->have_new = true; MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); /* The rest of connection processing must be handled in * the daemon thread. */ if ((MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "n"))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal new connection via inter-thread " \ "communication channel.\n")); #endif } return MHD_YES; } return new_connection_process_ (daemon, connection); } static void new_connections_list_process_ (struct MHD_Daemon *daemon) { struct MHD_Connection *local_head; struct MHD_Connection *local_tail; mhd_assert (daemon->have_new); mhd_assert (MHD_D_IS_THREAD_SAFE_ (daemon)); /* Detach DL-list of new connections from the daemon for * following local processing. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); mhd_assert (NULL != daemon->new_connections_head); local_head = daemon->new_connections_head; local_tail = daemon->new_connections_tail; daemon->new_connections_head = NULL; daemon->new_connections_tail = NULL; daemon->have_new = false; MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); (void) local_head; /* Mute compiler warning */ /* Process new connections in FIFO order. */ do { struct MHD_Connection *c; /**< Currently processed connection */ c = local_tail; DLL_remove (local_head, local_tail, c); mhd_assert (daemon == c->daemon); if (MHD_NO == new_connection_process_ (daemon, c)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to start serving new connection.\n")); #endif (void) 0; } } while (NULL != local_tail); } /** * Internal version of ::MHD_suspend_connection(). * * @remark In thread-per-connection mode: can be called from any thread, * in any other mode: to be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the connection to suspend */ void internal_suspend_connection_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; mhd_assert (NULL == daemon->worker_pool); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (connection->resuming) { /* suspending again while we didn't even complete resuming yet */ connection->resuming = false; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif return; } if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); mhd_assert (! connection->suspended); DLL_insert (daemon->suspended_connections_head, daemon->suspended_connections_tail, connection); connection->suspended = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_remove (daemon->eready_head, daemon->eready_tail, connection); connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, connection->socket_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET); } connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED; } #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * Suspend handling of network data for a given connection. * This can be used to dequeue a connection from MHD's event loop * (not applicable to thread-per-connection!) for a while. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that a resumed * connection is immediately processed by MHD. * * Suspended connections continue to count against the total number of * connections allowed (per daemon, as well as per IP, if such limits * are set). Suspended connections will NOT time out; timeouts will * restart when the connection handling is resumed. While a * connection is suspended, MHD will not detect disconnects by the * client. * * The only safe way to call this function is to call it from the * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback. * * Finally, it is an API violation to call #MHD_stop_daemon while * having suspended connections (this will at least create memory and * socket leaks or lead to undefined behavior). You must explicitly * resume all connections before stopping the daemon. * * @param connection the connection to suspend * * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN void MHD_suspend_connection (struct MHD_Connection *connection) { struct MHD_Daemon *const daemon = connection->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) MHD_PANIC (_ ("Cannot suspend connections without " \ "enabling MHD_ALLOW_SUSPEND_RESUME!\n")); #ifdef UPGRADE_SUPPORT if (NULL != connection->urh) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error: connection scheduled for \"upgrade\" cannot " \ "be suspended.\n")); #endif /* HAVE_MESSAGES */ return; } #endif /* UPGRADE_SUPPORT */ internal_suspend_connection_ (connection); } /** * Resume handling of network data for suspended connection. It is * safe to resume a suspended connection at any time. Calling this * function on a connection that was not previously suspended will * result in undefined behavior. * * If you are using this function in "external" sockets polling mode, you must * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before * again calling #MHD_get_fdset()), as otherwise the change may not be * reflected in the set returned by #MHD_get_fdset() and you may end up * with a connection that is stuck until the next network activity. * * @param connection the connection to resume */ _MHD_EXTERN void MHD_resume_connection (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) MHD_PANIC (_ ("Cannot resume connections without enabling " \ "MHD_ALLOW_SUSPEND_RESUME!\n")); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif connection->resuming = true; daemon->resuming = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "r")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume via inter-thread " \ "communication channel.\n")); #endif } } #ifdef UPGRADE_SUPPORT /** * Mark upgraded connection as closed by application. * * The @a connection pointer must not be used after call of this function * as it may be freed in other thread immediately. * @param connection the upgraded connection to mark as closed by application */ void MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection) { /* Cache 'daemon' here to avoid data races */ struct MHD_Daemon *const daemon = connection->daemon; #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ mhd_assert (NULL != connection->urh); mhd_assert (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); connection->urh->was_closed = true; connection->resuming = true; daemon->resuming = true; MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "r")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume via " \ "inter-thread communication channel.\n")); #endif } } #endif /* UPGRADE_SUPPORT */ /** * Run through the suspended connections and move any that are no * longer suspended back to the active state. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon context * @return #MHD_YES if a connection was actually resumed */ static enum MHD_Result resume_suspended_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; struct MHD_Connection *prev = NULL; enum MHD_Result ret; const bool used_thr_p_c = (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert (NULL == daemon->worker_pool); mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif ret = MHD_NO; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (daemon->resuming) { prev = daemon->suspended_connections_tail; /* During shutdown check for resuming is forced. */ mhd_assert ((NULL != prev) || (daemon->shutdown) || \ (0 != (daemon->options & MHD_ALLOW_UPGRADE))); } daemon->resuming = false; while (NULL != (pos = prev)) { #ifdef UPGRADE_SUPPORT struct MHD_UpgradeResponseHandle *const urh = pos->urh; #else /* ! UPGRADE_SUPPORT */ static const void *const urh = NULL; #endif /* ! UPGRADE_SUPPORT */ prev = pos->prev; if ( (! pos->resuming) #ifdef UPGRADE_SUPPORT || ( (NULL != urh) && ( (! urh->was_closed) || (! urh->clean_ready) ) ) #endif /* UPGRADE_SUPPORT */ ) continue; ret = MHD_YES; mhd_assert (pos->suspended); DLL_remove (daemon->suspended_connections_head, daemon->suspended_connections_tail, pos); pos->suspended = false; if (NULL == urh) { DLL_insert (daemon->connections_head, daemon->connections_tail, pos); if (! used_thr_p_c) { /* Reset timeout timer on resume. */ if (0 != pos->connection_timeout_ms) pos->last_activity = MHD_monotonic_msec_counter (); if (pos->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, pos); else XDLL_insert (daemon->manual_timeout_head, daemon->manual_timeout_tail, pos); } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) MHD_PANIC ("Resumed connection was already in EREADY set.\n"); /* we always mark resumed connections as ready, as we might have missed the edge poll event during suspension */ EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL \ | MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_SUSPENDED); } #endif } #ifdef UPGRADE_SUPPORT else { /* Data forwarding was finished (for TLS connections) AND * application was closed upgraded connection. * Insert connection into cleanup list. */ if ( (NULL != daemon->notify_completed) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && (pos->rq.client_aware) ) { daemon->notify_completed (daemon->notify_completed_cls, pos, &pos->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); pos->rq.client_aware = false; } DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, pos); daemon->data_already_pending = true; } #endif /* UPGRADE_SUPPORT */ pos->resuming = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if ( (used_thr_p_c) && (MHD_NO != ret) ) { /* Wake up suspended connections. */ if (! MHD_itc_activate_ (daemon->itc, "w")) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume of connection via " \ "inter-thread communication channel.\n")); #endif } } return ret; } /** * Add another client connection to the set of connections managed by * MHD. This API is usually not needed (since MHD will accept inbound * connections on the server socket). Use this API in special cases, * for example if your HTTP server is behind NAT and needs to connect * out to the HTTP client, or if you are building a proxy. * * If you use this API in conjunction with a internal select or a * thread pool, you must set the option * #MHD_USE_ITC to ensure that the freshly added * connection is immediately processed by MHD. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. malloc() failed, etc). * The socket will be closed in any case; `errno` is * set to indicate further details about the error. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen) { bool sk_nonbl; bool sk_spipe_supprs; struct sockaddr_storage addrstorage; /* TODO: fix atomic value reading */ if ((! MHD_D_IS_THREAD_SAFE_ (daemon)) && (daemon->connection_limit <= daemon->connections)) MHD_cleanup_connections (daemon); #ifdef HAVE_MESSAGES if (MHD_D_IS_USING_THREADS_ (daemon) && (0 == (daemon->options & MHD_USE_ITC))) { MHD_DLOG (daemon, _ ("MHD_add_connection() has been called for daemon started" " without MHD_USE_ITC flag.\nDaemon will not process newly" " added connection until any activity occurs in already" " added sockets.\n")); } #endif /* HAVE_MESSAGES */ if (0 != addrlen) { if (AF_INET == addr->sa_family) { if (sizeof(struct sockaddr_in) > (size_t) addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " "incorrect 'addrlen' value.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (sizeof(struct sockaddr_in) > (size_t) addr->sa_len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " \ "non-zero value of 'sa_len' member of " \ "'struct sockaddr' which does not match 'sa_family'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ } #ifdef HAVE_INET6 if (AF_INET6 == addr->sa_family) { if (sizeof(struct sockaddr_in6) > (size_t) addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " "incorrect 'addrlen' value.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (sizeof(struct sockaddr_in6) > (size_t) addr->sa_len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " \ "non-zero value of 'sa_len' member of " \ "'struct sockaddr' which does not match 'sa_family'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (addrlen > addr->sa_len)) addrlen = (socklen_t) addr->sa_len; /* Use safest value */ #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ #endif /* HAVE_INET6 */ } if (! MHD_socket_nonblocking_ (client_socket)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on new client socket: %s\n"), MHD_socket_last_strerr_ ()); #endif sk_nonbl = false; } else sk_nonbl = true; #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = false; #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ #if defined(MHD_socket_nosignal_) if (! sk_spipe_supprs) sk_spipe_supprs = MHD_socket_nosignal_ (client_socket); if (! sk_spipe_supprs) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to suppress SIGPIPE on new client socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ #ifndef MSG_NOSIGNAL /* Application expects that SIGPIPE will be suppressed, * but suppression failed and SIGPIPE cannot be suppressed with send(). */ if (! daemon->sigpipe_blocked) { int err = MHD_socket_get_error_ (); MHD_socket_close_ (client_socket); MHD_socket_fset_error_ (err); return MHD_NO; } #endif /* MSG_NOSIGNAL */ } #endif /* MHD_socket_nosignal_ */ if ( (0 != (daemon->options & MHD_USE_TURBO)) && (! MHD_socket_noninheritable_ (client_socket)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on new client socket.\n")); #endif } /* Copy to sockaddr_storage structure to avoid alignment problems */ if (0 < addrlen) memcpy (&addrstorage, addr, (size_t) addrlen); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN addrstorage.ss_len = addrlen; /* Force set the right length */ #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) { unsigned int i; /* have a pool, try to find a pool with capacity; we use the socket as the initial offset into the pool for load balancing */ for (i = 0; i < daemon->worker_pool_size; ++i) { struct MHD_Daemon *const worker = &daemon->worker_pool[(i + (unsigned int) client_socket) % daemon->worker_pool_size]; if (worker->connections < worker->connection_limit) return internal_add_connection (worker, client_socket, &addrstorage, addrlen, true, sk_nonbl, sk_spipe_supprs, _MHD_UNKNOWN); } /* all pools are at their connection limit, must refuse */ MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return MHD_NO; } #endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */ return internal_add_connection (daemon, client_socket, &addrstorage, addrlen, true, sk_nonbl, sk_spipe_supprs, _MHD_UNKNOWN); } /** * Accept an incoming connection and create the MHD_Connection object for * it. This function also enforces policy by way of checking with the * accept policy callback. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon handle with the listen socket * @return #MHD_YES on success (connections denied by policy or due * to 'out of memory' and similar errors) are still considered * successful as far as #MHD_accept_connection() is concerned); * a return code of #MHD_NO only refers to the actual * accept() system call. */ static enum MHD_Result MHD_accept_connection (struct MHD_Daemon *daemon) { struct sockaddr_storage addrstorage; socklen_t addrlen; MHD_socket s; MHD_socket fd; bool sk_nonbl; bool sk_spipe_supprs; bool sk_cloexec; enum MHD_tristate sk_non_ip; #if defined(_DEBUG) && defined (USE_ACCEPT4) const bool use_accept4 = ! daemon->avoid_accept4; #elif defined (USE_ACCEPT4) static const bool use_accept4 = true; #else /* ! USE_ACCEPT4 && ! _DEBUG */ static const bool use_accept4 = false; #endif /* ! USE_ACCEPT4 && ! _DEBUG */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_fd)) || (daemon->was_quiesced) ) return MHD_NO; addrlen = (socklen_t) sizeof (addrstorage); memset (&addrstorage, 0, (size_t) addrlen); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN addrstorage.ss_len = addrlen; #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ /* Initialise with default values to avoid compiler warnings */ sk_nonbl = false; sk_spipe_supprs = false; sk_cloexec = false; s = MHD_INVALID_SOCKET; #ifdef USE_ACCEPT4 if (use_accept4 && (MHD_INVALID_SOCKET != (s = accept4 (fd, (struct sockaddr *) &addrstorage, &addrlen, SOCK_CLOEXEC_OR_ZERO | SOCK_NONBLOCK_OR_ZERO | SOCK_NOSIGPIPE_OR_ZERO)))) { sk_nonbl = (SOCK_NONBLOCK_OR_ZERO != 0); #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = (SOCK_NOSIGPIPE_OR_ZERO != 0); #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ sk_cloexec = (SOCK_CLOEXEC_OR_ZERO != 0); } #endif /* USE_ACCEPT4 */ #if defined(_DEBUG) || ! defined(USE_ACCEPT4) if (! use_accept4 && (MHD_INVALID_SOCKET != (s = accept (fd, (struct sockaddr *) &addrstorage, &addrlen)))) { #ifdef MHD_ACCEPT_INHERIT_NONBLOCK sk_nonbl = daemon->listen_nonblk; #else /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ sk_nonbl = false; #endif /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = false; #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ sk_cloexec = false; } #endif /* _DEBUG || !USE_ACCEPT4 */ if (MHD_INVALID_SOCKET == s) { const int err = MHD_socket_get_error_ (); /* This could be a common occurrence with multiple worker threads */ if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_NO; /* can happen during shutdown */ if (MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_ (err)) return MHD_NO; /* do not print error if client just disconnected early */ #ifdef HAVE_MESSAGES if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) ) MHD_DLOG (daemon, _ ("Error accepting connection: %s\n"), MHD_socket_strerr_ (err)); #endif if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err) ) { /* system/process out of resources */ if (0 == daemon->connections) { #ifdef HAVE_MESSAGES /* Not setting 'at_limit' flag, as there is no way it would ever be cleared. Instead trying to produce bit fat ugly warning. */ MHD_DLOG (daemon, _ ("Hit process or system resource limit at FIRST " \ "connection. This is really bad as there is no sane " \ "way to proceed. Will try busy waiting for system " \ "resources to become magically available.\n")); #endif } else { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif daemon->at_limit = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Hit process or system resource limit at %u " \ "connections, temporarily suspending accept(). " \ "Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"), (unsigned int) daemon->connections); #endif } } return MHD_NO; } sk_non_ip = daemon->listen_is_unix; if (0 >= addrlen) { #ifdef HAVE_MESSAGES if (_MHD_NO != daemon->listen_is_unix) MHD_DLOG (daemon, _ ("Accepted socket has zero-length address. " "Processing the new socket as a socket with " \ "unknown type.\n")); #endif addrlen = 0; sk_non_ip = _MHD_YES; /* IP-type addresses have non-zero length */ } if (((socklen_t) sizeof (addrstorage)) < addrlen) { /* Should not happen as 'sockaddr_storage' must be large enough to * store any address supported by the system. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Accepted socket address is larger than expected by " \ "system headers. Processing the new socket as a socket with " \ "unknown type.\n")); #endif addrlen = 0; sk_non_ip = _MHD_YES; /* IP-type addresses must fit */ } if (! sk_nonbl && ! MHD_socket_nonblocking_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on incoming connection " \ "socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } else sk_nonbl = true; if (! sk_cloexec && ! MHD_socket_noninheritable_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on incoming connection " \ "socket.\n")); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } #if defined(MHD_socket_nosignal_) if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to suppress SIGPIPE on incoming connection " \ "socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ #ifndef MSG_NOSIGNAL /* Application expects that SIGPIPE will be suppressed, * but suppression failed and SIGPIPE cannot be suppressed with send(). */ if (! daemon->sigpipe_blocked) { (void) MHD_socket_close_ (s); return MHD_NO; } #endif /* MSG_NOSIGNAL */ } else sk_spipe_supprs = true; #endif /* MHD_socket_nosignal_ */ #ifdef HAVE_MESSAGES #if _MHD_DEBUG_CONNECT MHD_DLOG (daemon, _ ("Accepted connection on socket %d\n"), s); #endif #endif (void) internal_add_connection (daemon, s, &addrstorage, addrlen, false, sk_nonbl, sk_spipe_supprs, sk_non_ip); return MHD_YES; } /** * Free resources associated with all closed connections. * (destroy responses, free buffers, etc.). All closed * connections are kept in the "cleanup" doubly-linked list. * @remark To be called only from thread that * process daemon's select()/poll()/etc. * * @param daemon daemon to clean up */ static void MHD_cleanup_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif while (NULL != (pos = daemon->cleanup_tail)) { DLL_remove (daemon->cleanup_head, daemon->cleanup_tail, pos); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (! pos->thread_joined) && (! MHD_thread_handle_ID_join_thread_ (pos->tid)) ) MHD_PANIC (_ ("Failed to join a thread.\n")); #endif #ifdef UPGRADE_SUPPORT cleanup_upgraded_connection (pos); #endif /* UPGRADE_SUPPORT */ MHD_pool_destroy (pos->pool); #ifdef HTTPS_SUPPORT if (NULL != pos->tls_session) gnutls_deinit (pos->tls_session); #endif /* HTTPS_SUPPORT */ /* clean up the connection */ if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, pos, &pos->socket_context, MHD_CONNECTION_NOTIFY_CLOSED); MHD_ip_limit_del (daemon, pos->addr, pos->addr_len); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_remove (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } if ( (-1 != daemon->epoll_fd) && (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) ) { /* epoll documentation suggests that closing a FD automatically removes it from the epoll set; however, this is not true as if we fail to do manually remove it, we are still seeing an event for this fd in epoll, causing grief (use-after-free...) --- at least on my system. */ if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, pos->socket_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET); } } #endif if (NULL != pos->rp.response) { MHD_destroy_response (pos->rp.response); pos->rp.response = NULL; } if (MHD_INVALID_SOCKET != pos->socket_fd) MHD_socket_close_chk_ (pos->socket_fd); if (NULL != pos->addr) free (pos->addr); free (pos); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif daemon->connections--; daemon->at_limit = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * Obtain timeout value for polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout64(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to query for timeout * @param[out] timeout set to the timeout (in milliseconds) * @return #MHD_YES on success, #MHD_NO if timeouts are * not used and no data processing is pending. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout) { uint64_t t64; if (MHD_NO == MHD_get_timeout64 (daemon, &t64)) return MHD_NO; #if SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG if (ULLONG_MAX <= t64) *timeout = ULLONG_MAX; else #endif /* SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG */ *timeout = (MHD_UNSIGNED_LONG_LONG) t64; return MHD_YES; } /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to query for timeout * @param[out] timeout64 the pointer to the variable to be set to the * timeout (in milliseconds) * @return #MHD_YES if timeout value has been set, * #MHD_NO if timeouts are not used and no data processing is pending. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout64 (struct MHD_Daemon *daemon, uint64_t *timeout64) { uint64_t earliest_deadline; struct MHD_Connection *pos; struct MHD_Connection *earliest_tmot_conn; /**< the connection with earliest timeout */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Illegal call to MHD_get_timeout.\n")); #endif return MHD_NO; } if (daemon->data_already_pending || (NULL != daemon->cleanup_head) || daemon->resuming || daemon->have_new || daemon->shutdown) { /* Some data or connection statuses already waiting to be processed. */ *timeout64 = 0; return MHD_YES; } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && ((NULL != daemon->eready_head) #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) || (NULL != daemon->eready_urh_head) #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ ) ) { /* Some connection(s) already have some data pending. */ *timeout64 = 0; return MHD_YES; } #endif /* EPOLL_SUPPORT */ earliest_tmot_conn = NULL; earliest_deadline = 0; /* mute compiler warning */ /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */ pos = daemon->normal_timeout_tail; if ( (NULL != pos) && (0 != pos->connection_timeout_ms) ) { earliest_tmot_conn = pos; earliest_deadline = pos->last_activity + pos->connection_timeout_ms; } for (pos = daemon->manual_timeout_tail; NULL != pos; pos = pos->prevX) { if (0 != pos->connection_timeout_ms) { if ( (NULL == earliest_tmot_conn) || (earliest_deadline - pos->last_activity > pos->connection_timeout_ms) ) { earliest_tmot_conn = pos; earliest_deadline = pos->last_activity + pos->connection_timeout_ms; } } } if (NULL != earliest_tmot_conn) { *timeout64 = connection_get_wait (earliest_tmot_conn); return MHD_YES; } return MHD_NO; } #if defined(HAVE_POLL) || defined(EPOLL_SUPPORT) /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * that external polling function must wait for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int64_t MHD_get_timeout64s (struct MHD_Daemon *daemon) { uint64_t utimeout; if (MHD_NO == MHD_get_timeout64 (daemon, &utimeout)) return -1; if (INT64_MAX < utimeout) return INT64_MAX; return (int64_t) utimeout; } /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * (capped at INT_MAX) that external polling function must wait * for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int MHD_get_timeout_i (struct MHD_Daemon *daemon) { #if SIZEOF_INT >= SIZEOF_INT64_T return MHD_get_timeout64s (daemon); #else /* SIZEOF_INT < SIZEOF_INT64_T */ const int64_t to64 = MHD_get_timeout64s (daemon); if (INT_MAX >= to64) return (int) to64; return INT_MAX; #endif /* SIZEOF_INT < SIZEOF_INT64_T */ } /** * Obtain timeout value for polling function for this daemon. * @remark To be called only from the thread that processes * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @param max_timeout the maximum return value (in milliseconds), * ignored if set to '-1' * @return timeout value in milliseconds or -1 if no timeout is expected. */ static int64_t get_timeout_millisec_ (struct MHD_Daemon *daemon, int32_t max_timeout) { uint64_t d_timeout; mhd_assert (0 <= max_timeout || -1 == max_timeout); if (0 == max_timeout) return 0; if (MHD_NO == MHD_get_timeout64 (daemon, &d_timeout)) return max_timeout; if ((0 < max_timeout) && ((uint64_t) max_timeout < d_timeout)) return max_timeout; if (INT64_MAX <= d_timeout) return INT64_MAX; return (int64_t) d_timeout; } /** * Obtain timeout value for polling function for this daemon. * @remark To be called only from the thread that processes * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @param max_timeout the maximum return value (in milliseconds), * ignored if set to '-1' * @return timeout value in milliseconds, capped to INT_MAX, or * -1 if no timeout is expected. */ static int get_timeout_millisec_int (struct MHD_Daemon *daemon, int32_t max_timeout) { int64_t res; res = get_timeout_millisec_ (daemon, max_timeout); #if SIZEOF_INT < SIZEOF_INT64_T if (INT_MAX <= res) return INT_MAX; #endif /* SIZEOF_INT < SIZEOF_INT64_T */ return (int) res; } #endif /* HAVE_POLL || EPOLL_SUPPORT */ /** * Internal version of #MHD_run_from_select(). * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param fd_setsize value of FD_SETSIZE used when fd_sets were created * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ static enum MHD_Result internal_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, int fd_setsize) { MHD_socket ds; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); mhd_assert (0 < fd_setsize); (void) fd_setsize; /* Mute compiler warning */ #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ mhd_assert (((int) FD_SETSIZE) <= fd_setsize); fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /* Clear ITC to avoid spinning select */ /* Do it before any other processing so new signals will trigger select again and will be processed */ if (MHD_ITC_IS_VALID_ (daemon->itc)) { /* Have ITC */ bool need_to_clear_itc = true; /* ITC is always non-blocking, it is safe to clear even if ITC not activated */ if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (MHD_itc_r_fd_ (daemon->itc), NULL, fd_setsize)) need_to_clear_itc = FD_ISSET (MHD_itc_r_fd_ (daemon->itc), \ (fd_set *) _MHD_DROP_CONST (read_fd_set)); /* Skip clearing, if not needed */ if (need_to_clear_itc) MHD_itc_clear_ (daemon->itc); } /* Reset. New value will be set when connections are processed. */ /* Note: no-op for thread-per-connection as it is always false in that mode. */ daemon->data_already_pending = false; /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); /* select connection thread handling type */ ds = daemon->listen_fd; if ( (MHD_INVALID_SOCKET != ds) && (! daemon->was_quiesced) ) { bool need_to_accept; if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (ds, NULL, fd_setsize)) need_to_accept = FD_ISSET (ds, (fd_set *) _MHD_DROP_CONST (read_fd_set)); else /* Cannot check whether new connection are pending */ need_to_accept = daemon->listen_nonblk; /* Try to accept if non-blocking */ if (need_to_accept) (void) MHD_accept_connection (daemon); } if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* do not have a thread per connection, process all connections now */ struct MHD_Connection *pos; for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) { MHD_socket cs; bool r_ready; bool w_ready; bool has_err; cs = pos->socket_fd; if (MHD_INVALID_SOCKET == cs) continue; if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (cs, NULL, fd_setsize)) { r_ready = FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (read_fd_set)); w_ready = FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (write_fd_set)); has_err = (NULL != except_fd_set) && FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (except_fd_set)); } else { /* Cannot check the real readiness */ r_ready = pos->sk_nonblck; w_ready = r_ready; has_err = false; } call_handlers (pos, r_ready, w_ready, has_err); } } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /* handle upgraded HTTPS connections */ for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { urhn = urh->prev; /* update urh state based on select() output */ urh_from_fdset (urh, read_fd_set, write_fd_set, except_fd_set, fd_setsize); /* call generic forwarding function for passing data */ process_urh (urh); /* Finished forwarding? */ if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) { MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* Resuming will move connection to cleanup list. */ MHD_resume_connection (urh->connection); } } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ MHD_cleanup_connections (daemon); return MHD_YES; } #undef MHD_run_from_select /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This function specifies FD_SETSIZE used when provided fd_sets were * created. It is important on platforms where FD_SETSIZE can be * overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select2 (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, unsigned int fd_setsize) { if (MHD_D_IS_USING_POLL_ (daemon) || MHD_D_IS_USING_THREADS_ (daemon)) return MHD_NO; if ((NULL == read_fd_set) || (NULL == write_fd_set)) return MHD_NO; #ifdef HAVE_MESSAGES if (NULL == except_fd_set) { MHD_DLOG (daemon, _ ("MHD_run_from_select() called with except_fd_set " "set to NULL. Such behavior is deprecated.\n")); } #endif /* HAVE_MESSAGES */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE if (0 == fd_setsize) return MHD_NO; else if (((unsigned int) INT_MAX) < fd_setsize) fd_setsize = (unsigned int) INT_MAX; #ifdef HAVE_MESSAGES else if (daemon->fdset_size > ((int) fd_setsize)) { if (daemon->fdset_size_set_by_app) { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), "MHD_run_from_select2", fd_setsize, daemon->fdset_size); } else { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than FD_SETSIZE used by MHD (%d). " \ "Some socket FDs may be not processed. " \ "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), "MHD_run_from_select2", fd_setsize, daemon->fdset_size); } } #endif /* HAVE_MESSAGES */ #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (((unsigned int) FD_SETSIZE) > fd_setsize) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than fixed FD_SETSIZE value (%d) used on the " \ "platform.\n"), "MHD_run_from_select2", fd_setsize, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (MHD_D_IS_USING_EPOLL_ (daemon)) { #ifdef EPOLL_SUPPORT enum MHD_Result ret = MHD_epoll (daemon, 0); MHD_cleanup_connections (daemon); return ret; #else /* ! EPOLL_SUPPORT */ return MHD_NO; #endif /* ! EPOLL_SUPPORT */ } /* Resuming external connections when using an extern mainloop */ if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) resume_suspended_connections (daemon); return internal_run_from_select (daemon, read_fd_set, write_fd_set, except_fd_set, (int) fd_setsize); } /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * * You can use this function instead of #MHD_run if you called * `select()` on the result from #MHD_get_fdset. File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run is more efficient as MHD will * not have to call `select()` again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after `select()` returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) { return MHD_run_from_select2 (daemon, read_fd_set, write_fd_set, except_fd_set, #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size_set_by_app ? ((unsigned int) daemon->fdset_size) : ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ); } /** * Main internal select() call. Will compute select sets, call select() * and then #internal_run_from_select with the result. * * @param daemon daemon to run select() loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_select (struct MHD_Daemon *daemon, int32_t millisec) { int num_ready; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; struct timeval timeout; struct timeval *tv; int err_state; MHD_socket ls; timeout.tv_sec = 0; timeout.tv_usec = 0; if (daemon->shutdown) return MHD_NO; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); maxsock = MHD_INVALID_SOCKET; err_state = MHD_NO; if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) millisec = 0; if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* single-threaded, go over everything */ if (MHD_NO == internal_get_fdset2 (daemon, &rs, &ws, &es, &maxsock, (int) FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not obtain daemon fdsets.\n")); #endif err_state = MHD_YES; } } else { bool itc_added; /* accept only, have one thread per connection */ itc_added = false; if (MHD_ITC_IS_VALID_ (daemon->itc)) { itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), &rs, &maxsock, (int) FD_SETSIZE); if (! itc_added) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not add control inter-thread " \ "communication channel FD to fdset.\n")); #endif err_state = MHD_YES; } } if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { /* Stop listening if we are at the configured connection limit */ /* If we're at the connection limit, no point in really accepting new connections; however, make sure we do not miss the shutdown OR the termination of an existing connection; so only do this optimisation if we have a signaling ITC in place. */ if (! itc_added || ((daemon->connections < daemon->connection_limit) && ! daemon->at_limit)) { if (! MHD_add_to_fd_set_ (ls, &rs, &maxsock, (int) FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not add listen socket to fdset.\n")); #endif err_state = MHD_YES; } } } } if (MHD_NO != err_state) millisec = 0; if (0 == millisec) { timeout.tv_usec = 0; timeout.tv_sec = 0; tv = &timeout; } else { uint64_t mhd_tmo; uint64_t select_tmo; if ( (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && (MHD_NO != MHD_get_timeout64 (daemon, &mhd_tmo)) ) { if ( (0 < millisec) && (mhd_tmo > (uint64_t) millisec) ) select_tmo = (uint64_t) millisec; else select_tmo = mhd_tmo; tv = &timeout; /* have timeout value */ } else if (0 < millisec) { select_tmo = (uint64_t) millisec; tv = &timeout; /* have timeout value */ } else { select_tmo = 0; /* Not actually used, silent compiler warning */ tv = NULL; } if (NULL != tv) { /* have timeout value */ #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC if (select_tmo / 1000 > TIMEVAL_TV_SEC_MAX) timeout.tv_sec = TIMEVAL_TV_SEC_MAX; else #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (select_tmo / 1000); timeout.tv_usec = ((uint16_t) (select_tmo % 1000)) * ((int32_t) 1000); } } num_ready = MHD_SYS_select_ (maxsock + 1, &rs, &ws, &es, tv); if (daemon->shutdown) return MHD_NO; if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return (MHD_NO == err_state) ? MHD_YES : MHD_NO; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("select failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } if (MHD_NO != internal_run_from_select (daemon, &rs, &ws, &es, (int) FD_SETSIZE)) return (MHD_NO == err_state) ? MHD_YES : MHD_NO; return MHD_NO; } #ifdef HAVE_POLL /** * Process all of our connections and possibly the server * socket using poll(). * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll_all (struct MHD_Daemon *daemon, int32_t millisec) { unsigned int num_connections; struct MHD_Connection *pos; struct MHD_Connection *prev; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) ) millisec = 0; /* count number of connections and thus determine poll set size */ num_connections = 0; for (pos = daemon->connections_head; NULL != pos; pos = pos->next) num_connections++; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_head; NULL != urh; urh = urh->next) num_connections += 2; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ { unsigned int i; int timeout; unsigned int poll_server; int poll_listen; int poll_itc_idx; struct pollfd *p; MHD_socket ls; p = MHD_calloc_ ((2 + (size_t) num_connections), sizeof (struct pollfd)); if (NULL == p) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif return MHD_NO; } poll_server = 0; poll_listen = -1; if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) && (daemon->connections < daemon->connection_limit) && (! daemon->at_limit) ) { /* only listen if we are not at the connection limit */ p[poll_server].fd = ls; p[poll_server].events = POLLIN; p[poll_server].revents = 0; poll_listen = (int) poll_server; poll_server++; } poll_itc_idx = -1; if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc); p[poll_server].events = POLLIN; p[poll_server].revents = 0; poll_itc_idx = (int) poll_server; poll_server++; } timeout = get_timeout_millisec_int (daemon, millisec); i = 0; for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) { p[poll_server + i].fd = pos->socket_fd; switch (pos->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_WRITE: p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_PROCESS: p[poll_server + i].events |= MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_CLEANUP: timeout = 0; /* clean up "pos" immediately */ break; } i++; } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) { urh_to_pollfd (urh, &(p[poll_server + i])); i += 2; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (0 == poll_server + num_connections) { free (p); return MHD_YES; } if (MHD_sys_poll_ (p, poll_server + num_connections, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) { free (p); return MHD_YES; } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("poll failed: %s\n"), MHD_socket_strerr_ (err)); #endif free (p); return MHD_NO; } /* handle ITC FD */ /* do it before any other processing so new signals will be processed in next loop */ if ( (-1 != poll_itc_idx) && (0 != (p[poll_itc_idx].revents & POLLIN)) ) MHD_itc_clear_ (daemon->itc); /* handle shutdown */ if (daemon->shutdown) { free (p); return MHD_NO; } /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); /* handle 'listen' FD */ if ( (-1 != poll_listen) && (0 != (p[poll_listen].revents & POLLIN)) ) (void) MHD_accept_connection (daemon); /* Reset. New value will be set when connections are processed. */ daemon->data_already_pending = false; i = 0; prev = daemon->connections_tail; while (NULL != (pos = prev)) { prev = pos->prev; /* first, sanity checks */ if (i >= num_connections) break; /* connection list changed somehow, retry later ... */ if (p[poll_server + i].fd != pos->socket_fd) continue; /* fd mismatch, something else happened, retry later ... */ call_handlers (pos, 0 != (p[poll_server + i].revents & POLLIN), 0 != (p[poll_server + i].revents & POLLOUT), 0 != (p[poll_server + i].revents & MHD_POLL_REVENTS_ERR_DISC)); i++; } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { if (i >= num_connections) break; /* connection list changed somehow, retry later ... */ /* Get next connection here as connection can be removed * from 'daemon->urh_head' list. */ urhn = urh->prev; /* Check for fd mismatch. FIXME: required for safety? */ if ((p[poll_server + i].fd != urh->connection->socket_fd) || (p[poll_server + i + 1].fd != urh->mhd.socket)) break; urh_from_pollfd (urh, &p[poll_server + i]); i += 2; process_urh (urh); /* Finished forwarding? */ if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) { /* MHD_connection_finish_forward_() will remove connection from * 'daemon->urh_head' list. */ MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* If 'urh->was_closed' already was set to true, connection will be * moved immediately to cleanup list. Otherwise connection * will stay in suspended list until 'urh' will be marked * with 'was_closed' by application. */ MHD_resume_connection (urh->connection); } } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ free (p); } return MHD_YES; } /** * Process only the listen socket using poll(). * * @param daemon daemon to run poll loop for * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll_listen_socket (struct MHD_Daemon *daemon, int may_block) { struct pollfd p[2]; int timeout; unsigned int poll_count; int poll_listen; int poll_itc_idx; MHD_socket ls; mhd_assert (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)); mhd_assert (MHD_thread_handle_ID_is_current_thread_ (daemon->tid)); memset (&p, 0, sizeof (p)); poll_count = 0; poll_listen = -1; poll_itc_idx = -1; if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { p[poll_count].fd = ls; p[poll_count].events = POLLIN; p[poll_count].revents = 0; poll_listen = (int) poll_count; poll_count++; } if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc); p[poll_count].events = POLLIN; p[poll_count].revents = 0; poll_itc_idx = (int) poll_count; poll_count++; } if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) (void) resume_suspended_connections (daemon); if (MHD_NO == may_block) timeout = 0; else timeout = -1; if (0 == poll_count) return MHD_YES; if (MHD_sys_poll_ (p, poll_count, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("poll failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } if ( (0 <= poll_itc_idx) && (0 != (p[poll_itc_idx].revents & POLLIN)) ) MHD_itc_clear_ (daemon->itc); /* handle shutdown */ if (daemon->shutdown) return MHD_NO; /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); if ( (0 <= poll_listen) && (0 != (p[poll_listen].revents & POLLIN)) ) (void) MHD_accept_connection (daemon); return MHD_YES; } #endif #ifdef HAVE_POLL /** * Do poll()-based processing. * * @param daemon daemon to run poll()-loop for * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll (struct MHD_Daemon *daemon, int may_block) { if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) return MHD_poll_all (daemon, may_block ? -1 : 0); return MHD_poll_listen_socket (daemon, may_block); } #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT /** * How many events to we process at most per epoll() call? Trade-off * between required stack-size and number of system calls we have to * make; 128 should be way enough to avoid more than one system call * for most scenarios, and still be moderate in stack size * consumption. Embedded systems might want to choose a smaller value * --- but why use epoll() on such a system in the first place? */ #define MAX_EVENTS 128 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Checks whether @a urh has some data to process. * * @param urh upgrade handler to analyse * @return 'true' if @a urh has some data to process, * 'false' otherwise */ static bool is_urh_ready (struct MHD_UpgradeResponseHandle *const urh) { const struct MHD_Connection *const connection = urh->connection; if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) return false; if (connection->daemon->shutdown) return true; if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) & urh->app.celi)) || (connection->tls_read_ready) ) && (urh->in_buffer_used < urh->in_buffer_size) ) return true; if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) & urh->mhd.celi)) || urh->was_closed) && (urh->out_buffer_used < urh->out_buffer_size) ) return true; if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && (urh->out_buffer_used > 0) ) return true; if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && (urh->in_buffer_used > 0) ) return true; return false; } /** * Do epoll()-based processing for TLS connections that have been * upgraded. This requires a separate epoll() invocation as we * cannot use the `struct MHD_Connection` data structures for * the `union epoll_data` in this case. * @remark To be called only from thread that process * daemon's select()/poll()/etc. */ static enum MHD_Result run_epoll_for_upgrade (struct MHD_Daemon *daemon) { struct epoll_event events[MAX_EVENTS]; int num_events; struct MHD_UpgradeResponseHandle *pos; struct MHD_UpgradeResponseHandle *prev; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ num_events = MAX_EVENTS; while (0 != num_events) { unsigned int i; /* update event masks */ num_events = epoll_wait (daemon->epoll_upgrade_fd, events, MAX_EVENTS, 0); if (-1 == num_events) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_wait failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } for (i = 0; i < (unsigned int) num_events; i++) { struct UpgradeEpollHandle *const ueh = events[i].data.ptr; struct MHD_UpgradeResponseHandle *const urh = ueh->urh; bool new_err_state = false; if (urh->clean_ready) continue; /* Update ueh state based on what is ready according to epoll() */ if (0 != (events[i].events & EPOLLIN)) { ueh->celi |= MHD_EPOLL_STATE_READ_READY; } if (0 != (events[i].events & EPOLLOUT)) { ueh->celi |= MHD_EPOLL_STATE_WRITE_READY; } if (0 != (events[i].events & EPOLLHUP)) { ueh->celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; } if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) && (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) ) { /* Process new error state only one time and avoid continuously * marking this connection as 'ready'. */ ueh->celi |= MHD_EPOLL_STATE_ERROR; new_err_state = true; } if (! urh->in_eready_list) { if (new_err_state || is_urh_ready (urh)) { EDLL_insert (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = true; } } } } prev = daemon->eready_urh_tail; while (NULL != (pos = prev)) { prev = pos->prevE; process_urh (pos); if (! is_urh_ready (pos)) { EDLL_remove (daemon->eready_urh_head, daemon->eready_urh_tail, pos); pos->in_eready_list = false; } /* Finished forwarding? */ if ( (0 == pos->in_buffer_size) && (0 == pos->out_buffer_size) && (0 == pos->in_buffer_used) && (0 == pos->out_buffer_used) ) { MHD_connection_finish_forward_ (pos->connection); pos->clean_ready = true; /* If 'pos->was_closed' already was set to true, connection * will be moved immediately to cleanup list. Otherwise * connection will stay in suspended list until 'pos' will * be marked with 'was_closed' by application. */ MHD_resume_connection (pos->connection); } } return MHD_YES; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /** * Pointer-marker to distinguish ITC slot in epoll sets. */ static const char *const epoll_itc_marker = "itc_marker"; /** * Do epoll()-based processing. * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_epoll (struct MHD_Daemon *daemon, int32_t millisec) { #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) static const char *const upgrade_marker = "upgrade_ptr"; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ struct MHD_Connection *pos; struct MHD_Connection *prev; struct epoll_event events[MAX_EVENTS]; struct epoll_event event; int timeout_ms; int num_events; unsigned int i; MHD_socket ls; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) bool run_upgraded = false; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ bool need_to_accept; mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); if (-1 == daemon->epoll_fd) return MHD_NO; /* we're down! */ if (daemon->shutdown) return MHD_NO; if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) && (daemon->connections < daemon->connection_limit) && (! daemon->listen_socket_in_epoll) && (! daemon->at_limit) ) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = daemon; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, ls, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->listen_socket_in_epoll = true; } if ( (daemon->was_quiesced) && (daemon->listen_socket_in_epoll) ) { if ( (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ls, NULL)) && (ENOENT != errno) ) /* ENOENT can happen due to race with #MHD_quiesce_daemon() */ MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); daemon->listen_socket_in_epoll = false; } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if ( ( (! daemon->upgrade_fd_in_epoll) && (-1 != daemon->epoll_upgrade_fd) ) ) { event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP; event.data.ptr = _MHD_DROP_CONST (upgrade_marker); if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, daemon->epoll_upgrade_fd, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->upgrade_fd_in_epoll = true; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if ( (daemon->listen_socket_in_epoll) && ( (daemon->connections == daemon->connection_limit) || (daemon->at_limit) || (daemon->was_quiesced) ) ) { /* we're at the connection limit, disable listen socket for event loop for now */ if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ls, NULL)) MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); daemon->listen_socket_in_epoll = false; } if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) ) millisec = 0; timeout_ms = get_timeout_millisec_int (daemon, millisec); /* Reset. New value will be set when connections are processed. */ /* Note: Used mostly for uniformity here as same situation is * signaled in epoll mode by non-empty eready DLL. */ daemon->data_already_pending = false; need_to_accept = false; /* drain 'epoll' event queue; need to iterate as we get at most MAX_EVENTS in one system call here; in practice this should pretty much mean only one round, but better an extra loop here than unfair behavior... */ num_events = MAX_EVENTS; while (MAX_EVENTS == num_events) { /* update event masks */ num_events = epoll_wait (daemon->epoll_fd, events, MAX_EVENTS, timeout_ms); if (-1 == num_events) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_wait failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } for (i = 0; i < (unsigned int) num_events; i++) { /* First, check for the values of `ptr` that would indicate that this event is not about a normal connection. */ if (NULL == events[i].data.ptr) continue; /* shutdown signal! */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (upgrade_marker == events[i].data.ptr) { /* activity on an upgraded connection, we process those in a separate epoll() */ run_upgraded = true; continue; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (epoll_itc_marker == events[i].data.ptr) { /* It's OK to clear ITC here as all external conditions will be processed later. */ MHD_itc_clear_ (daemon->itc); continue; } if (daemon == events[i].data.ptr) { /* Check for error conditions on listen socket. */ /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */ if (0 == (events[i].events & (EPOLLERR | EPOLLHUP))) need_to_accept = true; continue; } /* this is an event relating to a 'normal' connection, remember the event and if appropriate mark the connection as 'eready'. */ pos = events[i].data.ptr; /* normal processing: update read/write data */ if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP))) { pos->epoll_state |= MHD_EPOLL_STATE_ERROR; if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } else { if (0 != (events[i].events & EPOLLIN)) { pos->epoll_state |= MHD_EPOLL_STATE_READ_READY; if ( ( (0 != (MHD_EVENT_LOOP_INFO_READ & pos->event_loop_info)) || (pos->read_buffer_size > pos->read_buffer_offset) ) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } if (0 != (events[i].events & EPOLLOUT)) { pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY; if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } } } } /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); if (need_to_accept) { unsigned int series_length = 0; /* Run 'accept' until it fails or daemon at limit of connections. * Do not accept more then 10 connections at once. The rest will * be accepted on next turn (level trigger is used for listen * socket). */ while ( (MHD_NO != MHD_accept_connection (daemon)) && (series_length < 10) && (daemon->connections < daemon->connection_limit) && (! daemon->at_limit) ) series_length++; } /* Handle timed-out connections; we need to do this here as the epoll mechanism won't call the 'MHD_connection_handle_idle()' on everything, as the other event loops do. As timeouts do not get an explicit event, we need to find those connections that might have timed out here. Connections with custom timeouts must all be looked at, as we do not bother to sort that (presumably very short) list. */ prev = daemon->manual_timeout_tail; while (NULL != (pos = prev)) { prev = pos->prevX; MHD_connection_handle_idle (pos); } /* Connections with the default timeout are sorted by prepending them to the head of the list whenever we touch the connection; thus it suffices to iterate from the tail until the first connection is NOT timed out */ prev = daemon->normal_timeout_tail; while (NULL != (pos = prev)) { prev = pos->prevX; MHD_connection_handle_idle (pos); if (MHD_CONNECTION_CLOSED != pos->state) break; /* sorted by timeout, no need to visit the rest! */ } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (run_upgraded || (NULL != daemon->eready_urh_head)) run_epoll_for_upgrade (daemon); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /* process events for connections */ prev = daemon->eready_tail; while (NULL != (pos = prev)) { prev = pos->prevE; call_handlers (pos, 0 != (pos->epoll_state & MHD_EPOLL_STATE_READ_READY), 0 != (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY), 0 != (pos->epoll_state & MHD_EPOLL_STATE_ERROR)); if (MHD_EPOLL_STATE_IN_EREADY_EDLL == (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED | MHD_EPOLL_STATE_IN_EREADY_EDLL))) { if ( ((MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) || ((MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) || (MHD_EVENT_LOOP_INFO_CLEANUP == pos->event_loop_info) ) { EDLL_remove (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } } } return MHD_YES; } #endif /** * Run webserver operations (without blocking unless in client callbacks). * * This method should be called by clients in combination with * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD * if epoll is used) and #MHD_get_timeout() if the client-controlled * connection polling method is used (i.e. daemon was started without * #MHD_USE_INTERNAL_POLLING_THREAD flag). * * This function is a convenience method, which is useful if the * fd_sets from #MHD_get_fdset were not directly passed to `select()`; * with this function, MHD will internally do the appropriate `select()` * call itself again. While it is acceptable to call #MHD_run (if * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should * call #MHD_run_from_select() if performance is important (as it saves an * expensive call to `select()`). * * If #MHD_get_timeout() returned #MHD_YES, than this function must be called * right after polling function returns regardless of detected activity on * the daemon's FDs. * * @param daemon daemon to run * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run (struct MHD_Daemon *daemon) { if ( (daemon->shutdown) || MHD_D_IS_USING_THREADS_ (daemon) ) return MHD_NO; (void) MHD_run_wait (daemon, 0); return MHD_YES; } /** * Run webserver operation with possible blocking. * * This function does the following: waits for any network event not more than * specified number of milliseconds, processes all incoming and outgoing data, * processes new connections, processes any timed-out connection, and does * other things required to run webserver. * Once all connections are processed, function returns. * * This function is useful for quick and simple (lazy) webserver implementation * if application needs to run a single thread only and does not have any other * network activity. * * This function calls MHD_get_timeout() internally and use returned value as * maximum wait time if it less than value of @a millisec parameter. * * It is expected that the "external" socket polling function is not used in * conjunction with this function unless the @a millisec is set to zero. * * @param daemon the daemon to run * @param millisec the maximum time in milliseconds to wait for network and * other events. Note: there is no guarantee that function * blocks for the specified amount of time. The real processing * time can be shorter (if some data or connection timeout * comes earlier) or longer (if data processing requires more * time, especially in user callbacks). * If set to '0' then function does not block and processes * only already available data (if any). * If set to '-1' then function waits for events * indefinitely (blocks until next network activity or * connection timeout). * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or some serious * unrecoverable error occurs. * @note Available since #MHD_VERSION 0x00097206 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_wait (struct MHD_Daemon *daemon, int32_t millisec) { enum MHD_Result res; if ( (daemon->shutdown) || MHD_D_IS_USING_THREADS_ (daemon) ) return MHD_NO; mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid)); if (0 > millisec) millisec = -1; #ifdef HAVE_POLL if (MHD_D_IS_USING_POLL_ (daemon)) { res = MHD_poll_all (daemon, millisec); MHD_cleanup_connections (daemon); } else #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { res = MHD_epoll (daemon, millisec); MHD_cleanup_connections (daemon); } else #endif if (1) { mhd_assert (MHD_D_IS_USING_SELECT_ (daemon)); #ifdef HAS_FD_SETSIZE_OVERRIDABLE #ifdef HAVE_MESSAGES if (daemon->fdset_size_set_by_app && (((int) FD_SETSIZE) < daemon->fdset_size)) { MHD_DLOG (daemon, _ ("MHD_run()/MHD_run_wait() called for daemon started with " \ "MHD_OPTION_APP_FD_SETSIZE option (%d). " \ "The library was compiled with smaller FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_run_from_select2() instead of MHD_run() or " \ "do not use MHD_OPTION_APP_FD_SETSIZE option.\n"), daemon->fdset_size, (int) FD_SETSIZE); } #endif /* HAVE_MESSAGES */ #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ res = MHD_select (daemon, millisec); /* MHD_select does MHD_cleanup_connections already */ } return res; } /** * Close the given connection, remove it from all of its * DLLs and move it into the cleanup queue. * @remark To be called only from thread that * process daemon's select()/poll()/etc. * * @param pos connection to move to cleanup */ static void close_connection (struct MHD_Connection *pos) { struct MHD_Daemon *daemon = pos->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { MHD_connection_mark_closed_ (pos); return; /* must let thread to do the rest */ } MHD_connection_close_ (pos, MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif mhd_assert (! pos->suspended); mhd_assert (! pos->resuming); if (pos->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, pos); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, pos); DLL_remove (daemon->connections_head, daemon->connections_tail, pos); DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, pos); daemon->data_already_pending = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Thread that runs the polling loop until the daemon * is explicitly shut down. * * @param cls `struct MHD_Deamon` to run select loop in a thread for * @return always 0 (on shutdown) */ static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ MHD_polling_thread (void *cls) { struct MHD_Daemon *daemon = cls; #ifdef HAVE_PTHREAD_SIGMASK sigset_t s_mask; int err; #endif /* HAVE_PTHREAD_SIGMASK */ MHD_thread_handle_ID_set_current_thread_ID_ (&(daemon->tid)); #ifdef HAVE_PTHREAD_SIGMASK if ((0 == sigemptyset (&s_mask)) && (0 == sigaddset (&s_mask, SIGPIPE))) { err = pthread_sigmask (SIG_BLOCK, &s_mask, NULL); } else err = errno; if (0 == err) daemon->sigpipe_blocked = true; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("Failed to block SIGPIPE on daemon thread: %s\n"), MHD_strerror_ (errno)); #endif /* HAVE_MESSAGES */ #endif /* HAVE_PTHREAD_SIGMASK */ while (! daemon->shutdown) { #ifdef HAVE_POLL if (MHD_D_IS_USING_POLL_ (daemon)) MHD_poll (daemon, MHD_YES); else #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) MHD_epoll (daemon, -1); else #endif MHD_select (daemon, -1); MHD_cleanup_connections (daemon); } /* Resume any pending for resume connections, join * all connection's threads (if any) and finally cleanup * everything. */ if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) resume_suspended_connections (daemon); close_all_connections (daemon); return (MHD_THRD_RTRN_TYPE_) 0; } #endif /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result must also still be 0-terminated. * * @param cls closure (use NULL) * @param connection handle to connection, not used * @param val value to unescape (modified in the process) * @return length of the resulting val (strlen(val) maybe * shorter afterwards due to elimination of escape sequences) */ static size_t unescape_wrapper (void *cls, struct MHD_Connection *connection, char *val) { bool broken; size_t res; (void) cls; /* Mute compiler warning. */ /* TODO: add individual parameter */ if (0 <= connection->daemon->client_discipline) return MHD_str_pct_decode_in_place_strict_ (val); res = MHD_str_pct_decode_in_place_lenient_ (val, &broken); #ifdef HAVE_MESSAGES if (broken) { MHD_DLOG (connection->daemon, _ ("The URL encoding is broken.\n")); } #endif /* HAVE_MESSAGES */ return res; } /** * Start a webserver on the given port. Variadic version of * #MHD_start_daemon_va. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if #MHD_OPTION_SOCK_ADDR or * #MHD_OPTION_LISTEN_SOCKET is provided * or #MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to @a apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...) { struct MHD_Daemon *daemon; va_list ap; va_start (ap, dh_cls); daemon = MHD_start_daemon_va (flags, port, apc, apc_cls, dh, dh_cls, ap); va_end (ap); return daemon; } /** * Stop accepting connections from the listening socket. Allows * clients to continue processing, but stops accepting new * connections. Note that the caller is responsible for closing the * returned socket; however, if MHD is run using threads (anything but * external select mode), socket will be removed from existing threads * with some delay and it must not be closed while it's in use. To make * sure that the socket is not used anymore, call #MHD_stop_daemon. * * Note that some thread modes require the caller to have passed * #MHD_USE_ITC when using this API. If this daemon is * in one of those modes and this option was not given to * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. * * @param daemon daemon to stop accepting new connections for * @return old listen socket on success, #MHD_INVALID_SOCKET if * the daemon was already not listening anymore * @ingroup specialized */ _MHD_EXTERN MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif MHD_socket ret; ret = daemon->listen_fd; if ((MHD_INVALID_SOCKET == ret) || daemon->was_quiesced) return MHD_INVALID_SOCKET; if ( (0 == (daemon->options & (MHD_USE_ITC))) && MHD_D_IS_USING_THREADS_ (daemon) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Using MHD_quiesce_daemon in this mode " \ "requires MHD_USE_ITC.\n")); #endif return MHD_INVALID_SOCKET; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) for (i = 0; i < daemon->worker_pool_size; i++) { daemon->worker_pool[i].was_quiesced = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->worker_pool[i].epoll_fd) && (daemon->worker_pool[i].listen_socket_in_epoll) ) { if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd, EPOLL_CTL_DEL, ret, NULL)) MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); daemon->worker_pool[i].listen_socket_in_epoll = false; } else #endif if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) { if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "q")) MHD_PANIC (_ ("Failed to signal quiesce via inter-thread " \ "communication channel.\n")); } } #endif daemon->was_quiesced = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_fd) && (daemon->listen_socket_in_epoll) ) { if ( (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ret, NULL)) && (ENOENT != errno) ) /* ENOENT can happen due to race with #MHD_epoll() */ MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); daemon->listen_socket_in_epoll = false; } #endif if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "q")) ) MHD_PANIC (_ ("failed to signal quiesce via inter-thread " \ "communication channel.\n")); return ret; } /** * Temporal location of the application-provided parameters/options. * Used when options are decoded from #MHD_start_deamon() parameters, but * not yet processed/applied. */ struct MHD_InterimParams_ { /** * The total number of all user options used. * * Contains number only of meaningful options, i.e. #MHD_OPTION_END and * #MHD_OPTION_ARRAY themselves are not counted, while options inside * #MHD_OPTION_ARRAY are counted. */ size_t num_opts; /** * Set to 'true' if @a fdset_size is set by application. */ bool fdset_size_set; /** * The value for #MHD_OPTION_APP_FD_SETSIZE set by application. */ int fdset_size; /** * Set to 'true' if @a listen_fd is set by application. */ bool listen_fd_set; /** * Application-provided listen socket. */ MHD_socket listen_fd; /** * Set to 'true' if @a server_addr is set by application. */ bool pserver_addr_set; /** * Application-provided struct sockaddr to bind server to. */ const struct sockaddr *pserver_addr; /** * Set to 'true' if @a server_addr_len is set by application. */ bool server_addr_len_set; /** * Applicaiton-provided the size of the memory pointed by @a server_addr. */ socklen_t server_addr_len; }; /** * Signature of the MHD custom logger function. * * @param cls closure * @param format format string * @param va arguments to the format string (fprintf-style) */ typedef void (*VfprintfFunctionPointerType)(void *cls, const char *format, va_list va); /** * Parse a list of options given as varargs. * * @param daemon the daemon to initialize * @param servaddr where to store the server's listen address * @param params the interim parameters to be assigned to * @param ap the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options_va (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, va_list ap); /** * Parse a list of options given as varargs. * * @param daemon the daemon to initialize * @param servaddr where to store the server's listen address * @param params the interim parameters to be assigned to * @param ... the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, ...) { va_list ap; enum MHD_Result ret; va_start (ap, params); ret = parse_options_va (daemon, params, ap); va_end (ap); return ret; } #ifdef HTTPS_SUPPORT /** * Type of GnuTLS priorities base string */ enum MHD_TlsPrioritiesBaseType { MHD_TLS_PRIO_BASE_LIBMHD = 0, /**< @c "@LIBMICROHTTPD" */ MHD_TLS_PRIO_BASE_SYSTEM = 1, /**< @c "@SYSTEM" */ #if GNUTLS_VERSION_NUMBER >= 0x030300 MHD_TLS_PRIO_BASE_DEFAULT, /**< Default priorities string */ #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ MHD_TLS_PRIO_BASE_NORMAL /**< @c "NORMAL */ }; static const struct _MHD_cstr_w_len MHD_TlsBasePriotities[] = { _MHD_S_STR_W_LEN ("@LIBMICROHTTPD"), _MHD_S_STR_W_LEN ("@SYSTEM"), #if GNUTLS_VERSION_NUMBER >= 0x030300 {NULL, 0}, #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ _MHD_S_STR_W_LEN ("NORMAL") }; /** * Initialise TLS priorities with default settings * @param daemon the daemon to initialise TLS priorities * @return true on success, false on error */ static bool daemon_tls_priorities_init_default (struct MHD_Daemon *daemon) { unsigned int p; int res; mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); mhd_assert (NULL == daemon->priority_cache); mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ for (p = 0; p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); ++p) { res = gnutls_priority_init (&daemon->priority_cache, MHD_TlsBasePriotities[p].str, NULL); if (GNUTLS_E_SUCCESS == res) { #ifdef _DEBUG #ifdef HAVE_MESSAGES switch ((enum MHD_TlsPrioritiesBaseType) p) { case MHD_TLS_PRIO_BASE_LIBMHD: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "@LIBMICROHTTPD application-specific system-wide " \ "configuration.\n") ); break; case MHD_TLS_PRIO_BASE_SYSTEM: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "@SYSTEM system-wide configuration.\n") ); break; #if GNUTLS_VERSION_NUMBER >= 0x030300 case MHD_TLS_PRIO_BASE_DEFAULT: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "GnuTLS default configuration.\n") ); break; #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ case MHD_TLS_PRIO_BASE_NORMAL: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "NORMAL configuration.\n") ); break; default: mhd_assert (0); } #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ return true; } } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set GnuTLS priorities. Last error: %s\n"), gnutls_strerror (res)); #endif /* HAVE_MESSAGES */ return false; } /** * The inner helper function for #daemon_tls_priorities_init_app(). * @param daemon the daemon to use * @param prio the appication-specified appendix for default priorities * @param prio_len the length of @a prio * @param buf the temporal buffer for string manipulations * @param buf_size the size of the @a buf * @return true on success, false on error */ static bool daemon_tls_priorities_init_append_inner_ (struct MHD_Daemon *daemon, const char *prio, size_t prio_len, char *buf, const size_t buf_size) { unsigned int p; int res; const char *err_pos; (void) buf_size; /* Mute compiler warning for non-Debug builds */ mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); mhd_assert (NULL == daemon->priority_cache); mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ for (p = 0; p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); ++p) { #if GNUTLS_VERSION_NUMBER >= 0x030300 #if GNUTLS_VERSION_NUMBER >= 0x030603 if (NULL == MHD_TlsBasePriotities[p].str) res = gnutls_priority_init2 (&daemon->priority_cache, prio, &err_pos, GNUTLS_PRIORITY_INIT_DEF_APPEND); else #else /* 0x030300 <= GNUTLS_VERSION_NUMBER && GNUTLS_VERSION_NUMBER < 0x030603 */ if (NULL == MHD_TlsBasePriotities[p].str) continue; /* Skip the value, no way to append priorities to the default string */ else #endif /* GNUTLS_VERSION_NUMBER < 0x030603 */ #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ if (1) { size_t buf_pos; mhd_assert (NULL != MHD_TlsBasePriotities[p].str); buf_pos = 0; memcpy (buf + buf_pos, MHD_TlsBasePriotities[p].str, MHD_TlsBasePriotities[p].len); buf_pos += MHD_TlsBasePriotities[p].len; buf[buf_pos++] = ':'; memcpy (buf + buf_pos, prio, prio_len + 1); #ifdef _DEBUG buf_pos += prio_len + 1; mhd_assert (buf_size >= buf_pos); #endif /* _DEBUG */ res = gnutls_priority_init (&daemon->priority_cache, buf, &err_pos); } if (GNUTLS_E_SUCCESS == res) { #ifdef _DEBUG #ifdef HAVE_MESSAGES switch ((enum MHD_TlsPrioritiesBaseType) p) { case MHD_TLS_PRIO_BASE_LIBMHD: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "@LIBMICROHTTPD application-specific system-wide " \ "configuration.\n") ); break; case MHD_TLS_PRIO_BASE_SYSTEM: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "@SYSTEM system-wide configuration.\n") ); break; #if GNUTLS_VERSION_NUMBER >= 0x030300 case MHD_TLS_PRIO_BASE_DEFAULT: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "GnuTLS default configuration.\n") ); break; #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ case MHD_TLS_PRIO_BASE_NORMAL: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "NORMAL configuration.\n") ); break; default: mhd_assert (0); } #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ return true; } } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set GnuTLS priorities. Last error: %s. " \ "The problematic part starts at: %s\n"), gnutls_strerror (res), err_pos); #endif /* HAVE_MESSAGES */ return false; } #define LOCAL_BUFF_SIZE 128 /** * Initialise TLS priorities with default settings with application-specified * appended string. * @param daemon the daemon to initialise TLS priorities * @param prio the application specified priorities to be appended to * the GnuTLS standard priorities string * @return true on success, false on error */ static bool daemon_tls_priorities_init_append (struct MHD_Daemon *daemon, const char *prio) { static const size_t longest_base_prio = MHD_STATICSTR_LEN_ ("@LIBMICROHTTPD"); bool ret; size_t prio_len; size_t buf_size_needed; if (NULL == prio) return daemon_tls_priorities_init_default (daemon); if (':' == prio[0]) ++prio; prio_len = strlen (prio); buf_size_needed = longest_base_prio + 1 + prio_len + 1; if (LOCAL_BUFF_SIZE >= buf_size_needed) { char local_buffer[LOCAL_BUFF_SIZE]; ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, local_buffer, LOCAL_BUFF_SIZE); } else { char *allocated_buffer; allocated_buffer = (char *) malloc (buf_size_needed); if (NULL == allocated_buffer) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif return false; } ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, allocated_buffer, buf_size_needed); free (allocated_buffer); } return ret; } #endif /* HTTPS_SUPPORT */ /** * Parse a list of options given as varargs. * * @param[in,out] daemon the daemon to initialize * @param[out] params the interim parameters to be assigned to * @param ap the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options_va (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, va_list ap) { enum MHD_OPTION opt; struct MHD_OptionItem *oa; unsigned int i; unsigned int uv; #ifdef HTTPS_SUPPORT const char *pstr; #if GNUTLS_VERSION_MAJOR >= 3 gnutls_certificate_retrieve_function2 * pgcrf; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 gnutls_certificate_retrieve_function3 * pgcrf2; #endif #endif /* HTTPS_SUPPORT */ while (MHD_OPTION_END != (opt = (enum MHD_OPTION) va_arg (ap, int))) { /* Increase counter at start, so resulting value is number of * processed options, including any failed ones. */ params->num_opts++; switch (opt) { case MHD_OPTION_CONNECTION_MEMORY_LIMIT: if (1) { size_t val; val = va_arg (ap, size_t); if (0 != val) { daemon->pool_size = val; if (64 > daemon->pool_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: specified " \ "MHD_OPTION_CONNECTION_MEMORY_LIMIT " \ "value is too small and rounded up to 64.\n")); #endif /* HAVE_MESSAGES */ daemon->pool_size = 64; } if (daemon->pool_size / 4 < daemon->pool_increment) daemon->pool_increment = daemon->pool_size / 4; } } break; case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: if (1) { size_t val; val = va_arg (ap, size_t); if (0 != val) { daemon->pool_increment = val; if (daemon->pool_size / 4 < daemon->pool_increment) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: specified " \ "MHD_OPTION_CONNECTION_MEMORY_INCREMENT value is " \ "too large and rounded down to 1/4 of " \ "MHD_OPTION_CONNECTION_MEMORY_LIMIT.\n")); #endif /* HAVE_MESSAGES */ daemon->pool_increment = daemon->pool_size / 4; } } } break; case MHD_OPTION_CONNECTION_LIMIT: daemon->connection_limit = va_arg (ap, unsigned int); break; case MHD_OPTION_CONNECTION_TIMEOUT: uv = va_arg (ap, unsigned int); #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT if ((UINT64_MAX / 4000 - 1) < uv) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The specified connection timeout (%u) is too large. " \ "Maximum allowed value (%" PRIu64 ") will be used " \ "instead.\n"), uv, (UINT64_MAX / 4000 - 1)); #endif uv = UINT64_MAX / 4000 - 1; } #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */ daemon->connection_timeout_ms = ((uint64_t) uv) * 1000; break; case MHD_OPTION_NOTIFY_COMPLETED: daemon->notify_completed = va_arg (ap, MHD_RequestCompletedCallback); daemon->notify_completed_cls = va_arg (ap, void *); break; case MHD_OPTION_NOTIFY_CONNECTION: daemon->notify_connection = va_arg (ap, MHD_NotifyConnectionCallback); daemon->notify_connection_cls = va_arg (ap, void *); break; case MHD_OPTION_PER_IP_CONNECTION_LIMIT: daemon->per_ip_connection_limit = va_arg (ap, unsigned int); break; case MHD_OPTION_SOCK_ADDR_LEN: params->server_addr_len = va_arg (ap, socklen_t); params->server_addr_len_set = true; params->pserver_addr = va_arg (ap, const struct sockaddr *); params->pserver_addr_set = true; break; case MHD_OPTION_SOCK_ADDR: params->server_addr_len_set = false; params->pserver_addr = va_arg (ap, const struct sockaddr *); params->pserver_addr_set = true; break; case MHD_OPTION_URI_LOG_CALLBACK: daemon->uri_log_callback = va_arg (ap, LogCallback); daemon->uri_log_callback_cls = va_arg (ap, void *); break; case MHD_OPTION_SERVER_INSANITY: daemon->insanity_level = (enum MHD_DisableSanityCheck) va_arg (ap, unsigned int); break; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) case MHD_OPTION_THREAD_POOL_SIZE: daemon->worker_pool_size = va_arg (ap, unsigned int); if (0 == daemon->worker_pool_size) { (void) 0; /* MHD_OPTION_THREAD_POOL_SIZE ignored, do nothing */ } else if (1 == daemon->worker_pool_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: value \"1\", specified as the thread pool " \ "size, is ignored. Thread pool is not used.\n")); #endif daemon->worker_pool_size = 0; } #if SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) /* Next comparison could be always false on some platforms and whole branch will * be optimized out on these platforms. On others it will be compiled into real * check. */ else if (daemon->worker_pool_size >= (SIZE_MAX / sizeof (struct MHD_Daemon))) /* Compiler may warn on some platforms, ignore warning. */ { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Specified thread pool size (%u) too big.\n"), daemon->worker_pool_size); #endif return MHD_NO; } #endif /* SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) */ else { if (! MHD_D_IS_USING_THREADS_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_THREAD_POOL_SIZE option is specified but " "MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n")); #endif return MHD_NO; } if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Both MHD_OPTION_THREAD_POOL_SIZE option and " "MHD_USE_THREAD_PER_CONNECTION flag are specified.\n")); #endif return MHD_NO; } } break; #endif #ifdef HTTPS_SUPPORT case MHD_OPTION_HTTPS_MEM_KEY: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_key = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_KEY_PASSWORD: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_key_password = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_MEM_CERT: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_cert = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_MEM_TRUST: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_trust = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_CRED_TYPE: daemon->cred_type = (gnutls_credentials_type_t) va_arg (ap, int); break; case MHD_OPTION_HTTPS_MEM_DHPARAMS: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) { gnutls_datum_t dhpar; size_t pstr_len; if (gnutls_dh_params_init (&daemon->https_mem_dhparams) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error initializing DH parameters.\n")); #endif return MHD_NO; } dhpar.data = (unsigned char *) _MHD_DROP_CONST (pstr); pstr_len = strlen (pstr); if (UINT_MAX < pstr_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Diffie-Hellman parameters string too long.\n")); #endif return MHD_NO; } dhpar.size = (unsigned int) pstr_len; if (gnutls_dh_params_import_pkcs3 (daemon->https_mem_dhparams, &dhpar, GNUTLS_X509_FMT_PEM) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Bad Diffie-Hellman parameters format.\n")); #endif gnutls_dh_params_deinit (daemon->https_mem_dhparams); return MHD_NO; } daemon->have_dhparams = true; } #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) { if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); if (MHD_OPTION_HTTPS_PRIORITIES == opt) { int init_res; const char *err_pos; init_res = gnutls_priority_init (&daemon->priority_cache, pstr, &err_pos); if (GNUTLS_E_SUCCESS != init_res) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Setting priorities to '%s' failed: %s " \ "The problematic part starts at: %s\n"), pstr, gnutls_strerror (init_res), err_pos); #endif daemon->priority_cache = NULL; return MHD_NO; } } else { /* The cache has been deinited */ daemon->priority_cache = NULL; if (! daemon_tls_priorities_init_append (daemon, pstr)) return MHD_NO; } } #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_CERT_CALLBACK: #if GNUTLS_VERSION_MAJOR < 3 #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_HTTPS_CERT_CALLBACK requires building " \ "MHD with GnuTLS >= 3.0.\n")); #endif return MHD_NO; #else pgcrf = va_arg (ap, gnutls_certificate_retrieve_function2 *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->cert_callback = pgcrf; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif /* HAVE_MESSAGES */ break; #endif case MHD_OPTION_HTTPS_CERT_CALLBACK2: #if GNUTLS_VERSION_NUMBER < 0x030603 #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building " \ "MHD with GnuTLS >= 3.6.3.\n")); #endif return MHD_NO; #else pgcrf2 = va_arg (ap, gnutls_certificate_retrieve_function3 *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->cert_callback2 = pgcrf2; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif /* HAVE_MESSAGES */ break; #endif #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: daemon->digest_auth_rand_size = va_arg (ap, size_t); daemon->digest_auth_random = va_arg (ap, const char *); if (MHD_OPTION_DIGEST_AUTH_RANDOM_COPY == opt) /* Set to some non-NULL value just to indicate that copy is required. */ daemon->digest_auth_random_copy = daemon; else daemon->digest_auth_random_copy = NULL; break; case MHD_OPTION_NONCE_NC_SIZE: daemon->nonce_nc_size = va_arg (ap, unsigned int); break; case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: daemon->dauth_bind_type = va_arg (ap, unsigned int); if (0 != (daemon->dauth_bind_type & MHD_DAUTH_BIND_NONCE_URI_PARAMS)) daemon->dauth_bind_type |= MHD_DAUTH_BIND_NONCE_URI; break; case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: if (1) { unsigned int val; val = va_arg (ap, unsigned int); if (0 != val) daemon->dauth_def_nonce_timeout = val; } break; case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: if (1) { uint32_t val; val = va_arg (ap, uint32_t); if (0 != val) daemon->dauth_def_max_nc = val; } break; #else /* ! DAUTH_SUPPORT */ case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: case MHD_OPTION_NONCE_NC_SIZE: case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Digest Auth is disabled for this build " \ "of GNU libmicrohttpd.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! DAUTH_SUPPORT */ case MHD_OPTION_LISTEN_SOCKET: params->listen_fd = va_arg (ap, MHD_socket); params->listen_fd_set = true; break; case MHD_OPTION_EXTERNAL_LOGGER: #ifdef HAVE_MESSAGES daemon->custom_error_log = va_arg (ap, VfprintfFunctionPointerType); daemon->custom_error_log_cls = va_arg (ap, void *); if (1 != params->num_opts) MHD_DLOG (daemon, _ ("MHD_OPTION_EXTERNAL_LOGGER is not the first option " "specified for the daemon. Some messages may be " "printed by the standard MHD logger.\n")); #else (void) va_arg (ap, VfprintfFunctionPointerType); (void) va_arg (ap, void *); #endif break; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) case MHD_OPTION_THREAD_STACK_SIZE: daemon->thread_stack_size = va_arg (ap, size_t); break; #endif case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: #ifdef TCP_FASTOPEN daemon->fastopen_queue_size = va_arg (ap, unsigned int); break; #else /* ! TCP_FASTOPEN */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("TCP fastopen is not supported on this platform.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! TCP_FASTOPEN */ case MHD_OPTION_LISTENING_ADDRESS_REUSE: daemon->listening_address_reuse = va_arg (ap, unsigned int) ? 1 : -1; break; case MHD_OPTION_LISTEN_BACKLOG_SIZE: daemon->listen_backlog_size = va_arg (ap, unsigned int); break; case MHD_OPTION_STRICT_FOR_CLIENT: daemon->client_discipline = va_arg (ap, int); /* Temporal assignment */ /* Map to correct value */ if (-1 >= daemon->client_discipline) daemon->client_discipline = -3; else if (1 <= daemon->client_discipline) daemon->client_discipline = 1; #ifdef HAVE_MESSAGES if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && (1 != daemon->client_discipline) ) { MHD_DLOG (daemon, _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " "another behaviour is specified by " "MHD_OPTION_STRICT_CLIENT.\n")); } #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_CLIENT_DISCIPLINE_LVL: daemon->client_discipline = va_arg (ap, int); #ifdef HAVE_MESSAGES if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && (1 != daemon->client_discipline) ) { MHD_DLOG (daemon, _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " "another behaviour is specified by " "MHD_OPTION_CLIENT_DISCIPLINE_LVL.\n")); } #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_ARRAY: params->num_opts--; /* Do not count MHD_OPTION_ARRAY */ oa = va_arg (ap, struct MHD_OptionItem *); i = 0; while (MHD_OPTION_END != (opt = oa[i].option)) { switch (opt) { /* all options taking 'size_t' */ case MHD_OPTION_CONNECTION_MEMORY_LIMIT: case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: case MHD_OPTION_THREAD_STACK_SIZE: if (MHD_NO == parse_options (daemon, params, opt, (size_t) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'unsigned int' */ case MHD_OPTION_NONCE_NC_SIZE: case MHD_OPTION_CONNECTION_LIMIT: case MHD_OPTION_CONNECTION_TIMEOUT: case MHD_OPTION_PER_IP_CONNECTION_LIMIT: case MHD_OPTION_THREAD_POOL_SIZE: case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: case MHD_OPTION_LISTENING_ADDRESS_REUSE: case MHD_OPTION_LISTEN_BACKLOG_SIZE: case MHD_OPTION_SERVER_INSANITY: case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: if (MHD_NO == parse_options (daemon, params, opt, (unsigned int) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'enum' */ case MHD_OPTION_HTTPS_CRED_TYPE: #ifdef HTTPS_SUPPORT if (MHD_NO == parse_options (daemon, params, opt, (gnutls_credentials_type_t) oa[i].value, MHD_OPTION_END)) #endif /* HTTPS_SUPPORT */ return MHD_NO; break; /* all options taking 'MHD_socket' */ case MHD_OPTION_LISTEN_SOCKET: if (MHD_NO == parse_options (daemon, params, opt, (MHD_socket) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'int' */ case MHD_OPTION_STRICT_FOR_CLIENT: case MHD_OPTION_CLIENT_DISCIPLINE_LVL: case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: case MHD_OPTION_TLS_NO_ALPN: case MHD_OPTION_APP_FD_SETSIZE: if (MHD_NO == parse_options (daemon, params, opt, (int) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'uint32_t' */ case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: if (MHD_NO == parse_options (daemon, params, opt, (uint32_t) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking one pointer */ case MHD_OPTION_SOCK_ADDR: case MHD_OPTION_HTTPS_MEM_KEY: case MHD_OPTION_HTTPS_KEY_PASSWORD: case MHD_OPTION_HTTPS_MEM_CERT: case MHD_OPTION_HTTPS_MEM_TRUST: case MHD_OPTION_HTTPS_MEM_DHPARAMS: case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: case MHD_OPTION_ARRAY: case MHD_OPTION_HTTPS_CERT_CALLBACK: case MHD_OPTION_HTTPS_CERT_CALLBACK2: if (MHD_NO == parse_options (daemon, params, opt, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking two pointers */ case MHD_OPTION_NOTIFY_COMPLETED: case MHD_OPTION_NOTIFY_CONNECTION: case MHD_OPTION_URI_LOG_CALLBACK: case MHD_OPTION_EXTERNAL_LOGGER: case MHD_OPTION_UNESCAPE_CALLBACK: case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: if (MHD_NO == parse_options (daemon, params, opt, (void *) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* options taking size_t-number followed by pointer */ case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: if (MHD_NO == parse_options (daemon, params, opt, (size_t) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* options taking socklen_t-number followed by pointer */ case MHD_OPTION_SOCK_ADDR_LEN: if (MHD_NO == parse_options (daemon, params, opt, (socklen_t) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; case MHD_OPTION_END: /* Not possible */ default: return MHD_NO; } i++; } break; case MHD_OPTION_UNESCAPE_CALLBACK: daemon->unescape_callback = va_arg (ap, UnescapeCallback); daemon->unescape_callback_cls = va_arg (ap, void *); break; #ifdef HTTPS_SUPPORT case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: #if GNUTLS_VERSION_MAJOR >= 3 daemon->cred_callback = va_arg (ap, MHD_PskServerCredentialsCallback); daemon->cred_callback_cls = va_arg (ap, void *); break; #else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD compiled " \ "without GNUtls >= 3.\n"), opt); return MHD_NO; #endif #endif /* HTTPS_SUPPORT */ case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: if (! MHD_D_IS_USING_THREADS_ (daemon)) daemon->sigpipe_blocked = ( (va_arg (ap, int)) != 0); else { (void) va_arg (ap, int); } break; case MHD_OPTION_TLS_NO_ALPN: #ifdef HTTPS_SUPPORT daemon->disable_alpn = (va_arg (ap, int) != 0); #else /* ! HTTPS_SUPPORT */ (void) va_arg (ap, int); #endif /* ! HTTPS_SUPPORT */ #ifdef HAVE_MESSAGES if (0 == (daemon->options & MHD_USE_TLS)) MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD " \ "but MHD_USE_TLS not set.\n"), (int) opt); #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_APP_FD_SETSIZE: params->fdset_size_set = true; params->fdset_size = va_arg (ap, int); break; #ifndef HTTPS_SUPPORT case MHD_OPTION_HTTPS_MEM_KEY: case MHD_OPTION_HTTPS_MEM_CERT: case MHD_OPTION_HTTPS_CRED_TYPE: case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: case MHD_OPTION_HTTPS_MEM_TRUST: case MHD_OPTION_HTTPS_CERT_CALLBACK: case MHD_OPTION_HTTPS_MEM_DHPARAMS: case MHD_OPTION_HTTPS_KEY_PASSWORD: case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: case MHD_OPTION_HTTPS_CERT_CALLBACK2: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD " "compiled without HTTPS support.\n"), opt); #endif return MHD_NO; #endif /* HTTPS_SUPPORT */ case MHD_OPTION_END: /* Not possible */ default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Invalid option %d! (Did you terminate " "the list with MHD_OPTION_END?).\n"), opt); #endif return MHD_NO; } } return MHD_YES; } #ifdef EPOLL_SUPPORT static int setup_epoll_fd (struct MHD_Daemon *daemon) { int fd; #ifndef HAVE_MESSAGES (void) daemon; /* Mute compiler warning. */ #endif /* ! HAVE_MESSAGES */ #ifdef USE_EPOLL_CREATE1 fd = epoll_create1 (EPOLL_CLOEXEC); #else /* ! USE_EPOLL_CREATE1 */ fd = epoll_create (MAX_EVENTS); #endif /* ! USE_EPOLL_CREATE1 */ if (MHD_INVALID_SOCKET == fd) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_create1 failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_INVALID_SOCKET; } #if ! defined(USE_EPOLL_CREATE1) if (! MHD_socket_noninheritable_ (fd)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on epoll FD.\n")); #endif } #endif /* ! USE_EPOLL_CREATE1 */ return fd; } /** * Setup epoll() FD for the daemon and initialize it to listen * on the listen FD. * @remark To be called only from MHD_start_daemon_va() * * @param daemon daemon to initialize for epoll() * @return #MHD_YES on success, #MHD_NO on failure */ static enum MHD_Result setup_epoll_to_listen (struct MHD_Daemon *daemon) { struct epoll_event event; MHD_socket ls; mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon)); mhd_assert (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)); mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) || \ MHD_ITC_IS_VALID_ (daemon->itc) ); daemon->epoll_fd = setup_epoll_fd (daemon); if (! MHD_D_IS_USING_THREADS_ (daemon) && (0 != (daemon->options & MHD_USE_AUTO))) { /* Application requested "MHD_USE_AUTO", probably MHD_get_fdset() will be used. Make sure that epoll FD is suitable for fd_set. Actually, MHD_get_fdset() is allowed for MHD_USE_EPOLL direct, but most probably direct requirement for MHD_USE_EPOLL means that epoll FD will be used directly. This logic is fuzzy, but better than nothing with current MHD API. */ if (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->epoll_fd, daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The epoll FD is too large to be used with fd_set.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } } if (-1 == daemon->epoll_fd) return MHD_NO; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (0 != (MHD_ALLOW_UPGRADE & daemon->options)) { daemon->epoll_upgrade_fd = setup_epoll_fd (daemon); if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd) return MHD_NO; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = daemon; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, ls, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->listen_socket_in_epoll = true; } if (MHD_ITC_IS_VALID_ (daemon->itc)) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = _MHD_DROP_CONST (epoll_itc_marker); if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, MHD_itc_r_fd_ (daemon->itc), &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } } return MHD_YES; } #endif /** * Apply interim parameters * @param[in,out] d the daemon to use * @param[out] ppsockaddr the pointer to store the pointer to 'struct sockaddr' * if provided by application * @param[out] psockaddr_len the size memory area pointed by 'struct sockaddr' * if provided by application * @param[in,out] params the interim parameters to process * @return true in case of success, * false in case of critical error (the daemon must be closed). */ static bool process_interim_params (struct MHD_Daemon *d, const struct sockaddr **ppsockaddr, socklen_t *psockaddr_len, struct MHD_InterimParams_ *params) { if (params->fdset_size_set) { if (0 >= params->fdset_size) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) is not positive.\n"), params->fdset_size); #endif /* HAVE_MESSAGES */ return false; } if (MHD_D_IS_USING_THREADS_ (d)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ "with MHD_USE_INTERNAL_POLLING_THREAD.\n")); #endif /* HAVE_MESSAGES */ (void) 0; } else if (MHD_D_IS_USING_POLL_ (d)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ "with MHD_USE_POLL.\n")); #endif /* HAVE_MESSAGES */ (void) 0; } else { /* The daemon without internal threads, external sockets polling */ #ifndef HAS_FD_SETSIZE_OVERRIDABLE if (((int) FD_SETSIZE) != params->fdset_size) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) does not match " \ "the platform FD_SETSIZE value (%d) and this platform " \ "does not support overriding of FD_SETSIZE.\n"), params->fdset_size, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return false; } #else /* HAS_FD_SETSIZE_OVERRIDABLE */ d->fdset_size = params->fdset_size; d->fdset_size_set_by_app = true; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ } } if (params->listen_fd_set) { if (MHD_INVALID_SOCKET == params->listen_fd) { (void) 0; /* Use MHD-created socket */ } #ifdef HAS_SIGNED_SOCKET else if (0 > params->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("The value provided for MHD_OPTION_LISTEN_SOCKET " \ "is invalid.\n")); #endif /* HAVE_MESSAGES */ return false; } #endif /* HAS_SIGNED_SOCKET */ else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_LISTEN_SOCKET specified for daemon " "with MHD_USE_NO_LISTEN_SOCKET flag set.\n")); #endif /* HAVE_MESSAGES */ (void) MHD_socket_close_ (params->listen_fd); return false; } else { d->listen_fd = params->listen_fd; d->listen_is_unix = _MHD_UNKNOWN; #ifdef MHD_USE_GETSOCKNAME d->port = 0; /* Force use of autodetection */ #endif /* MHD_USE_GETSOCKNAME */ } } mhd_assert (! params->server_addr_len_set || params->pserver_addr_set); if (params->pserver_addr_set) { if (NULL == params->pserver_addr) { /* The size must be zero if set */ if (params->server_addr_len_set && (0 != params->server_addr_len)) return false; /* Ignore parameter if it is NULL */ } else if (MHD_INVALID_SOCKET != d->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_LISTEN_SOCKET cannot be used together with " \ "MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR.\n")); #endif /* HAVE_MESSAGES */ return false; } else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR " \ "specified for daemon with MHD_USE_NO_LISTEN_SOCKET " \ "flag set.\n")); #endif /* HAVE_MESSAGES */ if (MHD_INVALID_SOCKET != d->listen_fd) { (void) MHD_socket_close_ (params->listen_fd); params->listen_fd = MHD_INVALID_SOCKET; } return false; } else { *ppsockaddr = params->pserver_addr; if (params->server_addr_len_set) { /* The size must be non-zero if set */ if (0 == params->server_addr_len) return false; *psockaddr_len = params->server_addr_len; } else *psockaddr_len = 0; } } return true; } /** * Start a webserver on the given port. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if #MHD_OPTION_SOCK_ADDR or * #MHD_OPTION_LISTEN_SOCKET is provided * or #MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to @a apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @param ap list of options (type-value pairs, * terminated with #MHD_OPTION_END). * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon_va (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, va_list ap) { const MHD_SCKT_OPT_BOOL_ on = 1; struct MHD_Daemon *daemon; const struct sockaddr *pservaddr = NULL; socklen_t addrlen; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif enum MHD_FLAG eflags; /* same type as in MHD_Daemon */ enum MHD_FLAG *pflags; struct MHD_InterimParams_ *interim_params; MHD_check_global_init_ (); eflags = (enum MHD_FLAG) flags; pflags = &eflags; if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_INTERNAL_POLLING_THREAD; /* Force enable, log warning later if needed */ #ifndef HAVE_INET6 if (0 != (*pflags & MHD_USE_IPv6)) return NULL; #endif #ifndef HAVE_POLL if (0 != (*pflags & MHD_USE_POLL)) return NULL; #endif #ifndef EPOLL_SUPPORT if (0 != (*pflags & MHD_USE_EPOLL)) return NULL; #endif /* ! EPOLL_SUPPORT */ #ifndef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) return NULL; #endif /* ! HTTPS_SUPPORT */ #ifndef TCP_FASTOPEN if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) return NULL; #endif if (0 != (*pflags & MHD_ALLOW_UPGRADE)) { #ifdef UPGRADE_SUPPORT *pflags |= MHD_ALLOW_SUSPEND_RESUME; #else /* ! UPGRADE_SUPPORT */ return NULL; #endif /* ! UPGRADE_SUPPORT */ } #ifdef MHD_USE_THREADS if ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) == ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) & *pflags)) return NULL; /* Cannot be thread-unsafe with multiple threads */ #else /* ! MHD_USE_THREADS */ if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) return NULL; #endif /* ! MHD_USE_THREADS */ if (NULL == dh) return NULL; /* Check for invalid combinations of flags. */ if ((0 != (*pflags & MHD_USE_POLL)) && (0 != (*pflags & MHD_USE_EPOLL))) return NULL; if ((0 != (*pflags & MHD_USE_EPOLL)) && (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))) return NULL; if ((0 != (*pflags & MHD_USE_POLL)) && (0 == (*pflags & (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION)))) return NULL; if ((0 != (*pflags & MHD_USE_AUTO)) && (0 != (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL)))) return NULL; if (0 != (*pflags & MHD_USE_AUTO)) { #if defined(EPOLL_SUPPORT) && defined(HAVE_POLL) if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_POLL; else *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ #elif defined(HAVE_POLL) if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) *pflags |= MHD_USE_POLL; /* Including thread-per-connection */ #elif defined(EPOLL_SUPPORT) if (0 == (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ #else /* No choice: use select() for any mode - do not modify flags */ #endif } if (0 != (*pflags & MHD_USE_NO_THREAD_SAFETY)) *pflags = (*pflags & ~((enum MHD_FLAG) MHD_USE_ITC)); /* useless in single-threaded environment */ else if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) { #ifdef HAVE_LISTEN_SHUTDOWN if (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)) #endif *pflags |= MHD_USE_ITC; /* yes, must use ITC to signal thread */ } if (NULL == (daemon = MHD_calloc_ (1, sizeof (struct MHD_Daemon)))) return NULL; interim_params = (struct MHD_InterimParams_ *) \ MHD_calloc_ (1, sizeof (struct MHD_InterimParams_)); if (NULL == interim_params) { int err_num = errno; free (daemon); errno = err_num; return NULL; } #ifdef EPOLL_SUPPORT daemon->epoll_fd = -1; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) daemon->epoll_upgrade_fd = -1; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* try to open listen socket */ #ifdef HTTPS_SUPPORT daemon->priority_cache = NULL; #endif /* HTTPS_SUPPORT */ daemon->listen_fd = MHD_INVALID_SOCKET; daemon->listen_is_unix = _MHD_NO; daemon->listening_address_reuse = 0; daemon->options = *pflags; pflags = &daemon->options; daemon->client_discipline = (0 != (*pflags & MHD_USE_PEDANTIC_CHECKS)) ? 1 : 0; daemon->port = port; daemon->apc = apc; daemon->apc_cls = apc_cls; daemon->default_handler = dh; daemon->default_handler_cls = dh_cls; daemon->connections = 0; daemon->connection_limit = MHD_MAX_CONNECTIONS_DEFAULT; daemon->pool_size = MHD_POOL_SIZE_DEFAULT; daemon->pool_increment = MHD_BUF_INC_SIZE; daemon->unescape_callback = &unescape_wrapper; daemon->connection_timeout_ms = 0; /* no timeout */ MHD_itc_set_invalid_ (daemon->itc); #ifdef MHD_USE_THREADS MHD_thread_handle_ID_set_invalid_ (&daemon->tid); #endif /* MHD_USE_THREADS */ #ifdef SOMAXCONN daemon->listen_backlog_size = SOMAXCONN; #else /* !SOMAXCONN */ daemon->listen_backlog_size = 511; /* should be safe value */ #endif /* !SOMAXCONN */ #ifdef HAVE_MESSAGES daemon->custom_error_log = &MHD_default_logger_; daemon->custom_error_log_cls = stderr; #endif #ifndef MHD_WINSOCK_SOCKETS daemon->sigpipe_blocked = false; #else /* MHD_WINSOCK_SOCKETS */ /* There is no SIGPIPE on W32, nothing to block. */ daemon->sigpipe_blocked = true; #endif /* _WIN32 && ! __CYGWIN__ */ #if defined(_DEBUG) && defined(HAVE_ACCEPT4) daemon->avoid_accept4 = false; #endif /* _DEBUG */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size = (int) FD_SETSIZE; daemon->fdset_size_set_by_app = false; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ #ifdef DAUTH_SUPPORT daemon->digest_auth_rand_size = 0; daemon->digest_auth_random = NULL; daemon->nonce_nc_size = 4; /* tiny */ daemon->dauth_def_nonce_timeout = MHD_DAUTH_DEF_TIMEOUT_; daemon->dauth_def_max_nc = MHD_DAUTH_DEF_MAX_NC_; #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) { daemon->cred_type = GNUTLS_CRD_CERTIFICATE; } #endif /* HTTPS_SUPPORT */ interim_params->num_opts = 0; interim_params->fdset_size_set = false; interim_params->fdset_size = 0; interim_params->listen_fd_set = false; interim_params->listen_fd = MHD_INVALID_SOCKET; interim_params->pserver_addr_set = false; interim_params->pserver_addr = NULL; interim_params->server_addr_len_set = false; interim_params->server_addr_len = 0; if (MHD_NO == parse_options_va (daemon, interim_params, ap)) { #ifdef HTTPS_SUPPORT if ( (0 != (*pflags & MHD_USE_TLS)) && (NULL != daemon->priority_cache) ) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (interim_params); free (daemon); return NULL; } if (! process_interim_params (daemon, &pservaddr, &addrlen, interim_params)) { free (interim_params); free (daemon); return NULL; } free (interim_params); interim_params = NULL; #ifdef HTTPS_SUPPORT if ((0 != (*pflags & MHD_USE_TLS)) && (NULL == daemon->priority_cache) && ! daemon_tls_priorities_init_default (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise GnuTLS priorities.\n")); #endif /* HAVE_MESSAGES */ free (daemon); return NULL; } #endif /* HTTPS_SUPPORT */ #ifdef HAVE_MESSAGES if ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) && (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD)) ) { MHD_DLOG (daemon, _ ("Warning: MHD_USE_THREAD_PER_CONNECTION must be used " \ "only with MHD_USE_INTERNAL_POLLING_THREAD. " \ "Flag MHD_USE_INTERNAL_POLLING_THREAD was added. " \ "Consider setting MHD_USE_INTERNAL_POLLING_THREAD " \ "explicitly.\n")); } #endif if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && ((NULL != daemon->notify_completed) || (NULL != daemon->notify_connection)) ) *pflags |= MHD_USE_ITC; /* requires ITC */ #ifdef _DEBUG #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Using debug build of libmicrohttpd.\n") ); #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ if ( (0 != (*pflags & MHD_USE_ITC)) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) && (0 == daemon->worker_pool_size) #endif ) { if (! MHD_itc_init_ (daemon->itc)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create inter-thread communication channel: %s\n"), MHD_itc_last_strerror_ ()); #endif #ifdef HTTPS_SUPPORT if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (daemon->itc), daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("file descriptor for inter-thread communication " \ "channel exceeds maximum value.\n")); #endif MHD_itc_destroy_chk_ (daemon->itc); #ifdef HTTPS_SUPPORT if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } } #ifdef DAUTH_SUPPORT if (NULL != daemon->digest_auth_random_copy) { mhd_assert (daemon == daemon->digest_auth_random_copy); daemon->digest_auth_random_copy = malloc (daemon->digest_auth_rand_size); if (NULL == daemon->digest_auth_random_copy) { #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } memcpy (daemon->digest_auth_random_copy, daemon->digest_auth_random, daemon->digest_auth_rand_size); daemon->digest_auth_random = daemon->digest_auth_random_copy; } if (daemon->nonce_nc_size > 0) { if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc))) / sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Specified value for NC_SIZE too large.\n")); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon); return NULL; } daemon->nnc = MHD_calloc_ (daemon->nonce_nc_size, sizeof (struct MHD_NonceNc)); if (NULL == daemon->nnc) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to allocate memory for nonce-nc map: %s\n"), MHD_strerror_ (errno)); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon); return NULL; } } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&daemon->nnc_lock)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD failed to initialize nonce-nc mutex.\n")); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon->nnc); free (daemon); return NULL; } #endif #endif /* Thread polling currently works only with internal select thread mode */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if ( (! MHD_D_IS_USING_THREADS_ (daemon)) && (daemon->worker_pool_size > 0) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD thread polling only works with " \ "MHD_USE_INTERNAL_POLLING_THREAD.\n")); #endif goto free_and_fail; } #endif if ( (MHD_INVALID_SOCKET == daemon->listen_fd) && (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) ) { /* try to open listen socket */ struct sockaddr_in servaddr4; #ifdef HAVE_INET6 struct sockaddr_in6 servaddr6; const bool use_ipv6 = (0 != (*pflags & MHD_USE_IPv6)); #else /* ! HAVE_INET6 */ const bool use_ipv6 = false; #endif /* ! HAVE_INET6 */ int domain; if (NULL != pservaddr) { #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN const socklen_t sa_len = pservaddr->sa_len; #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ #ifdef HAVE_INET6 if (use_ipv6 && (AF_INET6 != pservaddr->sa_family)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_USE_IPv6 is enabled, but 'struct sockaddr *' " \ "specified for MHD_OPTION_SOCK_ADDR_LEN or " \ "MHD_OPTION_SOCK_ADDR is not IPv6 address.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #endif /* HAVE_INET6 */ switch (pservaddr->sa_family) { case AF_INET: if (1) { struct sockaddr_in sa4; uint16_t sa4_port; if ((0 != addrlen) && (((socklen_t) sizeof(sa4)) > addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ "option is wrong.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 != sa_len) { if (((socklen_t) sizeof(sa4)) > sa_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The value of 'struct sockaddr.sa_len' provided " \ "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ "and does not match 'sa_family' value of the " \ "same structure.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } if ((0 == addrlen) || (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 == addrlen) addrlen = sizeof(sa4); memcpy (&sa4, pservaddr, sizeof(sa4)); /* Required due to stronger alignment */ sa4_port = (uint16_t) ntohs (sa4.sin_port); #ifndef MHD_USE_GETSOCKNAME if (0 != sa4_port) #endif /* ! MHD_USE_GETSOCKNAME */ daemon->port = sa4_port; domain = PF_INET; } break; #ifdef HAVE_INET6 case AF_INET6: if (1) { struct sockaddr_in6 sa6; uint16_t sa6_port; if ((0 != addrlen) && (((socklen_t) sizeof(sa6)) > addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ "option is wrong.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 != sa_len) { if (((socklen_t) sizeof(sa6)) > sa_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The value of 'struct sockaddr.sa_len' provided " \ "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ "and does not match 'sa_family' value of the " \ "same structure.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } if ((0 == addrlen) || (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 == addrlen) addrlen = sizeof(sa6); memcpy (&sa6, pservaddr, sizeof(sa6)); /* Required due to stronger alignment */ sa6_port = (uint16_t) ntohs (sa6.sin6_port); #ifndef MHD_USE_GETSOCKNAME if (0 != sa6_port) #endif /* ! MHD_USE_GETSOCKNAME */ daemon->port = sa6_port; domain = PF_INET6; *pflags |= ((enum MHD_FLAG) MHD_USE_IPv6); } break; #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: #endif /* AF_UNIX */ default: #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 == addrlen) addrlen = sa_len; else if ((0 != sa_len) && (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 >= addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The 'sa_family' of the 'struct sockaddr' provided " \ "via MHD_OPTION_SOCK_ADDR option is not supported.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef AF_UNIX if (AF_UNIX == pservaddr->sa_family) { daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; #ifdef PF_UNIX domain = PF_UNIX; #else /* ! PF_UNIX */ domain = AF_UNIX; #endif /* ! PF_UNIX */ } else /* combined with the next 'if' */ #endif /* AF_UNIX */ if (1) { daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; /* Assumed the same values for AF_* and PF_* */ domain = pservaddr->sa_family; } break; } } else { if (! use_ipv6) { memset (&servaddr4, 0, sizeof (struct sockaddr_in)); servaddr4.sin_family = AF_INET; servaddr4.sin_port = htons (port); if (0 != INADDR_ANY) servaddr4.sin_addr.s_addr = htonl (INADDR_ANY); #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN servaddr4.sin_len = sizeof (struct sockaddr_in); #endif pservaddr = (struct sockaddr *) &servaddr4; addrlen = (socklen_t) sizeof(servaddr4); daemon->listen_is_unix = _MHD_NO; domain = PF_INET; } #ifdef HAVE_INET6 else { #ifdef IN6ADDR_ANY_INIT static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT; #endif memset (&servaddr6, 0, sizeof (struct sockaddr_in6)); servaddr6.sin6_family = AF_INET6; servaddr6.sin6_port = htons (port); #ifdef IN6ADDR_ANY_INIT servaddr6.sin6_addr = static_in6any; #endif #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN servaddr6.sin6_len = sizeof (struct sockaddr_in6); #endif pservaddr = (struct sockaddr *) &servaddr6; addrlen = (socklen_t) sizeof (servaddr6); daemon->listen_is_unix = _MHD_NO; domain = PF_INET6; } #endif /* HAVE_INET6 */ } daemon->listen_fd = MHD_socket_create_listen_ (domain); if (MHD_INVALID_SOCKET == daemon->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create socket for listening: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket descriptor (%d) is not " \ "less than daemon FD_SETSIZE value (%d).\n"), (int) daemon->listen_fd, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif goto free_and_fail; } /* Apply the socket options according to listening_address_reuse. */ if (0 == daemon->listening_address_reuse) { #ifndef MHD_WINSOCK_SOCKETS /* No user requirement, use "traditional" default SO_REUSEADDR * on non-W32 platforms, and do not fail if it doesn't work. * Don't use it on W32, because on W32 it will allow multiple * bind to the same address:port, like SO_REUSEPORT on others. */ if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif /* ! MHD_WINSOCK_SOCKETS */ } else if (daemon->listening_address_reuse > 0) { /* User requested to allow reusing listening address:port. */ #ifndef MHD_WINSOCK_SOCKETS /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if * it doesn't work. */ if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif /* ! MHD_WINSOCK_SOCKETS */ /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms. * Fail if SO_REUSEPORT is not defined or setsockopt fails. */ /* SO_REUSEADDR on W32 has the same semantics as SO_REUSEPORT on BSD/Linux */ #if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT) if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, #ifndef MHD_WINSOCK_SOCKETS SO_REUSEPORT, #else /* MHD_WINSOCK_SOCKETS */ SO_REUSEADDR, #endif /* MHD_WINSOCK_SOCKETS */ (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #else /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ /* we're supposed to allow address:port re-use, but on this platform we cannot; fail hard */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot allow listening address reuse: " \ "SO_REUSEPORT not defined.\n")); #endif goto free_and_fail; #endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ } else /* if (daemon->listening_address_reuse < 0) */ { /* User requested to disallow reusing listening address:port. * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE * is used and Solaris with SO_EXCLBIND. * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE * or setsockopt fails. */ #if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \ (defined(__sun) && defined(SO_EXCLBIND)) if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, #ifdef SO_EXCLUSIVEADDRUSE SO_EXCLUSIVEADDRUSE, #else /* SO_EXCLBIND */ SO_EXCLBIND, #endif /* SO_EXCLBIND */ (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot disallow listening address reuse: " \ "SO_EXCLUSIVEADDRUSE not defined.\n")); #endif goto free_and_fail; #endif /* MHD_WINSOCK_SOCKETS */ } /* check for user supplied sockaddr */ if (0 != (*pflags & MHD_USE_IPv6)) { #ifdef IPPROTO_IPV6 #ifdef IPV6_V6ONLY /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options" (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx); and may also be missing on older POSIX systems; good luck if you have any of those, your IPv6 socket may then also bind against IPv4 anyway... */ const MHD_SCKT_OPT_BOOL_ v6_only = (MHD_USE_DUAL_STACK != (*pflags & MHD_USE_DUAL_STACK)); if (0 > setsockopt (daemon->listen_fd, IPPROTO_IPV6, IPV6_V6ONLY, (const void *) &v6_only, sizeof (v6_only))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif #endif } if (0 != bind (daemon->listen_fd, pservaddr, addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to bind to port %u: %s\n"), (unsigned int) port, MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #ifdef TCP_FASTOPEN if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) { if (0 == daemon->fastopen_queue_size) daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT; if (0 != setsockopt (daemon->listen_fd, IPPROTO_TCP, TCP_FASTOPEN, (const void *) &daemon->fastopen_queue_size, sizeof (daemon->fastopen_queue_size))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } } #endif if (0 != listen (daemon->listen_fd, (int) daemon->listen_backlog_size)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to listen for connections: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } } else { if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket descriptor (%d) is not " \ "less than daemon FD_SETSIZE value (%d).\n"), (int) daemon->listen_fd, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif goto free_and_fail; } else { #if defined(SOL_SOCKET) && (defined(SO_DOMAIN) || defined(SO_PROTOCOL_INFOW)) int af; int opt_name; void *poptval; socklen_t optval_size; #ifdef SO_DOMAIN opt_name = SO_DOMAIN; poptval = ⁡ optval_size = (socklen_t) sizeof (af); #else /* SO_PROTOCOL_INFOW */ WSAPROTOCOL_INFOW prot_info; opt_name = SO_PROTOCOL_INFOW; poptval = &prot_info; optval_size = (socklen_t) sizeof (prot_info); #endif /* SO_PROTOCOL_INFOW */ if (0 == getsockopt (daemon->listen_fd, SOL_SOCKET, opt_name, poptval, &optval_size)) { #ifndef SO_DOMAIN af = prot_info.iAddressFamily; #endif /* SO_DOMAIN */ switch (af) { case AF_INET: daemon->listen_is_unix = _MHD_NO; break; #ifdef HAVE_INET6 case AF_INET6: *pflags |= MHD_USE_IPv6; daemon->listen_is_unix = _MHD_NO; break; #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; break; #endif /* AF_UNIX */ default: daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; break; } } else #endif /* SOL_SOCKET && (SO_DOMAIN || SO_PROTOCOL_INFOW)) */ daemon->listen_is_unix = _MHD_UNKNOWN; } #ifdef MHD_USE_GETSOCKNAME daemon->port = 0; /* Force use of autodetection */ #endif /* MHD_USE_GETSOCKNAME */ } #ifdef MHD_USE_GETSOCKNAME if ( (0 == daemon->port) && (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) && (_MHD_YES != daemon->listen_is_unix) ) { /* Get port number. */ struct sockaddr_storage bindaddr; memset (&bindaddr, 0, sizeof (struct sockaddr_storage)); addrlen = sizeof (struct sockaddr_storage); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN bindaddr.ss_len = (socklen_t) addrlen; #endif if (0 != getsockname (daemon->listen_fd, (struct sockaddr *) &bindaddr, &addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to get listen port number: %s\n"), MHD_socket_last_strerr_ ()); #endif /* HAVE_MESSAGES */ } #ifdef MHD_POSIX_SOCKETS else if (sizeof (bindaddr) < addrlen) { /* should be impossible with `struct sockaddr_storage` */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to get listen port number " \ "(`struct sockaddr_storage` too small!?).\n")); #endif /* HAVE_MESSAGES */ } #ifndef __linux__ else if (0 == addrlen) { /* Many non-Linux-based platforms return zero addrlen * for AF_UNIX sockets */ daemon->port = 0; /* special value for UNIX domain sockets */ if (_MHD_UNKNOWN == daemon->listen_is_unix) daemon->listen_is_unix = _MHD_YES; } #endif /* __linux__ */ #endif /* MHD_POSIX_SOCKETS */ else { switch (bindaddr.ss_family) { case AF_INET: { struct sockaddr_in *s4 = (struct sockaddr_in *) &bindaddr; daemon->port = ntohs (s4->sin_port); daemon->listen_is_unix = _MHD_NO; break; } #ifdef HAVE_INET6 case AF_INET6: { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &bindaddr; daemon->port = ntohs (s6->sin6_port); daemon->listen_is_unix = _MHD_NO; mhd_assert (0 != (*pflags & MHD_USE_IPv6)); break; } #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; break; #endif default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket has unknown address family!\n")); #endif daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; break; } } } #endif /* MHD_USE_GETSOCKNAME */ if (MHD_INVALID_SOCKET != daemon->listen_fd) { mhd_assert (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)); if (! MHD_socket_nonblocking_ (daemon->listen_fd)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on listening socket: %s\n"), MHD_socket_last_strerr_ ()); #endif if (MHD_D_IS_USING_EPOLL_ (daemon) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) || (daemon->worker_pool_size > 0) #endif ) { /* Accept must be non-blocking. Multiple children may wake up * to handle a new connection, but only one will win the race. * The others must immediately return. */ goto free_and_fail; } daemon->listen_nonblk = false; } else daemon->listen_nonblk = true; } else { mhd_assert (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)); daemon->listen_nonblk = false; /* Actually listen socket does not exist */ } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) && (0 == daemon->worker_pool_size) #endif ) { if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Combining MHD_USE_THREAD_PER_CONNECTION and " \ "MHD_USE_EPOLL is not supported.\n")); #endif goto free_and_fail; } if (MHD_NO == setup_epoll_to_listen (daemon)) goto free_and_fail; } #endif /* EPOLL_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD failed to initialize IP connection limit mutex.\n")); #endif goto free_and_fail; } #endif #ifdef HTTPS_SUPPORT /* initialize HTTPS daemon certificate aspects & send / recv functions */ if ( (0 != (*pflags & MHD_USE_TLS)) && (0 != MHD_TLS_init (daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialize TLS support.\n")); #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); #endif goto free_and_fail; } #endif /* HTTPS_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* Start threads if requested by parameters */ if (MHD_D_IS_USING_THREADS_ (daemon)) { /* Internal thread (or threads) is used. * Make sure that MHD will be able to communicate with threads. */ /* If using a thread pool ITC will be initialised later * for each individual worker thread. */ #ifdef HAVE_LISTEN_SHUTDOWN mhd_assert ((1 < daemon->worker_pool_size) || \ (MHD_ITC_IS_VALID_ (daemon->itc)) || \ (MHD_INVALID_SOCKET != daemon->listen_fd)); #else /* ! HAVE_LISTEN_SHUTDOWN */ mhd_assert ((1 < daemon->worker_pool_size) || \ (MHD_ITC_IS_VALID_ (daemon->itc))); #endif /* ! HAVE_LISTEN_SHUTDOWN */ if (0 == daemon->worker_pool_size) { if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); goto free_and_fail; } if (! MHD_create_named_thread_ (&daemon->tid, MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) ? "MHD-listen" : "MHD-single", daemon->thread_stack_size, &MHD_polling_thread, daemon) ) { #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == errno) MHD_DLOG (daemon, _ ("Failed to create a new thread because it would have " \ "exceeded the system limit on the number of threads or " \ "no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create listen thread: %s\n"), MHD_strerror_ (errno)); #endif /* HAVE_MESSAGES */ MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); goto free_and_fail; } } else /* 0 < daemon->worker_pool_size */ { /* Coarse-grained count of connections per thread (note error * due to integer division). Also keep track of how many * connections are leftover after an equal split. */ unsigned int conns_per_thread = daemon->connection_limit / daemon->worker_pool_size; unsigned int leftover_conns = daemon->connection_limit % daemon->worker_pool_size; mhd_assert (2 <= daemon->worker_pool_size); i = 0; /* we need this in case fcntl or malloc fails */ /* Allocate memory for pooled objects */ daemon->worker_pool = malloc (sizeof (struct MHD_Daemon) * daemon->worker_pool_size); if (NULL == daemon->worker_pool) goto thread_failed; /* Start the workers in the pool */ for (i = 0; i < daemon->worker_pool_size; ++i) { /* Create copy of the Daemon object for each worker */ struct MHD_Daemon *d = &daemon->worker_pool[i]; memcpy (d, daemon, sizeof (struct MHD_Daemon)); /* Adjust polling params for worker daemons; note that memcpy() has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into the worker threads. */ d->master = daemon; d->worker_pool_size = 0; d->worker_pool = NULL; if (! MHD_mutex_init_ (&d->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif goto thread_failed; } if (! MHD_mutex_init_ (&d->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } if (0 != (*pflags & MHD_USE_ITC)) { if (! MHD_itc_init_ (d->itc)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create worker inter-thread " \ "communication channel: %s\n"), MHD_itc_last_strerror_ () ); #endif MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } if (MHD_D_IS_USING_SELECT_ (d) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (d->itc), daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("File descriptor for worker inter-thread " \ "communication channel exceeds maximum value.\n")); #endif MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } } else MHD_itc_set_invalid_ (d->itc); #ifdef HAVE_LISTEN_SHUTDOWN mhd_assert ((MHD_ITC_IS_VALID_ (d->itc)) || \ (MHD_INVALID_SOCKET != d->listen_fd)); #else /* ! HAVE_LISTEN_SHUTDOWN */ mhd_assert (MHD_ITC_IS_VALID_ (d->itc)); #endif /* ! HAVE_LISTEN_SHUTDOWN */ /* Divide available connections evenly amongst the threads. * Thread indexes in [0, leftover_conns) each get one of the * leftover connections. */ d->connection_limit = conns_per_thread; if (i < leftover_conns) ++d->connection_limit; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (d) && (MHD_NO == setup_epoll_to_listen (d)) ) { if (MHD_ITC_IS_VALID_ (d->itc)) MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } #endif /* Some members must be used only in master daemon */ #if defined(MHD_USE_THREADS) memset (&d->per_ip_connection_mutex, 0x7F, sizeof(d->per_ip_connection_mutex)); #endif /* MHD_USE_THREADS */ #ifdef DAUTH_SUPPORT d->nnc = NULL; d->nonce_nc_size = 0; d->digest_auth_random_copy = NULL; #if defined(MHD_USE_THREADS) memset (&d->nnc_lock, 0x7F, sizeof(d->nnc_lock)); #endif /* MHD_USE_THREADS */ #endif /* DAUTH_SUPPORT */ /* Spawn the worker thread */ if (! MHD_create_named_thread_ (&d->tid, "MHD-worker", daemon->thread_stack_size, &MHD_polling_thread, d)) { #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == errno) MHD_DLOG (daemon, _ ("Failed to create a new pool thread because it would " \ "have exceeded the system limit on the number of " \ "threads or no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create pool thread: %s\n"), MHD_strerror_ (errno)); #endif /* Free memory for this worker; cleanup below handles * all previously-created workers. */ MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); if (MHD_ITC_IS_VALID_ (d->itc)) MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } } } } else { /* Daemon without internal threads */ if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } } #endif #ifdef HTTPS_SUPPORT /* API promises to never use the password after initialization, so we additionally NULL it here to not deref a dangling pointer. */ daemon->https_key_password = NULL; #endif /* HTTPS_SUPPORT */ return daemon; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) thread_failed: /* If no worker threads created, then shut down normally. Calling MHD_stop_daemon (as we do below) doesn't work here since it assumes a 0-sized thread pool means we had been in the default MHD_USE_INTERNAL_POLLING_THREAD mode. */ if (0 == i) { MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); if (NULL != daemon->worker_pool) free (daemon->worker_pool); goto free_and_fail; } /* Shutdown worker threads we've already created. Pretend as though we had fully initialized our daemon, but with a smaller number of threads than had been requested. */ daemon->worker_pool_size = i; MHD_stop_daemon (daemon); return NULL; #endif free_and_fail: /* clean up basic memory state in 'daemon' and return NULL to indicate failure */ #ifdef EPOLL_SUPPORT #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (daemon->upgrade_fd_in_epoll) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, daemon->epoll_upgrade_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); daemon->upgrade_fd_in_epoll = false; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (-1 != daemon->epoll_fd) close (daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (-1 != daemon->epoll_upgrade_fd) close (daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ #ifdef DAUTH_SUPPORT free (daemon->digest_auth_random_copy); free (daemon->nnc); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->nnc_lock); #endif #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) { gnutls_priority_deinit (daemon->priority_cache); if (daemon->x509_cred) gnutls_certificate_free_credentials (daemon->x509_cred); if (daemon->psk_cred) gnutls_psk_free_server_credentials (daemon->psk_cred); } #endif /* HTTPS_SUPPORT */ if (MHD_ITC_IS_VALID_ (daemon->itc)) MHD_itc_destroy_chk_ (daemon->itc); if (MHD_INVALID_SOCKET != daemon->listen_fd) (void) MHD_socket_close_ (daemon->listen_fd); free (daemon); return NULL; } /** * Close all connections for the daemon. * Must only be called when MHD_Daemon::shutdown was set to true. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to close down */ static void close_all_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon); #ifdef UPGRADE_SUPPORT const bool upg_allowed = (0 != (daemon->options & MHD_ALLOW_UPGRADE)); #endif /* UPGRADE_SUPPORT */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; const bool used_tls = (0 != (daemon->options & MHD_USE_TLS)); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ mhd_assert (daemon->shutdown); #ifdef MHD_USE_THREADS /* Remove externally added new connections that are * not processed by the daemon thread. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); while (NULL != (pos = daemon->new_connections_tail)) { mhd_assert (MHD_D_IS_USING_THREADS_ (daemon)); DLL_remove (daemon->new_connections_head, daemon->new_connections_tail, pos); new_connection_close_ (daemon, pos); } MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); #endif /* MHD_USE_THREADS */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /* give upgraded HTTPS connections a chance to finish */ /* 'daemon->urh_head' is not used in thread-per-connection mode. */ for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { mhd_assert (! used_thr_p_c); urhn = urh->prev; /* call generic forwarding function for passing data with chance to detect that application is done. */ process_urh (urh); MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* Resuming will move connection to cleanup list. */ MHD_resume_connection (urh->connection); } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /* Give suspended connections a chance to resume to avoid running into the check for there not being any suspended connections left in case of a tight race with a recently resumed connection. */ if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) { daemon->resuming = true; /* Force check for pending resume. */ resume_suspended_connections (daemon); } /* first, make sure all threads are aware of shutdown; need to traverse DLLs in peace... */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef UPGRADE_SUPPORT if (upg_allowed) { struct MHD_Connection *susp; susp = daemon->suspended_connections_tail; while (NULL != susp) { if (NULL == susp->urh) /* "Upgraded" connection? */ MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ "suspended connections.\n")); #ifdef HTTPS_SUPPORT else if (used_tls && used_thr_p_c && (! susp->urh->clean_ready) ) shutdown (susp->urh->app.socket, SHUT_RDWR); /* Wake thread by shutdown of app socket. */ #endif /* HTTPS_SUPPORT */ else { #ifdef HAVE_MESSAGES if (! susp->urh->was_closed) MHD_DLOG (daemon, _ ("Initiated daemon shutdown while \"upgraded\" " \ "connection was not closed.\n")); #endif susp->urh->was_closed = true; /* If thread-per-connection is used, connection's thread * may still processing "upgrade" (exiting). */ if (! used_thr_p_c) MHD_connection_finish_forward_ (susp); /* Do not use MHD_resume_connection() as mutex is * already locked. */ susp->resuming = true; daemon->resuming = true; } susp = susp->prev; } } else /* This 'else' is combined with next 'if' */ #endif /* UPGRADE_SUPPORT */ if (NULL != daemon->suspended_connections_head) MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ "suspended connections.\n")); #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) #ifdef MHD_USE_THREADS if (upg_allowed && used_tls && used_thr_p_c) { /* "Upgraded" threads may be running in parallel. Connection will not be * moved to the "cleanup list" until connection's thread finishes. * We must ensure that all "upgraded" connections are finished otherwise * connection may stay in "suspended" list and will not be cleaned. */ for (pos = daemon->suspended_connections_tail; NULL != pos; pos = pos->prev) { /* Any connection found here is "upgraded" connection, normal suspended * connections are already removed from this list. */ mhd_assert (NULL != pos->urh); if (! pos->thread_joined) { /* While "cleanup" list is not manipulated by "upgraded" * connection, "cleanup" mutex is required for call of * MHD_resume_connection() during finishing of "upgraded" * thread. */ MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) MHD_PANIC (_ ("Failed to join a thread.\n")); pos->thread_joined = true; MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); } } } #endif /* MHD_USE_THREADS */ #endif for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) { shutdown (pos->socket_fd, SHUT_RDWR); #ifdef MHD_WINSOCK_SOCKETS if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "e")) ) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* now, collect per-connection threads */ if (used_thr_p_c) { pos = daemon->connections_tail; while (NULL != pos) { if (! pos->thread_joined) { MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) MHD_PANIC (_ ("Failed to join a thread.\n")); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); pos->thread_joined = true; /* The thread may have concurrently modified the DLL, need to restart from the beginning */ pos = daemon->connections_tail; continue; } pos = pos->prev; } } MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef UPGRADE_SUPPORT /* Finished threads with "upgraded" connections need to be moved * to cleanup list by resume_suspended_connections(). */ /* "Upgraded" connections that were not closed explicitly by * application should be moved to cleanup list too. */ if (upg_allowed) { daemon->resuming = true; /* Force check for pending resume. */ resume_suspended_connections (daemon); } #endif /* UPGRADE_SUPPORT */ mhd_assert (NULL == daemon->suspended_connections_head); /* now that we're alone, move everyone to cleanup */ while (NULL != (pos = daemon->connections_tail)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (! pos->thread_joined) ) MHD_PANIC (_ ("Failed to join a thread.\n")); #endif close_connection (pos); } MHD_cleanup_connections (daemon); } /** * Shutdown an HTTP daemon. * * @param daemon daemon to stop * @ingroup event */ _MHD_EXTERN void MHD_stop_daemon (struct MHD_Daemon *daemon) { MHD_socket fd; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif if (NULL == daemon) return; if ( (daemon->shutdown) && (NULL == daemon->master) ) MHD_PANIC (_ ("MHD_stop_daemon() was called twice.")); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (NULL != daemon->worker_pool) || \ (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && (NULL == daemon->worker_pool)) || \ (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); /* Slave daemons must be stopped by master daemon. */ mhd_assert ( (NULL == daemon->master) || (daemon->shutdown) ); daemon->shutdown = true; if (daemon->was_quiesced) fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */ else fd = daemon->listen_fd; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) { /* Master daemon with worker pool. */ mhd_assert (1 < daemon->worker_pool_size); mhd_assert (MHD_D_IS_USING_THREADS_ (daemon)); /* Let workers shutdown in parallel. */ for (i = 0; i < daemon->worker_pool_size; ++i) { daemon->worker_pool[i].shutdown = true; if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) { if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "e")) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); } else mhd_assert (MHD_INVALID_SOCKET != fd); } #ifdef HAVE_LISTEN_SHUTDOWN if (MHD_INVALID_SOCKET != fd) { (void) shutdown (fd, SHUT_RDWR); } #endif /* HAVE_LISTEN_SHUTDOWN */ for (i = 0; i < daemon->worker_pool_size; ++i) { MHD_stop_daemon (&daemon->worker_pool[i]); } free (daemon->worker_pool); mhd_assert (MHD_ITC_IS_INVALID_ (daemon->itc)); #ifdef EPOLL_SUPPORT mhd_assert (-1 == daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) mhd_assert (-1 == daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ } else #endif { /* Worker daemon or single daemon. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_D_IS_USING_THREADS_ (daemon)) { /* Worker daemon or single daemon with internal thread(s). */ mhd_assert (0 == daemon->worker_pool_size); /* Separate thread(s) is used for polling sockets. */ if (MHD_ITC_IS_VALID_ (daemon->itc)) { if (! MHD_itc_activate_ (daemon->itc, "e")) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); } else { #ifdef HAVE_LISTEN_SHUTDOWN if (MHD_INVALID_SOCKET != fd) { if (NULL == daemon->master) (void) shutdown (fd, SHUT_RDWR); } else #endif /* HAVE_LISTEN_SHUTDOWN */ mhd_assert (false); /* Should never happen */ } if (! MHD_thread_handle_ID_join_thread_ (daemon->tid)) { MHD_PANIC (_ ("Failed to join a thread.\n")); } /* close_all_connections() was called in daemon thread. */ } else #endif { /* No internal threads are used for polling sockets. */ close_all_connections (daemon); } mhd_assert (NULL == daemon->connections_head); mhd_assert (NULL == daemon->cleanup_head); mhd_assert (NULL == daemon->suspended_connections_head); mhd_assert (NULL == daemon->new_connections_head); #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) mhd_assert (NULL == daemon->urh_head); #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ if (MHD_ITC_IS_VALID_ (daemon->itc)) MHD_itc_destroy_chk_ (daemon->itc); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_fd) ) MHD_socket_close_chk_ (daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_upgrade_fd) ) MHD_socket_close_chk_ (daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); #endif } if (NULL == daemon->master) { /* Cleanup that should be done only one time in master/single daemon. * Do not perform this cleanup in worker daemons. */ if (MHD_INVALID_SOCKET != fd) MHD_socket_close_chk_ (fd); /* TLS clean up */ #ifdef HTTPS_SUPPORT if (daemon->have_dhparams) { gnutls_dh_params_deinit (daemon->https_mem_dhparams); daemon->have_dhparams = false; } if (0 != (daemon->options & MHD_USE_TLS)) { gnutls_priority_deinit (daemon->priority_cache); if (daemon->x509_cred) gnutls_certificate_free_credentials (daemon->x509_cred); if (daemon->psk_cred) gnutls_psk_free_server_credentials (daemon->psk_cred); } #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT free (daemon->digest_auth_random_copy); free (daemon->nnc); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->nnc_lock); #endif #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); #endif free (daemon); } } /** * Obtain information about the given daemon. * The returned pointer is invalidated with the next call of this function or * when the daemon is stopped. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType info_type, ...) { if (NULL == daemon) return NULL; mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (NULL != daemon->worker_pool) || \ (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && (NULL == daemon->worker_pool)) || \ (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); switch (info_type) { case MHD_DAEMON_INFO_KEY_SIZE: return NULL; /* no longer supported */ case MHD_DAEMON_INFO_MAC_KEY_SIZE: return NULL; /* no longer supported */ case MHD_DAEMON_INFO_LISTEN_FD: daemon->daemon_info_dummy_listen_fd.listen_fd = daemon->listen_fd; return &daemon->daemon_info_dummy_listen_fd; case MHD_DAEMON_INFO_EPOLL_FD: #ifdef EPOLL_SUPPORT daemon->daemon_info_dummy_epoll_fd.epoll_fd = daemon->epoll_fd; return &daemon->daemon_info_dummy_epoll_fd; #else /* ! EPOLL_SUPPORT */ return NULL; #endif /* ! EPOLL_SUPPORT */ case MHD_DAEMON_INFO_CURRENT_CONNECTIONS: if (! MHD_D_IS_THREAD_SAFE_ (daemon)) MHD_cleanup_connections (daemon); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) else if (daemon->worker_pool) { unsigned int i; /* Collect the connection information stored in the workers. */ daemon->connections = 0; for (i = 0; i < daemon->worker_pool_size; i++) { /* FIXME: next line is thread-safe only if read is atomic. */ daemon->connections += daemon->worker_pool[i].connections; } } #endif daemon->daemon_info_dummy_num_connections.num_connections = daemon->connections; return &daemon->daemon_info_dummy_num_connections; case MHD_DAEMON_INFO_FLAGS: daemon->daemon_info_dummy_flags.flags = daemon->options; return &daemon->daemon_info_dummy_flags; case MHD_DAEMON_INFO_BIND_PORT: daemon->daemon_info_dummy_port.port = daemon->port; return &daemon->daemon_info_dummy_port; default: return NULL; } } /** * Obtain the version of this library * * @return static version string, e.g. "0.9.9" * @ingroup specialized */ _MHD_EXTERN const char * MHD_get_version (void) { #ifdef PACKAGE_VERSION return PACKAGE_VERSION; #else /* !PACKAGE_VERSION */ static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0"; if (0 == ver[0]) { int res = MHD_snprintf_ (ver, sizeof(ver), "%x.%x.%x", (int) (((uint32_t) MHD_VERSION >> 24) & 0xFF), (int) (((uint32_t) MHD_VERSION >> 16) & 0xFF), (int) (((uint32_t) MHD_VERSION >> 8) & 0xFF)); if ((0 >= res) || (sizeof(ver) <= res)) return "0.0.0"; /* Can't return real version */ } return ver; #endif /* !PACKAGE_VERSION */ } /** * Obtain the version of this library as a binary value. * * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of * compiled MHD binary) * @note Available since #MHD_VERSION 0x00097601 * @ingroup specialized */ _MHD_EXTERN uint32_t MHD_get_version_bin (void) { return (uint32_t) MHD_VERSION; } /** * Get information about supported MHD features. * Indicate that MHD was compiled with or without support for * particular feature. Some features require additional support * by kernel. Kernel support is not checked by this function. * * @param feature type of requested information * @return #MHD_YES if feature is supported by MHD, #MHD_NO if * feature is not supported or feature is unknown. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_is_feature_supported (enum MHD_FEATURE feature) { switch (feature) { case MHD_FEATURE_MESSAGES: #ifdef HAVE_MESSAGES return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_TLS: #ifdef HTTPS_SUPPORT return MHD_YES; #else /* ! HTTPS_SUPPORT */ return MHD_NO; #endif /* ! HTTPS_SUPPORT */ case MHD_FEATURE_HTTPS_CERT_CALLBACK: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ case MHD_FEATURE_HTTPS_CERT_CALLBACK2: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030603 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ case MHD_FEATURE_IPv6: #ifdef HAVE_INET6 return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_IPv6_ONLY: #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_POLL: #ifdef HAVE_POLL return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_EPOLL: #ifdef EPOLL_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET: #ifdef HAVE_LISTEN_SHUTDOWN return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SOCKETPAIR: #ifdef _MHD_ITC_SOCKETPAIR return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_TCP_FASTOPEN: #ifdef TCP_FASTOPEN return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_BASIC_AUTH: #ifdef BAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_POSTPROCESSOR: #ifdef HAVE_POSTPROCESSOR return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_HTTPS_KEY_PASSWORD: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ case MHD_FEATURE_LARGE_FILE: #if defined(HAVE_PREAD64) || defined(_WIN32) return MHD_YES; #elif defined(HAVE_PREAD) return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; #elif defined(HAVE_LSEEK64) return MHD_YES; #else return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; #endif case MHD_FEATURE_THREAD_NAMES: #if defined(MHD_USE_THREAD_NAME_) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_UPGRADE: #if defined(UPGRADE_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_RESPONSES_SHARED_FD: #if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_AUTODETECT_BIND_PORT: #ifdef MHD_USE_GETSOCKNAME return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_AUTOSUPPRESS_SIGPIPE: #if defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || \ ! defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SENDFILE: #ifdef _MHD_HAVE_SENDFILE return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_THREADS: #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_COOKIE_PARSING: #if defined(COOKIE_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_RFC2069: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_MD5: #if defined(DAUTH_SUPPORT) && defined(MHD_MD5_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_SHA256: #if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_SHA512_256: #if defined(DAUTH_SUPPORT) && defined(MHD_SHA512_256_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_AUTH_INT: #ifdef DAUTH_SUPPORT return MHD_NO; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION: #ifdef DAUTH_SUPPORT return MHD_NO; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_USERHASH: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_EXTERN_HASH: #if defined(MHD_MD5_TLSLIB) || defined(MHD_SHA256_TLSLIB) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DEBUG_BUILD: #ifdef _DEBUG return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_FLEXIBLE_FD_SETSIZE: #ifdef HAS_FD_SETSIZE_OVERRIDABLE return MHD_YES; #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ return MHD_NO; #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ default: break; } return MHD_NO; } #ifdef MHD_HTTPS_REQUIRE_GCRYPT #if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600 #if defined(MHD_USE_POSIX_THREADS) GCRY_THREAD_OPTION_PTHREAD_IMPL; #elif defined(MHD_W32_MUTEX_) static int gcry_w32_mutex_init (void **ppmtx) { *ppmtx = malloc (sizeof (MHD_mutex_)); if (NULL == *ppmtx) return ENOMEM; if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx)) { free (*ppmtx); *ppmtx = NULL; return EPERM; } return 0; } static int gcry_w32_mutex_destroy (void **ppmtx) { int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL; free (*ppmtx); return res; } static int gcry_w32_mutex_lock (void **ppmtx) { return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; } static int gcry_w32_mutex_unlock (void **ppmtx) { return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; } static struct gcry_thread_cbs gcry_threads_w32 = { (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)), NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy, gcry_w32_mutex_lock, gcry_w32_mutex_unlock, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; #endif /* defined(MHD_W32_MUTEX_) */ #endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */ #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ /** * Initialize do setup work. */ void MHD_init (void) { #if defined(MHD_WINSOCK_SOCKETS) WSADATA wsd; #endif /* MHD_WINSOCK_SOCKETS */ MHD_set_panic_func (NULL, NULL); #if defined(MHD_WINSOCK_SOCKETS) if (0 != WSAStartup (MAKEWORD (2, 2), &wsd)) MHD_PANIC (_ ("Failed to initialize winsock.\n")); if ((2 != LOBYTE (wsd.wVersion)) && (2 != HIBYTE (wsd.wVersion))) MHD_PANIC (_ ("Winsock version 2.2 is not available.\n")); #endif /* MHD_WINSOCK_SOCKETS */ #ifdef HTTPS_SUPPORT #ifdef MHD_HTTPS_REQUIRE_GCRYPT #if GCRYPT_VERSION_NUMBER < 0x010600 #if GNUTLS_VERSION_NUMBER <= 0x020b00 #if defined(MHD_USE_POSIX_THREADS) if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)) MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); #elif defined(MHD_W32_MUTEX_) if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_w32)) MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); #endif /* defined(MHD_W32_MUTEX_) */ #endif /* GNUTLS_VERSION_NUMBER <= 0x020b00 */ gcry_check_version (NULL); #else if (NULL == gcry_check_version ("1.6.0")) MHD_PANIC (_ ("libgcrypt is too old. MHD was compiled for " \ "libgcrypt 1.6.0 or newer.\n")); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ gnutls_global_init (); #endif /* HTTPS_SUPPORT */ MHD_monotonic_sec_counter_init (); MHD_send_init_static_vars_ (); MHD_init_mem_pools_ (); /* Check whether sizes were correctly detected by configure */ #ifdef _DEBUG if (1) { struct timeval tv; mhd_assert (sizeof(tv.tv_sec) == SIZEOF_STRUCT_TIMEVAL_TV_SEC); } #endif /* _DEBUG */ mhd_assert (sizeof(uint64_t) == SIZEOF_UINT64_T); } void MHD_fini (void) { #ifdef HTTPS_SUPPORT gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ #if defined(MHD_WINSOCK_SOCKETS) WSACleanup (); #endif /* MHD_WINSOCK_SOCKETS */ MHD_monotonic_sec_counter_finish (); } #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED _SET_INIT_AND_DEINIT_FUNCS (MHD_init, MHD_fini); #endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */ /* end of daemon.c */ libmicrohttpd-1.0.2/src/microhttpd/mhd_itc_types.h0000644000175000017500000000455215035214301017247 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2020 Karlson2k (Evgeny Grin), Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc_types.h * @brief Types for platform-independent inter-thread communication * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic types for inter-thread communication. * Designed to be included by other headers. */ #ifndef MHD_ITC_TYPES_H #define MHD_ITC_TYPES_H 1 #include "mhd_options.h" /* Force socketpair on native W32 */ #if defined(_WIN32) && ! defined(__CYGWIN__) && ! defined(_MHD_ITC_SOCKETPAIR) #error _MHD_ITC_SOCKETPAIR is not defined on naitive W32 platform #endif /* _WIN32 && !__CYGWIN__ && !_MHD_ITC_SOCKETPAIR */ #if defined(_MHD_ITC_EVENTFD) /* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */ /** * Data type for a MHD ITC. */ struct MHD_itc_ { int fd; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID { -1 } #elif defined(_MHD_ITC_PIPE) /* **************** Standard UNIX ITC implementation by pipe ********** */ /** * Data type for a MHD ITC. */ struct MHD_itc_ { int fd[2]; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID { { -1, -1 } } #elif defined(_MHD_ITC_SOCKETPAIR) /* **************** ITC implementation by socket pair ********** */ #include "mhd_sockets.h" /** * Data type for a MHD ITC. */ struct MHD_itc_ { MHD_socket sk[2]; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID \ { { MHD_INVALID_SOCKET, MHD_INVALID_SOCKET } } #endif /* _MHD_ITC_SOCKETPAIR */ #endif /* ! MHD_ITC_TYPES_H */ libmicrohttpd-1.0.2/src/microhttpd/test_start_stop.c0000644000175000017500000001117314760713574017671 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_start_stop.c * @brief test for #1901 (start+stop) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return MHD_NO; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) static unsigned int testInternalGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 2; MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedPoolGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 4; MHD_stop_daemon (d); return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 8; MHD_stop_daemon (d); return 0; } #endif static unsigned int testExternalGetSingleThread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 8; MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silence compiler warning. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) errorCount += testInternalGet (0); errorCount += testMultithreadedGet (0); errorCount += testMultithreadedPoolGet (0); errorCount += testExternalGet (); #endif errorCount += testExternalGetSingleThread (); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (MHD_USE_POLL); errorCount += testMultithreadedGet (MHD_USE_POLL); errorCount += testMultithreadedPoolGet (MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (MHD_USE_EPOLL); } #endif if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/sha256.c0000644000175000017500000006026315035214301015420 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha256.c * @brief Calculation of SHA-256 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha256.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA256 calculation. * * @param ctx must be a `struct Sha256Ctx *` */ void MHD_SHA256_init (struct Sha256Ctx *ctx) { /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.3 */ /* First thirty-two bits of the fractional parts of the square * roots of the first eight prime numbers: 2, 3, 5, 7, 11, 13, * 17, 19." */ ctx->H[0] = UINT32_C (0x6a09e667); ctx->H[1] = UINT32_C (0xbb67ae85); ctx->H[2] = UINT32_C (0x3c6ef372); ctx->H[3] = UINT32_C (0xa54ff53a); ctx->H[4] = UINT32_C (0x510e527f); ctx->H[5] = UINT32_C (0x9b05688c); ctx->H[6] = UINT32_C (0x1f83d9ab); ctx->H[7] = UINT32_C (0x5be0cd19); /* Initialise number of bytes. */ ctx->count = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of SHA-256 transformation. * Gets full 64 bytes block of data and updates hash values; * @param H hash values * @param data data, must be exactly 64 bytes long */ static void sha256_transform (uint32_t H[SHA256_DIGEST_SIZE_WORDS], const void *data) { /* Working variables, see FIPS PUB 180-4 paragraph 6.2. */ uint32_t a = H[0]; uint32_t b = H[1]; uint32_t c = H[2]; uint32_t d = H[3]; uint32_t e = H[4]; uint32_t f = H[5]; uint32_t g = H[6]; uint32_t h = H[7]; /* Data buffer, used as cyclic buffer. See FIPS PUB 180-4 paragraphs 5.2.1, 6.2. */ uint32_t W[16]; #ifndef _MHD_GET_32BIT_BE_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN)) { /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, SHA256_BLOCK_SIZE); /* The W[] buffer itself will be used as the source of the data, * but data will be reloaded in correct bytes order during * the next steps */ data = (const void *) W; } #endif /* _MHD_GET_32BIT_BE_UNALIGNED */ /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. See FIPS PUB 180-4 formulae 4.2, 4.3. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ /* Four 'Sigma' macro functions. See FIPS PUB 180-4 formulae 4.4, 4.5, 4.6, 4.7. */ #define SIG0(x) (_MHD_ROTR32 ((x), 2) ^ _MHD_ROTR32 ((x), 13) ^ \ _MHD_ROTR32 ((x), 22) ) #define SIG1(x) (_MHD_ROTR32 ((x), 6) ^ _MHD_ROTR32 ((x), 11) ^ \ _MHD_ROTR32 ((x), 25) ) #define sig0(x) (_MHD_ROTR32 ((x), 7) ^ _MHD_ROTR32 ((x), 18) ^ \ ((x) >> 3) ) #define sig1(x) (_MHD_ROTR32 ((x), 17) ^ _MHD_ROTR32 ((x),19) ^ \ ((x) >> 10) ) /* One step of SHA-256 computation, see FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: this macro updates working variables in-place, without rotation. * Note: first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in FIPS PUB 180-4 paragraph 6.2.2 step 3. second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA2STEP32(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt)); \ (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0) /* Get value of W(t) from input data buffer, See FIPS PUB 180-4 paragraph 6.2. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 paragraph 3.1.2. */ /* Use cast to (const void*) to mute compiler alignment warning, * data was already aligned in previous step */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_32BIT_BE ((const void*)(((const uint8_t*) (buf)) + \ (t) * SHA256_BYTES_IN_WORD)) /* 'W' generation and assignment for 16 <= t <= 63. See FIPS PUB 180-4 paragraph 6.2.2. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as cyclic buffer. * Note: ((t-16)&0xf) have same value as (t&0xf) */ #define Wgen(w,t) ( (w)[(t - 16) & 0xf] + sig1 ((w)[((t) - 2) & 0xf]) \ + (w)[((t) - 7) & 0xf] + sig0 ((w)[((t) - 15) & 0xf]) ) #ifndef MHD_FAVOR_SMALL_CODE /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for K values. */ /* Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA2STEP32(a, b, c, d, e, f, g, h, K[0], data[0]); SHA2STEP32(h, a, b, c, d, e, f, g, K[1], data[1]); so current 'vD' will be used as 'vE' on next step, current 'vH' will be used as 'vA' on next step. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN if ((const void *) W == data) { /* The input data is already in the cyclic data buffer W[] in correct bytes order. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0]); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1]); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2]); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3]); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4]); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5]); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6]); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7]); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8]); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9]); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10]); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11]); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12]); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13]); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14]); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15]); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ if (1) { /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0] = \ GET_W_FROM_DATA (data, 0)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1] = \ GET_W_FROM_DATA (data, 1)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2] = \ GET_W_FROM_DATA (data, 2)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3] = \ GET_W_FROM_DATA (data, 3)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4] = \ GET_W_FROM_DATA (data, 4)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5] = \ GET_W_FROM_DATA (data, 5)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6] = \ GET_W_FROM_DATA (data, 6)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7] = \ GET_W_FROM_DATA (data, 7)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8] = \ GET_W_FROM_DATA (data, 8)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9] = \ GET_W_FROM_DATA (data, 9)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10] = \ GET_W_FROM_DATA (data, 10)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11] = \ GET_W_FROM_DATA (data, 11)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12] = \ GET_W_FROM_DATA (data, 12)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13] = \ GET_W_FROM_DATA (data, 13)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14] = \ GET_W_FROM_DATA (data, 14)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15] = \ GET_W_FROM_DATA (data, 15)); } /* During last 48 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for K values. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xe49b69c1), W[16 & 0xf] = \ Wgen (W,16)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xefbe4786), W[17 & 0xf] = \ Wgen (W,17)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x0fc19dc6), W[18 & 0xf] = \ Wgen (W,18)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x240ca1cc), W[19 & 0xf] = \ Wgen (W,19)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x2de92c6f), W[20 & 0xf] = \ Wgen (W,20)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4a7484aa), W[21 & 0xf] = \ Wgen (W,21)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5cb0a9dc), W[22 & 0xf] = \ Wgen (W,22)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x76f988da), W[23 & 0xf] = \ Wgen (W,23)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x983e5152), W[24 & 0xf] = \ Wgen (W,24)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa831c66d), W[25 & 0xf] = \ Wgen (W,25)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb00327c8), W[26 & 0xf] = \ Wgen (W,26)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xbf597fc7), W[27 & 0xf] = \ Wgen (W,27)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xc6e00bf3), W[28 & 0xf] = \ Wgen (W,28)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd5a79147), W[29 & 0xf] = \ Wgen (W,29)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x06ca6351), W[30 & 0xf] = \ Wgen (W,30)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x14292967), W[31 & 0xf] = \ Wgen (W,31)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x27b70a85), W[32 & 0xf] = \ Wgen (W,32)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x2e1b2138), W[33 & 0xf] = \ Wgen (W,33)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x4d2c6dfc), W[34 & 0xf] = \ Wgen (W,34)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x53380d13), W[35 & 0xf] = \ Wgen (W,35)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x650a7354), W[36 & 0xf] = \ Wgen (W,36)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x766a0abb), W[37 & 0xf] = \ Wgen (W,37)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x81c2c92e), W[38 & 0xf] = \ Wgen (W,38)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x92722c85), W[39 & 0xf] = \ Wgen (W,39)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xa2bfe8a1), W[40 & 0xf] = \ Wgen (W,40)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa81a664b), W[41 & 0xf] = \ Wgen (W,41)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xc24b8b70), W[42 & 0xf] = \ Wgen (W,42)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xc76c51a3), W[43 & 0xf] = \ Wgen (W,43)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xd192e819), W[44 & 0xf] = \ Wgen (W,44)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd6990624), W[45 & 0xf] = \ Wgen (W,45)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xf40e3585), W[46 & 0xf] = \ Wgen (W,46)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x106aa070), W[47 & 0xf] = \ Wgen (W,47)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x19a4c116), W[48 & 0xf] = \ Wgen (W,48)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x1e376c08), W[49 & 0xf] = \ Wgen (W,49)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x2748774c), W[50 & 0xf] = \ Wgen (W,50)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x34b0bcb5), W[51 & 0xf] = \ Wgen (W,51)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x391c0cb3), W[52 & 0xf] = \ Wgen (W,52)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4ed8aa4a), W[53 & 0xf] = \ Wgen (W,53)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5b9cca4f), W[54 & 0xf] = \ Wgen (W,54)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x682e6ff3), W[55 & 0xf] = \ Wgen (W,55)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x748f82ee), W[56 & 0xf] = \ Wgen (W,56)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x78a5636f), W[57 & 0xf] = \ Wgen (W,57)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x84c87814), W[58 & 0xf] = \ Wgen (W,58)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x8cc70208), W[59 & 0xf] = \ Wgen (W,59)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x90befffa), W[60 & 0xf] = \ Wgen (W,60)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xa4506ceb), W[61 & 0xf] = \ Wgen (W,61)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xbef9a3f7), W[62 & 0xf] = \ Wgen (W,62)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc67178f2), W[63 & 0xf] = \ Wgen (W,63)); #else /* ! MHD_FAVOR_SMALL_CODE */ if (1) { unsigned int t; /* K constants array. See FIPS PUB 180-4 paragraph 4.2.2 for K values. */ static const uint32_t K[80] = { UINT32_C (0x428a2f98), UINT32_C (0x71374491), UINT32_C (0xb5c0fbcf), UINT32_C (0xe9b5dba5), UINT32_C (0x3956c25b), UINT32_C (0x59f111f1), UINT32_C (0x923f82a4), UINT32_C (0xab1c5ed5), UINT32_C (0xd807aa98), UINT32_C (0x12835b01), UINT32_C (0x243185be), UINT32_C (0x550c7dc3), UINT32_C (0x72be5d74), UINT32_C (0x80deb1fe), UINT32_C (0x9bdc06a7), UINT32_C (0xc19bf174), UINT32_C (0xe49b69c1), UINT32_C (0xefbe4786), UINT32_C (0x0fc19dc6), UINT32_C (0x240ca1cc), UINT32_C (0x2de92c6f), UINT32_C (0x4a7484aa), UINT32_C (0x5cb0a9dc), UINT32_C (0x76f988da), UINT32_C (0x983e5152), UINT32_C (0xa831c66d), UINT32_C (0xb00327c8), UINT32_C (0xbf597fc7), UINT32_C (0xc6e00bf3), UINT32_C (0xd5a79147), UINT32_C (0x06ca6351), UINT32_C (0x14292967), UINT32_C (0x27b70a85), UINT32_C (0x2e1b2138), UINT32_C (0x4d2c6dfc), UINT32_C (0x53380d13), UINT32_C (0x650a7354), UINT32_C (0x766a0abb), UINT32_C (0x81c2c92e), UINT32_C (0x92722c85), UINT32_C (0xa2bfe8a1), UINT32_C (0xa81a664b), UINT32_C (0xc24b8b70), UINT32_C (0xc76c51a3), UINT32_C (0xd192e819), UINT32_C (0xd6990624), UINT32_C (0xf40e3585), UINT32_C (0x106aa070), UINT32_C (0x19a4c116), UINT32_C (0x1e376c08), UINT32_C (0x2748774c), UINT32_C (0x34b0bcb5), UINT32_C (0x391c0cb3), UINT32_C (0x4ed8aa4a), UINT32_C (0x5b9cca4f), UINT32_C (0x682e6ff3), UINT32_C (0x748f82ee), UINT32_C (0x78a5636f), UINT32_C (0x84c87814), UINT32_C (0x8cc70208), UINT32_C (0x90befffa), UINT32_C (0xa4506ceb), UINT32_C (0xbef9a3f7), UINT32_C (0xc67178f2) }; /* One step of SHA-256 computation with working variables rotation, see FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: this version of macro reassign all working variable on each step. */ #define SHA2STEP32RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ uint32_t tmp_h_ = (vH); \ SHA2STEP32((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt)); \ (vH) = (vG); \ (vG) = (vF); \ (vF) = (vE); \ (vE) = (vD); \ (vD) = (vC); \ (vC) = (vB); \ (vB) = (vA); \ (vA) = tmp_h_; } while (0) /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ for (t = 0; t < 16; ++t) { SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], \ W[t] = GET_W_FROM_DATA (data, t)); } /* During last 48 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ for (t = 16; t < 64; ++t) { SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], W[t & 15] = Wgen (W,t)); } } #endif /* ! MHD_FAVOR_SMALL_CODE */ /* Compute intermediate hash. See FIPS PUB 180-4 paragraph 6.2.2 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; } /** * Process portion of bytes. * * @param ctx_ must be a `struct Sha256Ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256Ctx *ctx, const uint8_t *data, size_t length) { unsigned bytes_have; /**< Number of bytes in buffer */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* MHD_FAVOR_SMALL_CODE */ /* Note: (count & (SHA256_BLOCK_SIZE-1)) equals (count % SHA256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned bytes_left = SHA256_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha256_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA256_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha256_transform (ctx->H, data); data += SHA256_BLOCK_SIZE; length -= SHA256_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" padding addition in bytes. * See FIPS PUB 180-4 paragraph 5.1.1. */ #define SHA256_SIZE_OF_LEN_ADD (64 / 8) /** * Finalise SHA256 calculation, return digest. * * @param ctx_ must be a `struct Sha256Ctx *` * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish (struct Sha256Ctx *ctx, uint8_t digest[SHA256_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned bytes_have; /**< Number of bytes in buffer */ num_bits = ctx->count << 3; /* Note: (count & (SHA256_BLOCK_SIZE-1)) equal (count % SHA256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See FIPS PUB 180-4 paragraph 5.1.1. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of first padding bit in byte is always predefined (0x80). */ /* Buffer always have space at least for one byte (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (SHA256_BLOCK_SIZE - bytes_have < SHA256_SIZE_OF_LEN_ADD) { /* No space in current block to put total length of message. Pad current block with zeros and process it. */ if (bytes_have < SHA256_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA256_BLOCK_SIZE - bytes_have); /* Process full block. */ sha256_transform (ctx->H, ctx->buffer); /* Start new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA256_BLOCK_SIZE - SHA256_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in processed message as big-endian value. */ _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA256_BLOCK_SIZE_WORDS - 2, num_bits); /* Process full final block. */ sha256_transform (ctx->H, ctx->buffer); /* Put final hash/digest in BE mode */ #ifndef _MHD_PUT_32BIT_BE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint32_t alig_dgst[SHA256_DIGEST_SIZE_WORDS]; _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]); _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]); _MHD_PUT_32BIT_BE (alig_dgst + 5, ctx->H[5]); _MHD_PUT_32BIT_BE (alig_dgst + 6, ctx->H[6]); _MHD_PUT_32BIT_BE (alig_dgst + 7, ctx->H[7]); /* Copy result to unaligned destination address */ memcpy (digest, alig_dgst, SHA256_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_32BIT_BE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_BE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA256_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA256_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA256_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA256_BYTES_IN_WORD), ctx->H[3]); _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA256_BYTES_IN_WORD), ctx->H[4]); _MHD_PUT_32BIT_BE ((void *) (digest + 5 * SHA256_BYTES_IN_WORD), ctx->H[5]); _MHD_PUT_32BIT_BE ((void *) (digest + 6 * SHA256_BYTES_IN_WORD), ctx->H[6]); _MHD_PUT_32BIT_BE ((void *) (digest + 7 * SHA256_BYTES_IN_WORD), ctx->H[7]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_BE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Sha256Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.2/src/microhttpd/sha512_256.h0000644000175000017500000000711115035214301016005 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha512_256.h * @brief Calculation of SHA-512/256 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA512_256_H #define MHD_SHA512_256_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Number of bits in single SHA-512/256 word. */ #define SHA512_256_WORD_SIZE_BITS 64 /** * Number of bytes in single SHA-512/256 word. */ #define SHA512_256_BYTES_IN_WORD (SHA512_256_WORD_SIZE_BITS / 8) /** * Hash is kept internally as 8 64-bit words. * This is intermediate hash size, used during computing the final digest. */ #define SHA512_256_HASH_SIZE_WORDS 8 /** * Size of SHA-512/256 resulting digest in bytes. * This is the final digest size, not intermediate hash. */ #define SHA512_256_DIGEST_SIZE_WORDS (SHA512_256_HASH_SIZE_WORDS / 2) /** * Size of SHA-512/256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA512_256_DIGEST_SIZE \ (SHA512_256_DIGEST_SIZE_WORDS * SHA512_256_BYTES_IN_WORD) /** * Size of SHA-512/256 digest string in chars including termination NUL. */ #define SHA512_256_DIGEST_STRING_SIZE ((SHA512_256_DIGEST_SIZE) * 2 + 1) /** * Size of SHA-512/256 single processing block in bits. */ #define SHA512_256_BLOCK_SIZE_BITS 1024 /** * Size of SHA-512/256 single processing block in bytes. */ #define SHA512_256_BLOCK_SIZE (SHA512_256_BLOCK_SIZE_BITS / 8) /** * Size of SHA-512/256 single processing block in words. */ #define SHA512_256_BLOCK_SIZE_WORDS \ (SHA512_256_BLOCK_SIZE_BITS / SHA512_256_WORD_SIZE_BITS) /** * SHA-512/256 calculation context */ struct Sha512_256Ctx { uint64_t H[SHA512_256_HASH_SIZE_WORDS]; /**< Intermediate hash value */ uint64_t buffer[SHA512_256_BLOCK_SIZE_WORDS]; /**< SHA512_256 input data buffer */ /** * The number of bytes, lower part */ uint64_t count; /** * The number of bits, high part. * Unlike lower part, this counts the number of bits, not bytes. */ uint64_t count_bits_hi; }; /** * Initialise structure for SHA-512/256 calculation. * * @param ctx the calculation context */ void MHD_SHA512_256_init (struct Sha512_256Ctx *ctx); /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA512_256_update (struct Sha512_256Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise SHA-512/256 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes */ void MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx, uint8_t digest[SHA512_256_DIGEST_SIZE]); #endif /* MHD_SHA512_256_H */ libmicrohttpd-1.0.2/src/microhttpd/test_sha1.c0000644000175000017500000003750114760713574016326 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha1.h * @brief Unit tests for SHA-1 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "sha1.h" #include "test_helpers.h" #include #include #include static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA1_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D}}, {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), {0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1}}, {D_STR_W_LEN (""), {0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09}}, {D_STR_W_LEN ("The quick brown fox jumps over the lazy dog"), {0x2f, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc, 0xed, 0x84, 0x9e, 0xe1, 0xbb, 0x76, 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0xa7, 0x08, 0x9e, 0x3d, 0xe1, 0x6b, 0x63, 0xa3, 0x2a, 0x43, 0xa5, 0xe7, 0xf3, 0xb5, 0x4f, 0x80, 0x6a, 0xc8, 0x4f, 0x53}}, {D_STR_W_LEN ("Simple string."), {0x6c, 0x6c, 0x9c, 0xef, 0x53, 0xff, 0x22, 0x39, 0x0c, 0x54, 0xc7, 0xba, 0x6d, 0x98, 0xe0, 0xd5, 0x6c, 0x24, 0x0d, 0x55}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37, 0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0x59, 0x0f, 0xc8, 0xea, 0xde, 0xa2, 0x78, 0x65, 0x5a, 0xf2, 0xa1, 0xe5, 0xb4, 0xc9, 0x61, 0xa4, 0x3a, 0xc3, 0x6a, 0x83}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xa7, 0x87, 0x4c, 0x16, 0xc0, 0x4e, 0xd6, 0x24, 0x5f, 0x25, 0xbe, 0x06, 0x7b, 0x1b, 0x6b, 0xaf, 0xf4, 0x0e, 0x74, 0x0b}}, }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA1_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37, 0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 }, /* 'A' x 72 times */ {0x41, 0xf9, 0x07, 0x05, 0x04, 0xf9, 0xc8, 0x1a, 0xbf, 0xbb, 0x61, 0x4d, 0xaa, 0xec, 0x3b, 0x26, 0xa2, 0xf9, 0x23, 0x7e}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,43, 44, 45, 46, 47, 48, 49, 50, 51, 52,53, 54, 55, 56, 57, 58, 59, 60,61, 62, 63, 64, 65, 66, 67,68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0xf2, 0x50, 0xb2, 0x79, 0x62, 0xcc, 0xff, 0x4b, 0x1b, 0x61, 0x4a, 0x6f, 0x80, 0xec, 0x9b, 0x4d, 0xd0, 0xc0, 0xfb, 0x7b}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,32, 33, 34, 35, 36, 37, 38, 39, 40, 41,42, 43, 44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56,57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0xf0, 0xa3, 0xfc, 0x4b, 0x90, 0x6f, 0x1b, 0x41, 0x68, 0xc8, 0x3e, 0x05, 0xb0, 0xc5, 0xac, 0xb7, 0x3d, 0xcd, 0x6b, 0x0f}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,62, 63, 64, 65, 66, 67, 68, 69, 70, 71,72, 73, 74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86,87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x93, 0xa4, 0x9c, 0x5f, 0xda, 0x22, 0x63, 0x73, 0x85, 0xeb, 0x70, 0xd2, 0x00, 0x52, 0x0c, 0xb0, 0x2e, 0x86, 0x9b, 0xa0 }}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38, 39, 40, 41, 42, 43, 44, 45,46, 47, 48, 49, 50, 51, 52,53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,71, 72},72}, /* 1..72 sequence */ {0x8b, 0x30, 0xd3, 0x41, 0x89, 0xb6, 0x1b, 0x66, 0x5a, 0x1a, 0x9a, 0x51, 0x64, 0x93, 0xab, 0x5e, 0x78, 0x81, 0x52, 0xb5}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140,141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167,168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180,181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220,221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,235, 236, 237, 238, 239, 240,241, 242, 243, 244, 245, 246, 247,248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x49, 0x16, 0xd6, 0xbd, 0xb7, 0xf7, 0x8e, 0x68, 0x03, 0x69, 0x8c, 0xab, 0x32, 0xd1, 0x58, 0x6e, 0xa4, 0x57, 0xdf, 0xc8}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,185, 184, 183, 182, 181, 180,179, 178, 177, 176, 175, 174, 173,172, 171, 170, 169, 168, 167, 166,165, 164, 163, 162, 161, 160,159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146,145, 144, 143, 142, 141, 140,139}, 61}, /* 199..139 sequence */ {0xb3, 0xec, 0x61, 0x3c, 0xf7, 0x36, 0x57, 0x94, 0x61, 0xdb, 0xb2, 0x16, 0x75, 0xfe, 0x34, 0x60, 0x99, 0x94, 0xb5, 0xfc}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x99, 0x1d, 0xc6, 0x95, 0xe1, 0xaa, 0xcc, 0xc9, 0x35, 0x60, 0xbe, 0xe3, 0xe2, 0x41, 0x2b, 0xa7, 0xab, 0x49, 0x32, 0xf7}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x9e, 0xb6, 0xce, 0x48, 0xf4, 0x6e, 0x9c, 0xf4, 0x1b, 0x4f, 0x9f, 0x66, 0xdd, 0xe8, 0x41, 0x01, 0x71, 0xf6, 0xf5, 0xd6}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA1_DIGEST_SIZE], const uint8_t expected[SHA1_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA1_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA1_DIGEST_STRING_SIZE]; char expc_str[SHA1_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str); bin2hex (expected, SHA1_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA1_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s matches " \ "expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units1_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units2_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } return num_failed; } /* Calculated SHA-256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units1_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units2_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA1_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { struct sha1_ctx ctx; uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA1_DIGEST_SIZE); MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA1_finish (&ctx, unaligned_digest); num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/mhd_panic.c0000644000175000017500000000577214760713574016362 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_panic.h * @brief MHD_panic() function and helpers * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_panic.h" #include "platform.h" #include "microhttpd.h" /** * Handler for fatal errors. */ MHD_PanicCallback mhd_panic = (MHD_PanicCallback) NULL; /** * Closure argument for #mhd_panic. */ void *mhd_panic_cls = NULL; /** * Default implementation of the panic function, * prints an error message and aborts. * * @param cls unused * @param file name of the file with the problem * @param line line number with the problem * @param reason error message with details */ _MHD_NORETURN static void mhd_panic_std (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; /* Mute compiler warning. */ #ifdef HAVE_MESSAGES fprintf (stderr, _ ("Fatal error in GNU libmicrohttpd %s:%u: %s\n"), file, line, reason); #else /* ! HAVE_MESSAGES */ (void) file; /* Mute compiler warning. */ (void) line; /* Mute compiler warning. */ (void) reason; /* Mute compiler warning. */ #endif abort (); } /** * Sets the global error handler to a different implementation. * * @a cb will only be called in the case of typically fatal, serious internal * consistency issues or serious system failures like failed lock of mutex. * * These issues should only arise in the case of serious memory corruption or * similar problems with the architecture, there is no safe way to continue * even for closing of the application. * * The default implementation that is used if no panic function is set simply * prints an error message and calls `abort()`. * Alternative implementations might call `exit()` or other similar functions. * * @param cb new error handler or NULL to use default handler * @param cls passed to @a cb * @ingroup logging */ _MHD_EXTERN void MHD_set_panic_func (MHD_PanicCallback cb, void *cls) { if ((MHD_PanicCallback) NULL != cb) mhd_panic = cb; else mhd_panic = &mhd_panic_std; mhd_panic_cls = cls; } libmicrohttpd-1.0.2/src/microhttpd/test_postprocessor_large.c0000644000175000017500000000675714760713574021602 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor_large.c * @brief Testcase with very large input for postprocessor * @author Christian Grothoff */ #include "platform.h" #include "microhttpd.h" #include "internal.h" #include "mhd_compat.h" #ifndef WINDOWS #include #endif static enum MHD_Result value_checker (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { size_t *pos = (size_t *) cls; (void) kind; (void) key; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) data; (void) off; /* Unused. Silent compiler warning. */ #if 0 fprintf (stderr, "VC: %" PRIu64 " %u `%s' `%s' `%s' `%s' `%.*s'\n", off, size, key, filename, content_type, transfer_encoding, size, data); #endif if (size == 0) return MHD_YES; *pos += size; return MHD_YES; } static unsigned int test_simple_large (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; size_t i; size_t delta; size_t size; char data[102400]; size_t pos; pos = 0; memset (data, 'A', sizeof (data)); memcpy (data, "key=", 4); data[sizeof (data) - 1] = '\0'; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &pos); i = 0; size = strlen (data); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &data[i], delta)) { fprintf (stderr, "MHD_post_process() failed!\n"); MHD_destroy_post_processor (pp); return 1; } i += delta; } MHD_destroy_post_processor (pp); if (pos != sizeof (data) - 5) /* minus 0-termination and 'key=' */ return 1; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_simple_large (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/md5.c0000644000175000017500000005076515035214301015103 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/md5.c * @brief Calculation of MD5 digest as defined in RFC 1321 * @author Karlson2k (Evgeny Grin) */ #include "md5.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for MD5 calculation. * * @param ctx the calculation context */ void MHD_MD5_init (struct Md5Ctx *ctx) { /* Initial hash values, see RFC 1321, Clause 3.3 (step 3). */ /* Note: values specified in RFC by bytes and should be loaded in little-endian mode, therefore hash values here are initialised with original bytes used in little-endian order. */ ctx->H[0] = UINT32_C (0x67452301); ctx->H[1] = UINT32_C (0xefcdab89); ctx->H[2] = UINT32_C (0x98badcfe); ctx->H[3] = UINT32_C (0x10325476); /* Initialise the number of bytes. */ ctx->count = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of MD5 transformation. * Gets full 64 bytes block of data and updates hash values; * @param H hash values * @param M the data buffer with #MD5_BLOCK_SIZE bytes block */ static void md5_transform (uint32_t H[MD5_HASH_SIZE_WORDS], const void *M) { /* Working variables, See RFC 1321, Clause 3.4 (step 4). */ uint32_t A = H[0]; uint32_t B = H[1]; uint32_t C = H[2]; uint32_t D = H[3]; /* The data buffer. See RFC 1321, Clause 3.4 (step 4). */ uint32_t X[16]; #ifndef _MHD_GET_32BIT_LE_UNALIGNED if (0 != (((uintptr_t) M) % _MHD_UINT32_ALIGN)) { /* The input data is unaligned. */ /* Copy the unaligned input data to the aligned buffer. */ memcpy (X, M, sizeof(X)); /* The X[] buffer itself will be used as the source of the data, * but the data will be reloaded in correct bytes order on * the next steps. */ M = (const void *) X; } #endif /* _MHD_GET_32BIT_LE_UNALIGNED */ /* Four auxiliary functions, see RFC 1321, Clause 3.4 (step 4). */ /* Some optimisations used. */ /* #define F_FUNC(x,y,z) (((x)&(y)) | ((~(x))&(z))) */ /* Original version */ #define F_FUNC(x,y,z) ((((y) ^ (z)) & (x)) ^ (z)) /* #define G_FUNC_1(x,y,z) (((x)&(z)) | ((y)&(~(z)))) */ /* Original version */ /* #define G_FUNC_2(x,y,z) UINT32_C(0) */ /* Original version */ #ifndef MHD_FAVOR_SMALL_CODE # define G_FUNC_1(x,y,z) ((~(z)) & (y)) # define G_FUNC_2(x,y,z) ((z) & (x)) #else /* MHD_FAVOR_SMALL_CODE */ # define G_FUNC_1(x,y,z) ((((x) ^ (y)) & (z)) ^ (y)) # define G_FUNC_2(x,y,z) UINT32_C(0) #endif /* MHD_FAVOR_SMALL_CODE */ #define H_FUNC(x,y,z) ((x) ^ (y) ^ (z)) /* Original version */ /* #define I_FUNC(x,y,z) ((y) ^ ((x) | (~(z)))) */ /* Original version */ #define I_FUNC(x,y,z) (((~(z)) | (x)) ^ (y)) /* One step of round 1 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R1(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += F_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* Get value of X(k) from input data buffer. See RFC 1321 Clause 3.4 (step 4). */ #define GET_X_FROM_DATA(buf,t) \ _MHD_GET_32BIT_LE (((const uint32_t*) (buf)) + (t)) /* One step of round 2 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R2(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += G_FUNC_1((vb),(vc),(vd)); \ (va) += G_FUNC_2((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* One step of round 3 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R3(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += H_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* One step of round 4 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R4(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += I_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) #if ! defined(MHD_FAVOR_SMALL_CODE) /* Round 1. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN if ((const void *) X == M) { /* The input data is already in the data buffer X[] in correct bytes order. */ MD5STEP_R1 (A, B, C, D, X[0], 7, UINT32_C (0xd76aa478)); MD5STEP_R1 (D, A, B, C, X[1], 12, UINT32_C (0xe8c7b756)); MD5STEP_R1 (C, D, A, B, X[2], 17, UINT32_C (0x242070db)); MD5STEP_R1 (B, C, D, A, X[3], 22, UINT32_C (0xc1bdceee)); MD5STEP_R1 (A, B, C, D, X[4], 7, UINT32_C (0xf57c0faf)); MD5STEP_R1 (D, A, B, C, X[5], 12, UINT32_C (0x4787c62a)); MD5STEP_R1 (C, D, A, B, X[6], 17, UINT32_C (0xa8304613)); MD5STEP_R1 (B, C, D, A, X[7], 22, UINT32_C (0xfd469501)); MD5STEP_R1 (A, B, C, D, X[8], 7, UINT32_C (0x698098d8)); MD5STEP_R1 (D, A, B, C, X[9], 12, UINT32_C (0x8b44f7af)); MD5STEP_R1 (C, D, A, B, X[10], 17, UINT32_C (0xffff5bb1)); MD5STEP_R1 (B, C, D, A, X[11], 22, UINT32_C (0x895cd7be)); MD5STEP_R1 (A, B, C, D, X[12], 7, UINT32_C (0x6b901122)); MD5STEP_R1 (D, A, B, C, X[13], 12, UINT32_C (0xfd987193)); MD5STEP_R1 (C, D, A, B, X[14], 17, UINT32_C (0xa679438e)); MD5STEP_R1 (B, C, D, A, X[15], 22, UINT32_C (0x49b40821)); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN */ if (1) { /* The input data is loaded in correct (little-endian) format before calculations on each step. */ MD5STEP_R1 (A, B, C, D, X[0] = GET_X_FROM_DATA (M, 0), 7, \ UINT32_C (0xd76aa478)); MD5STEP_R1 (D, A, B, C, X[1] = GET_X_FROM_DATA (M, 1), 12, \ UINT32_C (0xe8c7b756)); MD5STEP_R1 (C, D, A, B, X[2] = GET_X_FROM_DATA (M, 2), 17, \ UINT32_C (0x242070db)); MD5STEP_R1 (B, C, D, A, X[3] = GET_X_FROM_DATA (M, 3), 22, \ UINT32_C (0xc1bdceee)); MD5STEP_R1 (A, B, C, D, X[4] = GET_X_FROM_DATA (M, 4), 7, \ UINT32_C (0xf57c0faf)); MD5STEP_R1 (D, A, B, C, X[5] = GET_X_FROM_DATA (M, 5), 12, \ UINT32_C (0x4787c62a)); MD5STEP_R1 (C, D, A, B, X[6] = GET_X_FROM_DATA (M, 6), 17, \ UINT32_C (0xa8304613)); MD5STEP_R1 (B, C, D, A, X[7] = GET_X_FROM_DATA (M, 7), 22, \ UINT32_C (0xfd469501)); MD5STEP_R1 (A, B, C, D, X[8] = GET_X_FROM_DATA (M, 8), 7, \ UINT32_C (0x698098d8)); MD5STEP_R1 (D, A, B, C, X[9] = GET_X_FROM_DATA (M, 9), 12, \ UINT32_C (0x8b44f7af)); MD5STEP_R1 (C, D, A, B, X[10] = GET_X_FROM_DATA (M, 10), 17, \ UINT32_C (0xffff5bb1)); MD5STEP_R1 (B, C, D, A, X[11] = GET_X_FROM_DATA (M, 11), 22, \ UINT32_C (0x895cd7be)); MD5STEP_R1 (A, B, C, D, X[12] = GET_X_FROM_DATA (M, 12), 7, \ UINT32_C (0x6b901122)); MD5STEP_R1 (D, A, B, C, X[13] = GET_X_FROM_DATA (M, 13), 12, \ UINT32_C (0xfd987193)); MD5STEP_R1 (C, D, A, B, X[14] = GET_X_FROM_DATA (M, 14), 17, \ UINT32_C (0xa679438e)); MD5STEP_R1 (B, C, D, A, X[15] = GET_X_FROM_DATA (M, 15), 22, \ UINT32_C (0x49b40821)); } /* Round 2. */ MD5STEP_R2 (A, B, C, D, X[1], 5, UINT32_C (0xf61e2562)); MD5STEP_R2 (D, A, B, C, X[6], 9, UINT32_C (0xc040b340)); MD5STEP_R2 (C, D, A, B, X[11], 14, UINT32_C (0x265e5a51)); MD5STEP_R2 (B, C, D, A, X[0], 20, UINT32_C (0xe9b6c7aa)); MD5STEP_R2 (A, B, C, D, X[5], 5, UINT32_C (0xd62f105d)); MD5STEP_R2 (D, A, B, C, X[10], 9, UINT32_C (0x02441453)); MD5STEP_R2 (C, D, A, B, X[15], 14, UINT32_C (0xd8a1e681)); MD5STEP_R2 (B, C, D, A, X[4], 20, UINT32_C (0xe7d3fbc8)); MD5STEP_R2 (A, B, C, D, X[9], 5, UINT32_C (0x21e1cde6)); MD5STEP_R2 (D, A, B, C, X[14], 9, UINT32_C (0xc33707d6)); MD5STEP_R2 (C, D, A, B, X[3], 14, UINT32_C (0xf4d50d87)); MD5STEP_R2 (B, C, D, A, X[8], 20, UINT32_C (0x455a14ed)); MD5STEP_R2 (A, B, C, D, X[13], 5, UINT32_C (0xa9e3e905)); MD5STEP_R2 (D, A, B, C, X[2], 9, UINT32_C (0xfcefa3f8)); MD5STEP_R2 (C, D, A, B, X[7], 14, UINT32_C (0x676f02d9)); MD5STEP_R2 (B, C, D, A, X[12], 20, UINT32_C (0x8d2a4c8a)); /* Round 3. */ MD5STEP_R3 (A, B, C, D, X[5], 4, UINT32_C (0xfffa3942)); MD5STEP_R3 (D, A, B, C, X[8], 11, UINT32_C (0x8771f681)); MD5STEP_R3 (C, D, A, B, X[11], 16, UINT32_C (0x6d9d6122)); MD5STEP_R3 (B, C, D, A, X[14], 23, UINT32_C (0xfde5380c)); MD5STEP_R3 (A, B, C, D, X[1], 4, UINT32_C (0xa4beea44)); MD5STEP_R3 (D, A, B, C, X[4], 11, UINT32_C (0x4bdecfa9)); MD5STEP_R3 (C, D, A, B, X[7], 16, UINT32_C (0xf6bb4b60)); MD5STEP_R3 (B, C, D, A, X[10], 23, UINT32_C (0xbebfbc70)); MD5STEP_R3 (A, B, C, D, X[13], 4, UINT32_C (0x289b7ec6)); MD5STEP_R3 (D, A, B, C, X[0], 11, UINT32_C (0xeaa127fa)); MD5STEP_R3 (C, D, A, B, X[3], 16, UINT32_C (0xd4ef3085)); MD5STEP_R3 (B, C, D, A, X[6], 23, UINT32_C (0x04881d05)); MD5STEP_R3 (A, B, C, D, X[9], 4, UINT32_C (0xd9d4d039)); MD5STEP_R3 (D, A, B, C, X[12], 11, UINT32_C (0xe6db99e5)); MD5STEP_R3 (C, D, A, B, X[15], 16, UINT32_C (0x1fa27cf8)); MD5STEP_R3 (B, C, D, A, X[2], 23, UINT32_C (0xc4ac5665)); /* Round 4. */ MD5STEP_R4 (A, B, C, D, X[0], 6, UINT32_C (0xf4292244)); MD5STEP_R4 (D, A, B, C, X[7], 10, UINT32_C (0x432aff97)); MD5STEP_R4 (C, D, A, B, X[14], 15, UINT32_C (0xab9423a7)); MD5STEP_R4 (B, C, D, A, X[5], 21, UINT32_C (0xfc93a039)); MD5STEP_R4 (A, B, C, D, X[12], 6, UINT32_C (0x655b59c3)); MD5STEP_R4 (D, A, B, C, X[3], 10, UINT32_C (0x8f0ccc92)); MD5STEP_R4 (C, D, A, B, X[10], 15, UINT32_C (0xffeff47d)); MD5STEP_R4 (B, C, D, A, X[1], 21, UINT32_C (0x85845dd1)); MD5STEP_R4 (A, B, C, D, X[8], 6, UINT32_C (0x6fa87e4f)); MD5STEP_R4 (D, A, B, C, X[15], 10, UINT32_C (0xfe2ce6e0)); MD5STEP_R4 (C, D, A, B, X[6], 15, UINT32_C (0xa3014314)); MD5STEP_R4 (B, C, D, A, X[13], 21, UINT32_C (0x4e0811a1)); MD5STEP_R4 (A, B, C, D, X[4], 6, UINT32_C (0xf7537e82)); MD5STEP_R4 (D, A, B, C, X[11], 10, UINT32_C (0xbd3af235)); MD5STEP_R4 (C, D, A, B, X[2], 15, UINT32_C (0x2ad7d2bb)); MD5STEP_R4 (B, C, D, A, X[9], 21, UINT32_C (0xeb86d391)); #else /* MHD_FAVOR_SMALL_CODE */ if (1) { static const uint32_t T[64] = { UINT32_C (0xd76aa478), UINT32_C (0xe8c7b756), UINT32_C (0x242070db), UINT32_C (0xc1bdceee), UINT32_C (0xf57c0faf), UINT32_C (0x4787c62a), UINT32_C (0xa8304613), UINT32_C (0xfd469501), UINT32_C (0x698098d8), UINT32_C (0x8b44f7af), UINT32_C (0xffff5bb1), UINT32_C (0x895cd7be), UINT32_C (0x6b901122), UINT32_C (0xfd987193), UINT32_C (0xa679438e), UINT32_C (0x49b40821), UINT32_C (0xf61e2562), UINT32_C (0xc040b340), UINT32_C (0x265e5a51), UINT32_C (0xe9b6c7aa), UINT32_C (0xd62f105d), UINT32_C (0x02441453), UINT32_C (0xd8a1e681), UINT32_C (0xe7d3fbc8), UINT32_C (0x21e1cde6), UINT32_C (0xc33707d6), UINT32_C (0xf4d50d87), UINT32_C (0x455a14ed), UINT32_C (0xa9e3e905), UINT32_C (0xfcefa3f8), UINT32_C (0x676f02d9), UINT32_C (0x8d2a4c8a), UINT32_C (0xfffa3942), UINT32_C (0x8771f681), UINT32_C (0x6d9d6122), UINT32_C (0xfde5380c), UINT32_C (0xa4beea44), UINT32_C (0x4bdecfa9), UINT32_C (0xf6bb4b60), UINT32_C (0xbebfbc70), UINT32_C (0x289b7ec6), UINT32_C (0xeaa127fa), UINT32_C (0xd4ef3085), UINT32_C (0x04881d05), UINT32_C (0xd9d4d039), UINT32_C (0xe6db99e5), UINT32_C (0x1fa27cf8), UINT32_C (0xc4ac5665), UINT32_C (0xf4292244), UINT32_C (0x432aff97), UINT32_C (0xab9423a7), UINT32_C (0xfc93a039), UINT32_C (0x655b59c3), UINT32_C (0x8f0ccc92), UINT32_C (0xffeff47d), UINT32_C (0x85845dd1), UINT32_C (0x6fa87e4f), UINT32_C (0xfe2ce6e0), UINT32_C (0xa3014314), UINT32_C (0x4e0811a1), UINT32_C (0xf7537e82), UINT32_C (0xbd3af235), UINT32_C (0x2ad7d2bb), UINT32_C (0xeb86d391) }; unsigned int i; /**< Zero-based index */ /* Round 1. */ i = 0; do { /* The input data is loaded in correct (little-endian) format before calculations on each step. */ MD5STEP_R1 (A, B, C, D, X[i] = GET_X_FROM_DATA (M, i), 7, T[i]); ++i; MD5STEP_R1 (D, A, B, C, X[i] = GET_X_FROM_DATA (M, i), 12, T[i]); ++i; MD5STEP_R1 (C, D, A, B, X[i] = GET_X_FROM_DATA (M, i), 17, T[i]); ++i; MD5STEP_R1 (B, C, D, A, X[i] = GET_X_FROM_DATA (M, i), 22, T[i]); ++i; } while (i < 16); /* Round 2. */ do { const unsigned int idx_add = i; MD5STEP_R2 (A, B, C, D, X[(1U + idx_add) & 15U], 5, T[i]); ++i; MD5STEP_R2 (D, A, B, C, X[(6U + idx_add) & 15U], 9, T[i]); ++i; MD5STEP_R2 (C, D, A, B, X[(11U + idx_add) & 15U], 14, T[i]); ++i; MD5STEP_R2 (B, C, D, A, X[(0U + idx_add) & 15U], 20, T[i]); ++i; } while (i < 32); /* Round 3. */ do { const unsigned int idx_add = i; MD5STEP_R3 (A, B, C, D, X[(5U + 64U - idx_add) & 15U], 4, T[i]); ++i; MD5STEP_R3 (D, A, B, C, X[(8U + 64U - idx_add) & 15U], 11, T[i]); ++i; MD5STEP_R3 (C, D, A, B, X[(11U + 64U - idx_add) & 15U], 16, T[i]); ++i; MD5STEP_R3 (B, C, D, A, X[(14U + 64U - idx_add) & 15U], 23, T[i]); ++i; } while (i < 48); /* Round 4. */ do { const unsigned int idx_add = i; MD5STEP_R4 (A, B, C, D, X[(0U + 64U - idx_add) & 15U], 6, T[i]); ++i; MD5STEP_R4 (D, A, B, C, X[(7U + 64U - idx_add) & 15U], 10, T[i]); ++i; MD5STEP_R4 (C, D, A, B, X[(14U + 64U - idx_add) & 15U], 15, T[i]); ++i; MD5STEP_R4 (B, C, D, A, X[(5U + 64U - idx_add) & 15U], 21, T[i]); ++i; } while (i < 64); } #endif /* MHD_FAVOR_SMALL_CODE */ /* Finally increment and store working variables. See RFC 1321, end of Clause 3.4 (step 4). */ H[0] += A; H[1] += B; H[2] += C; H[3] += D; } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5Ctx *ctx, const uint8_t *data, size_t length) { unsigned int bytes_have; /**< Number of bytes in the context buffer */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* MHD_FAVOR_SMALL_CODE */ /* Note: (count & (MD5_BLOCK_SIZE-1)) equals (count % MD5_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned int bytes_left = MD5_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process the full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; md5_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (MD5_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ md5_transform (ctx->H, data); data += MD5_BLOCK_SIZE; length -= MD5_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" insertion in bits. * See RFC 1321, end of Clause 3.2 (step 2). */ #define MD5_SIZE_OF_LEN_ADD_BITS 64 /** * Size of "length" insertion in bytes. */ #define MD5_SIZE_OF_LEN_ADD (MD5_SIZE_OF_LEN_ADD_BITS / 8) /** * Finalise MD5 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish (struct Md5Ctx *ctx, uint8_t digest[MD5_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned int bytes_have; /**< Number of bytes in the context buffer */ /* Memorise the number of processed bits. The padding and other data added here during the postprocessing must not change the amount of hashed data. */ num_bits = ctx->count << 3; /* Note: (count & (MD5_BLOCK_SIZE-1)) equals (count % MD5_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See RFC 1321, Clauses 3.1 and 3.2 (steps 1 and 2). */ /* Data is always processed in form of bytes (not by individual bits), therefore position of the first padding bit in byte is always predefined (0x80). */ /* Buffer always have space for one byte at least (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (MD5_BLOCK_SIZE - bytes_have < MD5_SIZE_OF_LEN_ADD) { /* No space in the current block to put the total length of message. Pad the current block with zeros and process it. */ if (bytes_have < MD5_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, MD5_BLOCK_SIZE - bytes_have); /* Process the full block. */ md5_transform (ctx->H, ctx->buffer); /* Start the new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, MD5_BLOCK_SIZE - MD5_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in processed data as little-endian value. See RFC 1321, clauses 2 and 3.2 (step 2). */ _MHD_PUT_64BIT_LE_SAFE (ctx->buffer + MD5_BLOCK_SIZE_WORDS - 2, num_bits); /* Process the full final block. */ md5_transform (ctx->H, ctx->buffer); /* Put in LE mode the hash as the final digest. See RFC 1321, clauses 2 and 3.5 (step 5). */ #ifndef _MHD_PUT_32BIT_LE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint32_t alig_dgst[MD5_DIGEST_SIZE_WORDS]; _MHD_PUT_32BIT_LE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_LE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_LE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_LE (alig_dgst + 3, ctx->H[3]); /* Copy result to the unaligned destination address. */ memcpy (digest, alig_dgst, MD5_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_32BIT_LE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_LE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_LE ((void *) (digest + 0 * MD5_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_LE ((void *) (digest + 1 * MD5_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_LE ((void *) (digest + 2 * MD5_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_LE ((void *) (digest + 3 * MD5_BYTES_IN_WORD), ctx->H[3]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_LE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Md5Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.2/src/microhttpd/mhd_bithelpers.h0000644000175000017500000004023615035214301017404 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_bithelpers.h * @brief macros for bits manipulations * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BITHELPERS_H #define MHD_BITHELPERS_H 1 #include "mhd_options.h" #include #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Declarations for VC & Clang/C2 built-ins */ #include #endif /* _MSC_FULL_VER */ #include "mhd_byteorder.h" #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN || _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #include "mhd_align.h" #endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN || _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ #ifndef __has_builtin /* Avoid precompiler errors with non-clang */ # define __has_builtin(x) 0 # define _MHD_has_builtin_dummy 1 #endif MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ #ifdef MHD_HAVE___BUILTIN_BSWAP32 #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) __builtin_bswap32 ((uint32_t) value32)) #elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 may not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_byteswap_ulong) #endif /* ! __clang__ */ #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) _byteswap_ulong ((uint32_t) value32)) #elif \ __has_builtin (__builtin_bswap32) #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) __builtin_bswap32 ((uint32_t) value32)) #else /* ! __has_builtin(__builtin_bswap32) */ #define _MHD_BYTES_SWAP32(value32) \ ( (((uint32_t) (value32)) << 24) \ | ((((uint32_t) (value32)) & ((uint32_t) 0x0000FF00)) << 8) \ | ((((uint32_t) (value32)) & ((uint32_t) 0x00FF0000)) >> 8) \ | (((uint32_t) (value32)) >> 24) ) #endif /* ! __has_builtin(__builtin_bswap32) */ #ifdef MHD_HAVE___BUILTIN_BSWAP64 #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) __builtin_bswap64 ((uint64_t) value64)) #elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 may not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_byteswap_uint64) #endif /* ! __clang__ */ #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) _byteswap_uint64 ((uint64_t) value64)) #elif \ __has_builtin (__builtin_bswap64) #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) __builtin_bswap64 ((uint64_t) value64)) #else /* ! __has_builtin(__builtin_bswap64) */ #define _MHD_BYTES_SWAP64(value64) \ ( (((uint64_t) (value64)) << 56) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x000000000000FF00)) << 40) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x0000000000FF0000)) << 24) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x00000000FF000000)) << 8) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x000000FF00000000)) >> 8) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x0000FF0000000000)) >> 24) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x00FF000000000000)) >> 40) \ | (((uint64_t) (value64)) >> 56) ) #endif /* ! __has_builtin(__builtin_bswap64) */ /* _MHD_PUT_64BIT_LE (addr, value64) * put native-endian 64-bit value64 to addr * in little-endian mode. */ /* Slow version that works with unaligned addr and with any bytes order */ #define _MHD_PUT_64BIT_LE_SLOW(addr, value64) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_64BIT_LE(addr, value64) \ ((*(uint64_t*) (addr)) = (uint64_t) (value64)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_64BIT_LE(addr, value64) \ ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_64BIT_LE(addr, value64) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) /* Indicate that _MHD_PUT_64BIT_LE does not need aligned pointer */ #define _MHD_PUT_64BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Put result safely to unaligned address */ _MHD_static_inline void _MHD_PUT_64BIT_LE_SAFE (void *dst, uint64_t value) { #ifndef _MHD_PUT_64BIT_LE_UNALIGNED if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN)) _MHD_PUT_64BIT_LE_SLOW (dst, value); else #endif /* ! _MHD_PUT_64BIT_LE_UNALIGNED */ _MHD_PUT_64BIT_LE (dst, value); } /* _MHD_PUT_32BIT_LE (addr, value32) * put native-endian 32-bit value32 to addr * in little-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_32BIT_LE(addr,value32) \ ((*(uint32_t*) (addr)) = (uint32_t) (value32)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_32BIT_LE(addr, value32) \ ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_32BIT_LE(addr, value32) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint32_t) (value32)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint32_t) (value32)) >> 24); \ } while (0) /* Indicate that _MHD_PUT_32BIT_LE does not need aligned pointer */ #define _MHD_PUT_32BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* _MHD_GET_32BIT_LE (addr) * get little-endian 32-bit value storied at addr * and return it in native-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_32BIT_LE(addr) \ (*(const uint32_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_32BIT_LE(addr) \ _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_32BIT_LE(addr) \ ( ( (uint32_t) (((const uint8_t*) addr)[0])) \ | (((uint32_t) (((const uint8_t*) addr)[1])) << 8) \ | (((uint32_t) (((const uint8_t*) addr)[2])) << 16) \ | (((uint32_t) (((const uint8_t*) addr)[3])) << 24) ) /* Indicate that _MHD_GET_32BIT_LE does not need aligned pointer */ #define _MHD_GET_32BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* _MHD_PUT_64BIT_BE (addr, value64) * put native-endian 64-bit value64 to addr * in big-endian mode. */ /* Slow version that works with unaligned addr and with any bytes order */ #define _MHD_PUT_64BIT_BE_SLOW(addr, value64) do { \ ((uint8_t*) (addr))[7] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[0] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_64BIT_BE(addr, value64) \ ((*(uint64_t*) (addr)) = (uint64_t) (value64)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_64BIT_BE(addr, value64) \ ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_64BIT_BE(addr, value64) _MHD_PUT_64BIT_BE_SLOW(addr, value64) /* Indicate that _MHD_PUT_64BIT_BE does not need aligned pointer */ #define _MHD_PUT_64BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Put result safely to unaligned address */ _MHD_static_inline void _MHD_PUT_64BIT_BE_SAFE (void *dst, uint64_t value) { #ifndef _MHD_PUT_64BIT_BE_UNALIGNED if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN)) _MHD_PUT_64BIT_BE_SLOW (dst, value); else #endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */ _MHD_PUT_64BIT_BE (dst, value); } /* _MHD_GET_64BIT_BE (addr) * load 64-bit value located at addr in big endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_64BIT_BE(addr) \ (*(const uint64_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_64BIT_BE(addr) \ _MHD_BYTES_SWAP64 (*(const uint64_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_64BIT_BE(addr) \ ( (((uint64_t) (((const uint8_t*) addr)[0])) << 56) \ | (((uint64_t) (((const uint8_t*) addr)[1])) << 48) \ | (((uint64_t) (((const uint8_t*) addr)[2])) << 40) \ | (((uint64_t) (((const uint8_t*) addr)[3])) << 32) \ | (((uint64_t) (((const uint8_t*) addr)[4])) << 24) \ | (((uint64_t) (((const uint8_t*) addr)[5])) << 16) \ | (((uint64_t) (((const uint8_t*) addr)[6])) << 8) \ | ((uint64_t) (((const uint8_t*) addr)[7])) ) /* Indicate that _MHD_GET_64BIT_BE does not need aligned pointer */ #define _MHD_GET_64BIT_BE_ALLOW_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* _MHD_PUT_32BIT_BE (addr, value32) * put native-endian 32-bit value32 to addr * in big-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_32BIT_BE(addr, value32) \ ((*(uint32_t*) (addr)) = (uint32_t) (value32)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_32BIT_BE(addr, value32) \ ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_32BIT_BE(addr, value32) do { \ ((uint8_t*) (addr))[3] = (uint8_t) ((uint32_t) (value32)); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 8); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 16); \ ((uint8_t*) (addr))[0] = (uint8_t) (((uint32_t) (value32)) >> 24); \ } while (0) /* Indicate that _MHD_PUT_32BIT_BE does not need aligned pointer */ #define _MHD_PUT_32BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* _MHD_GET_32BIT_BE (addr) * get big-endian 32-bit value storied at addr * and return it in native-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_32BIT_BE(addr) \ (*(const uint32_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_32BIT_BE(addr) \ _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_32BIT_BE(addr) \ ( (((uint32_t) (((const uint8_t*) addr)[0])) << 24) \ | (((uint32_t) (((const uint8_t*) addr)[1])) << 16) \ | (((uint32_t) (((const uint8_t*) addr)[2])) << 8) \ | ((uint32_t) (((const uint8_t*) addr)[3])) ) /* Indicate that _MHD_GET_32BIT_BE does not need aligned pointer */ #define _MHD_GET_32BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /** * Rotate right 32-bit value by number of bits. * bits parameter must be more than zero and must be less than 32. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotr) #endif /* ! __clang__ */ #define _MHD_ROTR32(value32, bits) \ ((uint32_t) _rotr ((uint32_t) (value32),(bits))) #elif __has_builtin (__builtin_rotateright32) #define _MHD_ROTR32(value32, bits) \ ((uint32_t) __builtin_rotateright32 ((value32), (bits))) #else /* ! __builtin_rotateright32 */ _MHD_static_inline uint32_t _MHD_ROTR32 (uint32_t value32, int bits) { bits %= 32; if (0 == bits) return value32; /* Defined in form which modern compiler could optimize. */ return (value32 >> bits) | (value32 << (32 - bits)); } #endif /* ! __builtin_rotateright32 */ /** * Rotate left 32-bit value by number of bits. * bits parameter must be more than zero and must be less than 32. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotl) #endif /* ! __clang__ */ #define _MHD_ROTL32(value32, bits) \ ((uint32_t) _rotl ((uint32_t) (value32),(bits))) #elif __has_builtin (__builtin_rotateleft32) #define _MHD_ROTL32(value32, bits) \ ((uint32_t) __builtin_rotateleft32 ((value32), (bits))) #else /* ! __builtin_rotateleft32 */ _MHD_static_inline uint32_t _MHD_ROTL32 (uint32_t value32, int bits) { bits %= 32; if (0 == bits) return value32; /* Defined in form which modern compiler could optimize. */ return (value32 << bits) | (value32 >> (32 - bits)); } #endif /* ! __builtin_rotateleft32 */ /** * Rotate right 64-bit value by number of bits. * bits parameter must be more than zero and must be less than 64. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimisations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotr64) #endif /* ! __clang__ */ #define _MHD_ROTR64(value64, bits) \ ((uint64_t) _rotr64 ((uint64_t) (value64),(bits))) #elif __has_builtin (__builtin_rotateright64) #define _MHD_ROTR64(value64, bits) \ ((uint64_t) __builtin_rotateright64 ((value64), (bits))) #else /* ! __builtin_rotateright64 */ _MHD_static_inline uint64_t _MHD_ROTR64 (uint64_t value64, int bits) { bits %= 64; if (0 == bits) return value64; /* Defined in form which modern compiler could optimise. */ return (value64 >> bits) | (value64 << (64 - bits)); } #endif /* ! __builtin_rotateright64 */ MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ #ifdef _MHD_has_builtin_dummy /* Remove macro function replacement to avoid misdetection in files which * include this header */ # undef __has_builtin #endif #endif /* ! MHD_BITHELPERS_H */ libmicrohttpd-1.0.2/src/microhttpd/test_shutdown_select.c0000644000175000017500000002406114760713574020701 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file microhttpd/test_shutdown_select.c * @brief Test whether shutdown socket triggers select()/poll() * @details On some platforms shutting down the socket in one thread * triggers select() or poll() waiting for this socket in * other thread. libmicrohttpd depends on this behavior on * these platforms. This program check whether select() * and poll() (if available) work as expected. * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include "mhd_sockets.h" #include #include #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #if defined(MHD_USE_POSIX_THREADS) #include #endif /* MHD_USE_POSIX_THREADS */ #if defined(MHD_WINSOCK_SOCKETS) #include #include #define sock_errno (WSAGetLastError ()) #elif defined(MHD_POSIX_SOCKETS) #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_ARPA_INET_H #include #endif /* HAVE_ARPA_INET_H */ #ifdef HAVE_SYS_SELECT_H #include #endif /* HAVE_SYS_SELECT_H */ #if defined(HAVE_POLL) && defined(HAVE_POLL_H) #include #endif /* HAVE_POLL && HAVE_POLL_H */ #define sock_errno (errno) #endif /* MHD_POSIX_SOCKETS */ #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_threads.h" #ifndef SOMAXCONN #define SOMAXCONN 511 #endif /* ! SOMAXCONN */ #if ! defined(SHUT_RDWR) && defined(SD_BOTH) #define SHUT_RDWR SD_BOTH #endif static bool check_err; static bool has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return true; return strstr (prog_name + name_pos, marker) != NULL; } static MHD_socket start_socket_listen (int domain) { /* Create sockets similarly to daemon.c */ MHD_socket fd; int cloexec_set; struct sockaddr_in sock_addr; socklen_t addrlen; #ifdef MHD_WINSOCK_SOCKETS unsigned long flags = 1; #else /* MHD_POSIX_SOCKETS */ int flags; #endif /* MHD_POSIX_SOCKETS */ #if defined(MHD_POSIX_SOCKETS) && defined(SOCK_CLOEXEC) fd = socket (domain, SOCK_STREAM | SOCK_CLOEXEC, 0); cloexec_set = 1; #elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT) fd = WSASocketW (domain, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT); cloexec_set = 1; #else /* !SOCK_CLOEXEC */ fd = socket (domain, SOCK_STREAM, 0); cloexec_set = 0; #endif /* !SOCK_CLOEXEC */ if ( (MHD_INVALID_SOCKET == fd) && (cloexec_set) ) { fd = socket (domain, SOCK_STREAM, 0); cloexec_set = 0; } if (MHD_INVALID_SOCKET == fd) { fprintf (stderr, "Can't create socket: %u\n", (unsigned) sock_errno); return MHD_INVALID_SOCKET; } if (! cloexec_set) { #ifdef MHD_WINSOCK_SOCKETS if (! SetHandleInformation ((HANDLE) fd, HANDLE_FLAG_INHERIT, 0)) fprintf (stderr, "Failed to make socket non-inheritable: %u\n", (unsigned int) GetLastError ()); #else /* MHD_POSIX_SOCKETS */ flags = fcntl (fd, F_GETFD); if ( ( (-1 == flags) || ( (flags != (flags | FD_CLOEXEC)) && (0 != fcntl (fd, F_SETFD, flags | FD_CLOEXEC)) ) ) ) fprintf (stderr, "Failed to make socket non-inheritable: %s\n", MHD_socket_last_strerr_ ()); #endif /* MHD_POSIX_SOCKETS */ } memset (&sock_addr, 0, sizeof (struct sockaddr_in)); sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons (0); #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sock_addr.sin_len = sizeof (struct sockaddr_in); #endif addrlen = sizeof (struct sockaddr_in); if (bind (fd, (const struct sockaddr *) &sock_addr, addrlen) < 0) { fprintf (stderr, "Failed to bind socket: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #ifdef MHD_WINSOCK_SOCKETS if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) { fprintf (stderr, "Failed to make socket non-blocking: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #else /* MHD_POSIX_SOCKETS */ flags = fcntl (fd, F_GETFL); if ( ( (-1 == flags) || ( (flags != (flags | O_NONBLOCK)) && (0 != fcntl (fd, F_SETFL, flags | O_NONBLOCK)) ) ) ) { fprintf (stderr, "Failed to make socket non-blocking: %s\n", MHD_socket_last_strerr_ ()); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #endif /* MHD_POSIX_SOCKETS */ if (listen (fd, SOMAXCONN) < 0) { fprintf (stderr, "Failed to listen on socket: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } return fd; } static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ select_thread (void *data) { /* use select() like in daemon.c */ MHD_socket listen_sock = *((MHD_socket *) data); fd_set rs, ws; struct timeval timeout; FD_ZERO (&rs); FD_ZERO (&ws); FD_SET (listen_sock, &rs); timeout.tv_usec = 0; timeout.tv_sec = 7; check_err = (0 > MHD_SYS_select_ (listen_sock + 1, &rs, &ws, NULL, &timeout)); return (MHD_THRD_RTRN_TYPE_) 0; } #ifdef HAVE_POLL static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ poll_thread (void *data) { /* use poll() like in daemon.c */ struct pollfd p[1]; MHD_socket listen_sock = *((MHD_socket *) data); p[0].fd = listen_sock; p[0].events = POLLIN; p[0].revents = 0; check_err = (0 > MHD_sys_poll_ (p, 1, 7000)); return (MHD_THRD_RTRN_TYPE_) 0; } #endif /* HAVE_POLL */ static void local_sleep (unsigned seconds) { #if defined(_WIN32) && ! defined(__CYGWIN__) Sleep (seconds * 1000); #else unsigned seconds_left = seconds; do { seconds_left = sleep (seconds_left); } while (seconds_left > 0); #endif } int main (int argc, char *const *argv) { int i; time_t start_t, end_t; int result = 0; MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ * test_func)(void *data); #ifdef MHD_WINSOCK_SOCKETS WORD ver_req; WSADATA wsa_data; int err; #endif /* MHD_WINSOCK_SOCKETS */ bool test_poll; bool must_ignore; (void) argc; /* Unused. Silent compiler warning. */ test_poll = has_in_name (argv[0], "_poll"); must_ignore = has_in_name (argv[0], "_ignore"); if (! test_poll) test_func = &select_thread; else { #ifndef HAVE_POLL return 77; #else /* ! HAVE_POLL */ test_func = &poll_thread; #endif /* ! HAVE_POLL */ } #ifdef MHD_WINSOCK_SOCKETS ver_req = MAKEWORD (2, 2); err = WSAStartup (ver_req, &wsa_data); if ((err != 0) || (MAKEWORD (2, 2) != wsa_data.wVersion)) { printf ("WSAStartup() failed\n"); WSACleanup (); return 99; } #endif /* MHD_WINSOCK_SOCKETS */ /* try several times to ensure that accidental incoming connection * didn't interfere with test results */ for (i = 0; i < 5 && result == 0; i++) { MHD_thread_handle_native_ sel_thrd; /* fprintf(stdout, "Creating, binding and listening socket...\n"); */ MHD_socket listen_socket = start_socket_listen (AF_INET); if (MHD_INVALID_SOCKET == listen_socket) return 99; check_err = true; /* fprintf (stdout, "Starting select() thread...\n"); */ #if defined(MHD_USE_POSIX_THREADS) if (0 != pthread_create (&sel_thrd, NULL, test_func, &listen_socket)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't start thread\n"); return 99; } #elif defined(MHD_USE_W32_THREADS) sel_thrd = (HANDLE) (uintptr_t) _beginthreadex (NULL, 0, test_func, &listen_socket, 0, NULL); if (0 == (sel_thrd)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't start select() thread\n"); return 99; } #else #error No threading lib available #endif /* fprintf (stdout, "Waiting...\n"); */ local_sleep (1); /* make sure that select() is started */ /* fprintf (stdout, "Shutting down socket...\n"); */ start_t = time (NULL); shutdown (listen_socket, SHUT_RDWR); /* fprintf (stdout, "Waiting for thread to finish...\n"); */ if (! MHD_join_thread_ (sel_thrd)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't join select() thread\n"); return 99; } if (check_err) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Error in waiting thread\n"); return 99; } end_t = time (NULL); /* fprintf (stdout, "Thread finished.\n"); */ MHD_socket_close_chk_ (listen_socket); if ((start_t == (time_t) -1) || (end_t == (time_t) -1) ) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't get current time\n"); return 99; } if (end_t - start_t > 3) result++; } #ifdef MHD_WINSOCK_SOCKETS WSACleanup (); #endif /* MHD_WINSOCK_SOCKETS */ return must_ignore ? (! result) : (result); } libmicrohttpd-1.0.2/src/microhttpd/tsearch.c0000644000175000017500000000671114760713574016063 00000000000000/* * Tree search generalized from Knuth (6.2.2) Algorithm T just like * the AT&T man page says. * * The node_t structure is for internal use only, lint doesn't grok it. * * Written by reading the System V Interface Definition, not the code. * * Totally public domain. */ #include "mhd_options.h" #include "tsearch.h" #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ typedef struct node { const void *key; struct node *llink, *rlink; } node_t; /* $NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $ */ /* find or insert datum into search tree */ void * tsearch (const void *vkey, void **vrootp, int (*compar)(const void *, const void *)) { node_t *q; node_t **rootp = (node_t **) vrootp; if (rootp == NULL) return NULL; while (*rootp != NULL) /* Knuth's T1: */ { int r; if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ return *rootp; /* we found it! */ rootp = (r < 0) ? &(*rootp)->llink : /* T3: follow left branch */ &(*rootp)->rlink; /* T4: follow right branch */ } q = malloc (sizeof(node_t)); /* T5: key not found */ if (q != NULL) /* make new node */ { *rootp = q; /* link new node to old */ q->key = vkey; /* initialize new node */ q->llink = q->rlink = NULL; } return q; } /* $NetBSD: tfind.c,v 1.7 2012/06/25 22:32:45 abs Exp $ */ /* find a node by key "vkey" in tree "vrootp", or return 0 */ void * tfind (const void *vkey, void * const *vrootp, int (*compar)(const void *, const void *)) { node_t * const *rootp = (node_t * const *) vrootp; if (rootp == NULL) return NULL; while (*rootp != NULL) /* T1: */ { int r; if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ return *rootp; /* key found */ rootp = (r < 0) ? &(*rootp)->llink : /* T3: follow left branch */ &(*rootp)->rlink; /* T4: follow right branch */ } return NULL; } /* $NetBSD: tdelete.c,v 1.8 2016/01/20 20:47:41 christos Exp $ */ /* find a node with key "vkey" in tree "vrootp" */ void * tdelete (const void *vkey, void **vrootp, int (*compar)(const void *, const void *)) { node_t **rootp = (node_t **) vrootp; node_t *p, *q, *r; int cmp; if ((rootp == NULL) || ((p = *rootp) == NULL) ) return NULL; while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) { p = *rootp; rootp = (cmp < 0) ? &(*rootp)->llink : /* follow llink branch */ &(*rootp)->rlink; /* follow rlink branch */ if (*rootp == NULL) return NULL; /* key not found */ } r = (*rootp)->rlink; /* D1: */ if ((q = (*rootp)->llink) == NULL) /* Left NULL? */ q = r; else if (r != NULL) /* Right link is NULL? */ { if (r->llink == NULL) /* D2: Find successor */ { r->llink = q; q = r; } else /* D3: Find NULL link */ { for (q = r->llink; q->llink != NULL; q = r->llink) r = q; r->llink = q->rlink; q->llink = (*rootp)->llink; q->rlink = (*rootp)->rlink; } } free (*rootp); /* D4: Free node */ *rootp = q; /* link parent to new node */ return p; } /* end of tsearch.c */ libmicrohttpd-1.0.2/src/microhttpd/mhd_assert.h0000644000175000017500000000370014760713577016566 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_assert.h * @brief macros for mhd_assert() * @author Karlson2k (Evgeny Grin) */ /* Unlike POSIX version of 'assert.h', MHD version of 'assert' header * does not allow multiple redefinition of 'mhd_assert' macro within single * source file. */ #ifndef MHD_ASSERT_H #define MHD_ASSERT_H 1 #include "mhd_options.h" #if ! defined(_DEBUG) && ! defined(NDEBUG) #ifndef DEBUG /* Used by some toolchains */ #define NDEBUG 1 /* Use NDEBUG by default */ #else /* DEBUG */ #define _DEBUG 1 #endif /* DEBUG */ #endif /* !_DEBUG && !NDEBUG */ #if defined(_DEBUG) && defined(NDEBUG) #error Both _DEBUG and NDEBUG are defined #endif /* _DEBUG && NDEBUG */ #ifdef NDEBUG # define mhd_assert(ignore) ((void) 0) #else /* _DEBUG */ # ifdef HAVE_ASSERT # include # define mhd_assert(CHK) assert (CHK) # else /* ! HAVE_ASSERT */ # include # include # define mhd_assert(CHK) \ do { \ if (! (CHK)) { \ fprintf (stderr, "%s:%u Assertion failed: %s\nProgram aborted.\n", \ __FILE__, (unsigned) __LINE__, #CHK); \ fflush (stderr); abort (); } \ } while (0) # endif /* ! HAVE_ASSERT */ #endif /* _DEBUG */ #endif /* ! MHD_ASSERT_H */ libmicrohttpd-1.0.2/src/microhttpd/test_auth_parse.c0000644000175000017500000022626414760713574017633 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022-2023 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_auth_parse.c * @brief Unit tests for request's 'Authorization" headers parsing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "gen_auth.h" #ifdef BAUTH_SUPPORT #include "basicauth.h" #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT #include "digestauth.h" #endif /* DAUTH_SUPPORT */ #include "mhd_assert.h" #include "internal.h" #include "connection.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Declarations for local replacements of MHD functions */ /* None, headers are included */ /* Local replacements implementations */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size) { void *ret; if (NULL == connection) mhdErrorExitDesc ("'connection' parameter is NULL"); /* Use 'read_buffer' just as a flag */ if (NULL != connection->read_buffer) { /* Use 'write_buffer' just as a flag */ if (NULL != connection->write_buffer) mhdErrorExitDesc ("Unexpected third memory allocation, " \ "while previous allocations was not freed"); } /* Just use simple "malloc()" here */ ret = malloc (size); if (NULL == ret) externalErrorExit (); /* Track up to two allocations */ if (NULL == connection->read_buffer) connection->read_buffer = (char *) ret; else connection->write_buffer = (char *) ret; return ret; } /** * Static variable to avoid additional malloc()/free() pairs */ static struct MHD_Connection conn; void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...) { (void) daemon; if (! conn.rq.client_aware) { fprintf (stderr, "Unexpected call of 'MHD_LOG(), format is '%s'.\n", format); fprintf (stderr, "'Authorization' header value: '%s'.\n", (NULL == conn.rq.headers_received) ? "NULL" : (conn.rq.headers_received->value)); mhdErrorExit (); } conn.rq.client_aware = false; /* Clear the flag */ return; } /** * Static variable to avoid additional malloc()/free() pairs */ static struct MHD_HTTP_Req_Header req_header; static void test_global_init (void) { memset (&conn, 0, sizeof(conn)); memset (&req_header, 0, sizeof(req_header)); } /** * Add "Authorization" client test header. * * @param hdr the pointer to the headr value, must be valid until end of * checking of this header * @param hdr_len the length of the @a hdr * @note The function is NOT thread-safe */ static void add_AuthHeader (const char *hdr, size_t hdr_len) { if ((NULL != conn.rq.headers_received) || (NULL != conn.rq.headers_received_tail)) externalErrorExitDesc ("Connection's test headers are not empty already"); if (NULL != hdr) { /* Skip initial whitespaces, emulate MHD's headers processing */ while (' ' == hdr[0] || '\t' == hdr[0]) { hdr++; hdr_len--; } req_header.header = MHD_HTTP_HEADER_AUTHORIZATION; /* Static string */ req_header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); req_header.value = hdr; req_header.value_size = hdr_len; req_header.kind = MHD_HEADER_KIND; req_header.prev = NULL; req_header.next = NULL; conn.rq.headers_received = &req_header; conn.rq.headers_received_tail = &req_header; } else { conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; } conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */ } #ifdef BAUTH_SUPPORT /** * Parse previously added Basic Authorization client header and return * result of the parsing. * * Function performs basic checking of the parsing result * @return result of header parsing * @note The function is NOT thread-safe */ static const struct MHD_RqBAuth * get_BAuthRqParams (void) { const struct MHD_RqBAuth *res1; const struct MHD_RqBAuth *res2; /* Store pointer in some member unused in this test */ res1 = MHD_get_rq_bauth_params_ (&conn); if (! conn.rq.bauth_tried) mhdErrorExitDesc ("'rq.bauth_tried' is not set"); res2 = MHD_get_rq_bauth_params_ (&conn); if (res1 != res2) mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \ "when called for the second time"); return res2; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Parse previously added Digest Authorization client header and return * result of the parsing. * * Function performs basic checking of the parsing result * @return result of header parsing * @note The function is NOT thread-safe */ static const struct MHD_RqDAuth * get_DAuthRqParams (void) { const struct MHD_RqDAuth *res1; const struct MHD_RqDAuth *res2; /* Store pointer in some member unused in this test */ res1 = MHD_get_rq_dauth_params_ (&conn); if (! conn.rq.dauth_tried) mhdErrorExitDesc ("'rq.dauth_tried' is not set"); res2 = MHD_get_rq_dauth_params_ (&conn); if (res1 != res2) mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \ "when called for the second time"); return res2; } #endif /* DAUTH_SUPPORT */ static void clean_AuthHeaders (void) { conn.state = MHD_CONNECTION_INIT; free (conn.read_buffer); free (conn.write_buffer); #ifdef BAUTH_SUPPORT conn.rq.bauth_tried = false; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT conn.rq.dauth_tried = false; #endif /* BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if ((NULL != conn.rq.bauth) && (conn.read_buffer != (const char *) conn.rq.bauth) && (conn.write_buffer != (const char *) conn.rq.bauth)) externalErrorExitDesc ("Memory allocation is not tracked as it should be"); conn.rq.bauth = NULL; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if ((NULL != conn.rq.dauth) && (conn.read_buffer != (const char *) conn.rq.dauth) && (conn.write_buffer != (const char *) conn.rq.dauth)) externalErrorExitDesc ("Memory allocation is not tracked as it should be"); conn.rq.dauth = NULL; #endif /* BAUTH_SUPPORT */ conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; conn.read_buffer = NULL; conn.write_buffer = NULL; conn.rq.client_aware = false; } enum MHD_TestAuthType { MHD_TEST_AUTHTYPE_NONE, MHD_TEST_AUTHTYPE_BASIC, MHD_TEST_AUTHTYPE_DIGEST, }; /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_type_n (const char *hdr, size_t hdr_len, const enum MHD_TestAuthType expected_type, int expect_log, unsigned int line_num) { unsigned int ret; ret = 0; add_AuthHeader (hdr, hdr_len); if (expect_log) conn.rq.client_aware = true; /* Use like a flag */ else conn.rq.client_aware = false; #ifdef BAUTH_SUPPORT if (MHD_TEST_AUTHTYPE_BASIC == expected_type) { if (NULL == get_BAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Basic Authorization was not found, while it should be.\n"); ret++; } } else #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (MHD_TEST_AUTHTYPE_DIGEST == expected_type) { if (NULL == get_DAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Digest Authorization was not found, while it should be.\n"); ret++; } } else #endif /* BAUTH_SUPPORT */ { #ifdef BAUTH_SUPPORT if (NULL != get_BAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Found Basic Authorization, while it should not be.\n"); ret++; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (NULL != get_DAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Found Digest Authorization, while it should not be.\n"); ret++; } #endif /* DAUTH_SUPPORT */ } #if defined(BAUTH_SUPPORT) && defined(DAUTH_SUPPORT) if (conn.rq.client_aware) { fprintf (stderr, "'Authorization' header parsing ERROR:\n" "Log function must be called, but it was not.\n"); ret++; } #endif /* BAUTH_SUPPORT && DAUTH_SUPPORT */ if (ret) { if (NULL == hdr) fprintf (stderr, "Input: Absence of 'Authorization' header.\n"); else if (0 == hdr_len) fprintf (stderr, "Input: empty 'Authorization' header.\n"); else fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret = 1; } clean_AuthHeaders (); return ret; } #define expect_result_type(h,t,l) \ expect_result_type_n(h,MHD_STATICSTR_LEN_(h),t,l,__LINE__) static unsigned int check_type (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_type_n (NULL, 0, MHD_TEST_AUTHTYPE_NONE, 0, __LINE__); r += expect_result_type ("", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC abc ", MHD_TEST_AUTHTYPE_BASIC, 0); /* Only single token is allowed for 'Basic' Authorization */ r += expect_result_type ("Basic a b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic abc1 b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1 ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1\t", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c\tabc1\t", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1 b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx, b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx,b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx ,b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx;b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx; b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t \t Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 123", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t123", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 abc ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic \t\t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicDigest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic\0", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\0" "Basic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDigest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tDigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tdigEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tdigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tDIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest , ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest , ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t, ,\t, ,\t, ,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t,\t,\t,\t,\t,\t,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=b", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\"b\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=1", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=\"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=b ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=1 ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=\"1\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a = b", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a\t=\t\"b\"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc= \"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\tb ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a = \"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc\t\t\t= 1 ", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =\t\t\t\"1\" ", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1,,,,", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1 ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,,nc= \"1 \"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \" 1\"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\",,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc ,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc , ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest \tnc\t ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest \tnc\t ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc,uri", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1, uri,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri ,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri , ", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Binary zero */ r += expect_result_type ("Digest nc=1\0", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1\0" " ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1\t\0", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\0" "1", MHD_TEST_AUTHTYPE_NONE, 1); /* Semicolon */ r += expect_result_type ("Digest nc=1;", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1; ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=;1", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc;=1", MHD_TEST_AUTHTYPE_NONE, 1); /* The equal sign alone */ r += expect_result_type ("Digest =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest = ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest ,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest , =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest ,= ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest , = ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1, =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=bar,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=bar, =", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Unclosed quotation */ r += expect_result_type ("Digest nc=\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"abc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"abc ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"abc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"abc ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"bar", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"bar ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo= \" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\", bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Full set of parameters with semicolon inside */ r += expect_result_type ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001; cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001;cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest username;=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("2Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Digest2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" 2Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("2Digest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("a" "Digest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "\0", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\0" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); return r; } #ifdef BAUTH_SUPPORT /* return zero if succeed, 1 otherwise */ static unsigned int expect_basic_n (const char *hdr, size_t hdr_len, const char *tkn, size_t tkn_len, unsigned int line_num) { const struct MHD_RqBAuth *h; unsigned int ret; mhd_assert (NULL != hdr); mhd_assert (0 != hdr_len); add_AuthHeader (hdr, hdr_len); h = get_BAuthRqParams (); if (NULL == h) mhdErrorExitDesc ("'MHD_get_rq_bauth_params_()' returned NULL"); ret = 1; if (tkn_len != h->token68.len) fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Wrong token length:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n", (unsigned) h->token68.len, (int) h->token68.len, h->token68.str ? h->token68.str : "(NULL)", (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)"); else if ( ((NULL == tkn) != (NULL == h->token68.str)) || ((NULL != tkn) && (0 != memcmp (tkn, h->token68.str, tkn_len))) ) fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Wrong token string:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n", (unsigned) h->token68.len, (int) h->token68.len, h->token68.str ? h->token68.str : "(NULL)", (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)"); else ret = 0; if (0 != ret) { fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); } clean_AuthHeaders (); return ret; } #define expect_basic(h,t) \ expect_basic_n(h,MHD_STATICSTR_LEN_(h),t,MHD_STATICSTR_LEN_(t),__LINE__) static unsigned int check_basic (void) { unsigned int r = 0; /**< The number of errors */ r += expect_basic ("Basic a", "a"); r += expect_basic ("Basic a", "a"); r += expect_basic ("Basic \ta", "a"); r += expect_basic ("Basic \ta\t", "a"); r += expect_basic ("Basic \ta ", "a"); r += expect_basic ("Basic a ", "a"); r += expect_basic ("Basic \t a\t ", "a"); r += expect_basic ("Basic \t abc\t ", "abc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic -A.1-z~9+/=====", "-A.1-z~9+/====="); r += expect_basic (" Basic -A.1-z~9+/===== ", "-A.1-z~9+/====="); r += expect_basic_n ("Basic", MHD_STATICSTR_LEN_ ("Basic"), NULL, 0,__LINE__); r += expect_basic_n (" Basic", MHD_STATICSTR_LEN_ (" Basic"), NULL, 0, __LINE__); r += expect_basic_n ("Basic ", MHD_STATICSTR_LEN_ ("Basic "), NULL, 0, __LINE__); r += expect_basic_n ("Basic \t\t", MHD_STATICSTR_LEN_ ("Basic \t\t"), NULL, 0, __LINE__); return r; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /* return zero if succeed, 1 otherwise */ static unsigned int cmp_dauth_param (const char *pname, const struct MHD_RqDAuthParam *param, const char *expected_value) { unsigned int ret; size_t expected_len; bool expected_quoted; mhd_assert (NULL != param); mhd_assert (NULL != pname); ret = 0; if (NULL == expected_value) { expected_len = 0; expected_quoted = false; if (NULL != param->value.str) ret = 1; else if (param->value.len != expected_len) ret = 1; else if (param->quoted != expected_quoted) ret = 1; } else { expected_len = strlen (expected_value); expected_quoted = (NULL != memchr (expected_value, '\\', expected_len)); if (NULL == param->value.str) ret = 1; else if (param->value.len != expected_len) ret = 1; else if (param->quoted != expected_quoted) ret = 1; else if (0 != memcmp (param->value.str, expected_value, expected_len)) ret = 1; } if (0 != ret) { fprintf (stderr, "Parameter '%s' parsed incorrectly:\n", pname); fprintf (stderr, "\tRESULT :\tvalue.str: %.*s", (int) (param->value.str ? param->value.len : 6), param->value.str ? param->value.str : "(NULL)"); fprintf (stderr, "\tvalue.len: %u", (unsigned) param->value.len); fprintf (stderr, "\tquoted: %s\n", (unsigned) param->quoted ? "true" : "false"); fprintf (stderr, "\tEXPECTED:\tvalue.str: %.*s", (int) (expected_value ? expected_len : 6), expected_value ? expected_value : "(NULL)"); fprintf (stderr, "\tvalue.len: %u", (unsigned) expected_len); fprintf (stderr, "\tquoted: %s\n", (unsigned) expected_quoted ? "true" : "false"); } return ret; } /* return zero if succeed, 1 otherwise */ static unsigned int expect_digest_n (const char *hdr, size_t hdr_len, const char *nonce, enum MHD_DigestAuthAlgo3 algo3, const char *response, const char *username, const char *username_ext, const char *realm, const char *uri, const char *qop_raw, enum MHD_DigestAuthQOP qop, const char *cnonce, const char *nc, int userhash, unsigned int line_num) { const struct MHD_RqDAuth *h; unsigned int ret; mhd_assert (NULL != hdr); mhd_assert (0 != hdr_len); add_AuthHeader (hdr, hdr_len); h = get_DAuthRqParams (); if (NULL == h) mhdErrorExitDesc ("'MHD_get_rq_dauth_params_()' returned NULL"); ret = 0; ret += cmp_dauth_param ("nonce", &h->nonce, nonce); if (h->algo3 != algo3) { ret += 1; fprintf (stderr, "Parameter 'algorithm' detected incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%u\n", (unsigned) h->algo3); fprintf (stderr, "\tEXPECTED:\t%u\n", (unsigned) algo3); } ret += cmp_dauth_param ("response", &h->response, response); ret += cmp_dauth_param ("username", &h->username, username); ret += cmp_dauth_param ("username_ext", &h->username_ext, username_ext); ret += cmp_dauth_param ("realm", &h->realm, realm); ret += cmp_dauth_param ("uri", &h->uri, uri); ret += cmp_dauth_param ("qop", &h->qop_raw, qop_raw); if (h->qop != qop) { ret += 1; fprintf (stderr, "Parameter 'qop' detected incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%u\n", (unsigned) h->qop); fprintf (stderr, "\tEXPECTED:\t%u\n", (unsigned) qop); } ret += cmp_dauth_param ("cnonce", &h->cnonce, cnonce); ret += cmp_dauth_param ("nc", &h->nc, nc); if (h->userhash != ! (! userhash)) { ret += 1; fprintf (stderr, "Parameter 'userhash' parsed incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%s\n", h->userhash ? "true" : "false"); fprintf (stderr, "\tEXPECTED:\t%s\n", userhash ? "true" : "false"); } if (0 != ret) { fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); } clean_AuthHeaders (); return ret; } #define expect_digest(h,no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh) \ expect_digest_n(h,MHD_STATICSTR_LEN_(h),\ no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh,__LINE__) static unsigned int check_digest (void) { unsigned int r = 0; /**< The number of errors */ r += expect_digest ("Digest", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest nc=1", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, NULL, \ MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\" ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,nc=\"1\" ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\" , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=1, ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=1 , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=1, ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=1 , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=\"1 \", ", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \" ,", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1;", 0); r += expect_digest ("Digest nc=\"1\\;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1\\;", 0); r += expect_digest ("Digest userhash=false", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=\"false\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=foo", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=true", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=\"true\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=\"\\t\\r\\u\\e\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=TRUE", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=True", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash = true", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=True2", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=\" true\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=md5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=Md5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=mD5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"MD5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"\\M\\D\\5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"\\m\\d\\5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=sha-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=Sha-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"SHA-256\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"SHA\\-25\\6\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"shA-256\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-SESS", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=md5-Sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256-seSS", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-512-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA512_256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-512-256-sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-2", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-sess2", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256-512", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest qop=auth", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=Auth", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "Auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=AUTH", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "AUTH", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"\\A\\ut\\H\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "\\A\\ut\\H", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth \"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth ", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0); r += expect_digest ("Digest qop=auth-int", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth-int\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auTh-iNt\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auTh-iNt", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auTh-iNt2\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auTh-iNt2", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0); r += expect_digest ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", " \ "nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_MD5, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ NULL, "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, \ "0a4f113b", "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=test@example.com, " \ "realm=users@example.com, algorithm=\"SHA-256-sess\", " \ "nonce=32141232413abcde, " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=/example, qop=\"auth\", nc=\"00000001\", " \ "cnonce=0a4f113b, " \ "response=6629fae49393a05397450978507c4ef1, " \ "opaque=sadfljk32sdaf", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username = \"test@example.com\", " \ "realm\t=\t\"users@example.com\", algorithm\t= SHA-256, " \ "nonce\t= \"32141232413abcde\", " \ "username*\t=\tUTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri = \"/example\", qop = auth, nc\t=\t00000001, " \ "cnonce\t\t\t= \"0a4f113b\", " \ "response =\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\t\t\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\"," \ "realm=\"users@example.com\",algorithm=SHA-512-256," \ "nonce=\"32141232413abcde\"," \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \ "uri=\"/example\",qop=auth,nc=00000001," \ "cnonce=\"0a4f113b\"," \ "response=\"6629fae49393a05397450978507c4ef1\"," \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA512_256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\"," \ "realm=\"users@example.com\",algorithm=SHA-256," \ "nonce=\"32141232413abcde\",asdf=asdffdsaf," \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \ "uri=\"/example\",qop=auth,nc=00000001,cnonce=\"0a4f113b\"," \ "response=\"6629fae49393a05397450978507c4ef1\"," \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx, username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",,,,,", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx\", username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \ "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \ "32141232413abcde", MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\",nc=02\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); return r; } #endif /* DAUTH_SUPPORT */ #define TEST_AUTH_STR "dXNlcjpwYXNz" static unsigned int check_two_auths (void) { unsigned int ret; static struct MHD_HTTP_Req_Header h1; static struct MHD_HTTP_Req_Header h2; static struct MHD_HTTP_Req_Header h3; #ifdef BAUTH_SUPPORT const struct MHD_RqBAuth *bauth; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT const struct MHD_RqDAuth *dauth; #endif /* DAUTH_SUPPORT */ if ((NULL != conn.rq.headers_received) || (NULL != conn.rq.headers_received_tail)) externalErrorExitDesc ("Connection's test headers are not empty already"); /* Init and use both Basic and Digest Auth headers */ memset (&h1, 0, sizeof(h1)); memset (&h2, 0, sizeof(h2)); memset (&h3, 0, sizeof(h3)); h1.kind = MHD_HEADER_KIND; h1.header = MHD_HTTP_HEADER_HOST; /* Just some random header */ h1.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); h1.value = "localhost"; h1.value_size = strlen (h1.value); h2.kind = MHD_HEADER_KIND; h2.header = MHD_HTTP_HEADER_AUTHORIZATION; h2.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); h2.value = "Basic " TEST_AUTH_STR; h2.value_size = strlen (h2.value); h3.kind = MHD_HEADER_KIND; h3.header = MHD_HTTP_HEADER_AUTHORIZATION; h3.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); h3.value = "Digest cnonce=" TEST_AUTH_STR; h3.value_size = strlen (h3.value); conn.rq.headers_received = &h1; h1.next = &h2; h2.prev = &h1; h2.next = &h3; h3.prev = &h2; conn.rq.headers_received_tail = &h3; conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */ ret = 0; #ifdef BAUTH_SUPPORT bauth = get_BAuthRqParams (); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT dauth = get_DAuthRqParams (); #endif /* DAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if (NULL == bauth) { fprintf (stderr, "No Basic Authorization header detected. Line: %u\n", (unsigned int) __LINE__); ret++; } else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != bauth->token68.len) || (0 != memcmp (bauth->token68.str, TEST_AUTH_STR, bauth->token68.len))) { fprintf (stderr, "Basic Authorization token does not match. Line: %u\n", (unsigned int) __LINE__); ret++; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (NULL == dauth) { fprintf (stderr, "No Digest Authorization header detected. Line: %u\n", (unsigned int) __LINE__); ret++; } else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != dauth->cnonce.value.len) || (0 != memcmp (dauth->cnonce.value.str, TEST_AUTH_STR, dauth->cnonce.value.len))) { fprintf (stderr, "Digest Authorization 'cnonce' does not match. Line: %u\n", (unsigned int) __LINE__); ret++; } #endif /* DAUTH_SUPPORT */ /* Cleanup */ conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; conn.state = MHD_CONNECTION_INIT; return ret; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ test_global_init (); errcount += check_type (); #ifdef BAUTH_SUPPORT errcount += check_basic (); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT errcount += check_digest (); #endif /* DAUTH_SUPPORT */ errcount += check_two_auths (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/digestauth.c0000644000175000017500000042577215035214301016563 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digestauth.c * @brief Implements HTTP digest authentication * @author Amr Ali * @author Matthieu Speder * @author Christian Grothoff (RFC 7616 support) * @author Karlson2k (Evgeny Grin) (fixes, new API, improvements, large rewrite, * many RFC 7616 features implementation, * old RFC 2069 support) */ #include "digestauth.h" #include "gen_auth.h" #include "platform.h" #include "mhd_limits.h" #include "internal.h" #include "response.h" #ifdef MHD_MD5_SUPPORT # include "mhd_md5_wrap.h" #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT # include "mhd_sha256_wrap.h" #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT # include "sha512_256.h" #endif /* MHD_SHA512_256_SUPPORT */ #include "mhd_locks.h" #include "mhd_mono_clock.h" #include "mhd_str.h" #include "mhd_compat.h" #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Allow re-use of the nonce-nc map array slot after #REUSE_TIMEOUT seconds, * if this slot is needed for the new nonce, while the old nonce was not used * even one time by the client. * Typically clients immediately use generated nonce for new request. */ #define REUSE_TIMEOUT 30 /** * The maximum value of artificial timestamp difference to avoid clashes. * The value must be suitable for bitwise AND operation. */ #define DAUTH_JUMPBACK_MAX (0x7F) /** * 48 bit value in bytes */ #define TIMESTAMP_BIN_SIZE (48 / 8) /** * Trim value to the TIMESTAMP_BIN_SIZE size */ #define TRIM_TO_TIMESTAMP(value) \ ((value) & ((UINT64_C (1) << (TIMESTAMP_BIN_SIZE * 8)) - 1)) /** * The printed timestamp size in chars */ #define TIMESTAMP_CHARS_LEN (TIMESTAMP_BIN_SIZE * 2) /** * Standard server nonce length, not including terminating null, * * @param digest_size digest size */ #define NONCE_STD_LEN(digest_size) \ ((digest_size) * 2 + TIMESTAMP_CHARS_LEN) #ifdef MHD_SHA512_256_SUPPORT /** * Maximum size of any digest hash supported by MHD. * (SHA-512/256 > MD5). */ #define MAX_DIGEST SHA512_256_DIGEST_SIZE /** * The common size of SHA-256 digest and SHA-512/256 digest */ #define SHA256_SHA512_256_DIGEST_SIZE SHA512_256_DIGEST_SIZE #elif defined(MHD_SHA256_SUPPORT) /** * Maximum size of any digest hash supported by MHD. * (SHA-256 > MD5). */ #define MAX_DIGEST SHA256_DIGEST_SIZE /** * The common size of SHA-256 digest and SHA-512/256 digest */ #define SHA256_SHA512_256_DIGEST_SIZE SHA256_DIGEST_SIZE #elif defined(MHD_MD5_SUPPORT) /** * Maximum size of any digest hash supported by MHD. */ #define MAX_DIGEST MD5_DIGEST_SIZE #else /* ! MHD_MD5_SUPPORT */ #error At least one hashing algorithm must be enabled #endif /* ! MHD_MD5_SUPPORT */ /** * Macro to avoid using VLAs if the compiler does not support them. */ #ifndef HAVE_C_VARARRAYS /** * Return #MAX_DIGEST. * * @param n length of the digest to be used for a VLA */ #define VLA_ARRAY_LEN_DIGEST(n) (MAX_DIGEST) #else /** * Return @a n. * * @param n length of the digest to be used for a VLA */ #define VLA_ARRAY_LEN_DIGEST(n) (n) #endif /** * Check that @a n is below #MAX_DIGEST */ #define VLA_CHECK_LEN_DIGEST(n) \ do { if ((n) > MAX_DIGEST) MHD_PANIC (_ ("VLA too big.\n")); } while (0) /** * Maximum length of a username for digest authentication. */ #define MAX_USERNAME_LENGTH 128 /** * Maximum length of a realm for digest authentication. */ #define MAX_REALM_LENGTH 256 /** * Maximum length of the response in digest authentication. */ #define MAX_AUTH_RESPONSE_LENGTH (MAX_DIGEST * 2) /** * The required prefix of parameter with the extended notation */ #define MHD_DAUTH_EXT_PARAM_PREFIX "UTF-8'" /** * The minimal size of the prefix for parameter with the extended notation */ #define MHD_DAUTH_EXT_PARAM_MIN_LEN \ MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX "'") /** * The result of nonce-nc map array check. */ enum MHD_CheckNonceNC_ { /** * The nonce and NC are OK (valid and NC was not used before). */ MHD_CHECK_NONCENC_OK = MHD_DAUTH_OK, /** * The 'nonce' was overwritten with newer 'nonce' in the same slot or * NC was already used. * The validity of the 'nonce' was not be checked. */ MHD_CHECK_NONCENC_STALE = MHD_DAUTH_NONCE_STALE, /** * The 'nonce' is wrong, it was not generated before. */ MHD_CHECK_NONCENC_WRONG = MHD_DAUTH_NONCE_WRONG }; /** * Get base hash calculation algorithm from #MHD_DigestAuthAlgo3 value. * @param algo3 the MHD_DigestAuthAlgo3 value * @return the base hash calculation algorithm */ _MHD_static_inline enum MHD_DigestBaseAlgo get_base_digest_algo (enum MHD_DigestAuthAlgo3 algo3) { unsigned int base_algo; base_algo = ((unsigned int) algo3) & ~((unsigned int) (MHD_DIGEST_AUTH_ALGO3_NON_SESSION | MHD_DIGEST_AUTH_ALGO3_SESSION)); return (enum MHD_DigestBaseAlgo) base_algo; } /** * Get digest size for specified algorithm. * * Internal inline version. * @param algo3 the algorithm to check * @return the size of the digest or zero if the input value is not * supported/valid */ _MHD_static_inline size_t digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3) { #ifdef MHD_MD5_SUPPORT mhd_assert (MHD_MD5_DIGEST_SIZE == MD5_DIGEST_SIZE); #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT mhd_assert (MHD_SHA256_DIGEST_SIZE == SHA256_DIGEST_SIZE); #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT mhd_assert (MHD_SHA512_256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE); #ifdef MHD_SHA256_SUPPORT mhd_assert (SHA256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE); #endif /* MHD_SHA256_SUPPORT */ #endif /* MHD_SHA512_256_SUPPORT */ /* Only one algorithm must be specified */ mhd_assert (1 == \ (((0 != (algo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0) \ + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0) \ + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0))); #ifdef MHD_MD5_SUPPORT if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_MD5))) return MHD_MD5_DIGEST_SIZE; else #endif /* MHD_MD5_SUPPORT */ #if defined(MHD_SHA256_SUPPORT) && defined(MHD_SHA512_256_SUPPORT) if (0 != (((unsigned int) algo3) & ( ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256) | ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256)))) return MHD_SHA256_DIGEST_SIZE; /* The same as SHA512_256_DIGEST_SIZE */ else #elif defined(MHD_SHA256_SUPPORT) if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256))) return MHD_SHA256_DIGEST_SIZE; else #elif defined(MHD_SHA512_256_SUPPORT) if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256))) return MHD_SHA512_256_DIGEST_SIZE; else #endif /* MHD_SHA512_256_SUPPORT */ (void) 0; /* Unsupported algorithm */ return 0; /* Wrong input or unsupported algorithm */ } /** * Get digest size for specified algorithm. * * The size of the digest specifies the size of the userhash, userdigest * and other parameters which size depends on used hash algorithm. * @param algo3 the algorithm to check * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or * #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE) * or zero if the input value is not supported or not valid * @sa #MHD_digest_auth_calc_userdigest() * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN size_t MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3) { return digest_get_hash_size (algo3); } /** * Digest context data */ union DigestCtx { #ifdef MHD_MD5_SUPPORT struct Md5CtxWr md5_ctx; #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT struct Sha256CtxWr sha256_ctx; #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT struct Sha512_256Ctx sha512_256_ctx; #endif /* MHD_SHA512_256_SUPPORT */ }; /** * The digest calculation structure. */ struct DigestAlgorithm { /** * A context for the digest algorithm, already initialized to be * useful for @e init, @e update and @e digest. */ union DigestCtx ctx; /** * The hash calculation algorithm. */ enum MHD_DigestBaseAlgo algo; /** * Buffer for hex-print of the final digest. */ #ifdef _DEBUG bool uninitialised; /**< The structure has been not set-up */ bool algo_selected; /**< The algorithm has been selected */ bool ready_for_hashing; /**< The structure is ready to hash data */ bool hashing; /**< Some data has been hashed, but the digest has not finalised yet */ #endif /* _DEBUG */ }; /** * Return the size of the digest. * @param da the digest calculation structure to identify * @return the size of the digest. */ _MHD_static_inline unsigned int digest_get_size (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) return MD5_DIGEST_SIZE; #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) return SHA256_DIGEST_SIZE; #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) return SHA512_256_DIGEST_SIZE; #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* May not happen */ return 0; } #if defined(MHD_MD5_HAS_DEINIT) || defined(MHD_SHA256_HAS_DEINIT) /** * Indicates presence of digest_deinit() function */ #define MHD_DIGEST_HAS_DEINIT 1 #endif /* MHD_MD5_HAS_DEINIT || MHD_SHA256_HAS_DEINIT */ #ifdef MHD_DIGEST_HAS_DEINIT /** * Zero-initialise digest calculation structure. * * This initialisation is enough to safely call #digest_deinit() only. * To make any real digest calculation, #digest_setup_and_init() must be called. * @param da the digest calculation */ _MHD_static_inline void digest_setup_zero (struct DigestAlgorithm *da) { #ifdef _DEBUG da->uninitialised = false; da->algo_selected = false; da->ready_for_hashing = false; da->hashing = false; #endif /* _DEBUG */ da->algo = MHD_DIGEST_BASE_ALGO_INVALID; } /** * De-initialise digest calculation structure. * * This function must be called if #digest_setup_and_init() was called for * @a da. * This function must not be called if @a da was not initialised by * #digest_setup_and_init() or by #digest_setup_zero(). * @param da the digest calculation */ _MHD_static_inline void digest_deinit (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); #ifdef MHD_MD5_HAS_DEINIT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) MHD_MD5_deinit (&da->ctx.md5_ctx); else #endif /* MHD_MD5_HAS_DEINIT */ #ifdef MHD_SHA256_HAS_DEINIT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) MHD_SHA256_deinit (&da->ctx.sha256_ctx); else #endif /* MHD_SHA256_HAS_DEINIT */ (void) 0; digest_setup_zero (da); } #else /* ! MHD_DIGEST_HAS_DEINIT */ #define digest_setup_zero(da) (void)0 #define digest_deinit(da) (void)0 #endif /* ! MHD_DIGEST_HAS_DEINIT */ /** * Set-up the digest calculation structure and initialise with initial values. * * If @a da was successfully initialised, #digest_deinit() must be called * after finishing using of the @a da. * * This function must not be called more than once for any @a da. * * @param da the structure to set-up * @param algo the algorithm to use for digest calculation * @return boolean 'true' if successfully set-up, * false otherwise. */ _MHD_static_inline bool digest_init_one_time (struct DigestAlgorithm *da, enum MHD_DigestBaseAlgo algo) { #ifdef _DEBUG da->uninitialised = false; da->algo_selected = false; da->ready_for_hashing = false; da->hashing = false; #endif /* _DEBUG */ #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_MD5; #ifdef _DEBUG da->algo_selected = true; #endif MHD_MD5_init_one_time (&da->ctx.md5_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_SHA256; #ifdef _DEBUG da->algo_selected = true; #endif MHD_SHA256_init_one_time (&da->ctx.sha256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_SHA512_256; #ifdef _DEBUG da->algo_selected = true; #endif MHD_SHA512_256_init (&da->ctx.sha512_256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_SHA512_256_SUPPORT */ da->algo = MHD_DIGEST_BASE_ALGO_INVALID; return false; /* Unsupported or bad algorithm */ } /** * Feed digest calculation with more data. * @param da the digest calculation * @param data the data to process * @param length the size of the @a data in bytes */ _MHD_static_inline void digest_update (struct DigestAlgorithm *da, const void *data, size_t length) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (da->ready_for_hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) MHD_MD5_update (&da->ctx.md5_ctx, (const uint8_t *) data, length); else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) MHD_SHA256_update (&da->ctx.sha256_ctx, (const uint8_t *) data, length); else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) MHD_SHA512_256_update (&da->ctx.sha512_256_ctx, (const uint8_t *) data, length); else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* May not happen */ #ifdef _DEBUG da->hashing = true; #endif } /** * Feed digest calculation with more data from string. * @param da the digest calculation * @param str the zero-terminated string to process */ _MHD_static_inline void digest_update_str (struct DigestAlgorithm *da, const char *str) { const size_t str_len = strlen (str); digest_update (da, (const uint8_t *) str, str_len); } /** * Feed digest calculation with single colon ':' character. * @param da the digest calculation * @param str the zero-terminated string to process */ _MHD_static_inline void digest_update_with_colon (struct DigestAlgorithm *da) { static const uint8_t colon = (uint8_t) ':'; digest_update (da, &colon, 1); } /** * Finally calculate hash (the digest). * @param da the digest calculation * @param[out] digest the pointer to the buffer to put calculated digest, * must be at least digest_get_size(da) bytes large */ _MHD_static_inline void digest_calc_hash (struct DigestAlgorithm *da, uint8_t *digest) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (da->ready_for_hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) { #ifdef MHD_MD5_HAS_FINISH MHD_MD5_finish (&da->ctx.md5_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ #else /* ! MHD_MD5_HAS_FINISH */ MHD_MD5_finish_reset (&da->ctx.md5_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ #endif /* ! MHD_MD5_HAS_FINISH */ } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) { #ifdef MHD_SHA256_HAS_FINISH MHD_SHA256_finish (&da->ctx.sha256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ #else /* ! MHD_SHA256_HAS_FINISH */ MHD_SHA256_finish_reset (&da->ctx.sha256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ #endif /* ! MHD_SHA256_HAS_FINISH */ } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) { MHD_SHA512_256_finish (&da->ctx.sha512_256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ } else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* Should not happen */ #ifdef _DEBUG da->hashing = false; #endif /* _DEBUG */ } /** * Reset the digest calculation structure. * * @param da the structure to reset */ _MHD_static_inline void digest_reset (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (! da->hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) { #ifdef MHD_MD5_HAS_FINISH mhd_assert (! da->ready_for_hashing); #else /* ! MHD_MD5_HAS_FINISH */ mhd_assert (da->ready_for_hashing); #endif /* ! MHD_MD5_HAS_FINISH */ MHD_MD5_reset (&da->ctx.md5_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) { #ifdef MHD_SHA256_HAS_FINISH mhd_assert (! da->ready_for_hashing); #else /* ! MHD_SHA256_HAS_FINISH */ mhd_assert (da->ready_for_hashing); #endif /* ! MHD_SHA256_HAS_FINISH */ MHD_SHA256_reset (&da->ctx.sha256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) { mhd_assert (! da->ready_for_hashing); MHD_SHA512_256_init (&da->ctx.sha512_256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif } else #endif /* MHD_SHA512_256_SUPPORT */ { #ifdef _DEBUG da->ready_for_hashing = false; #endif mhd_assert (0); /* May not happen, bad algorithm */ } } #if defined(MHD_MD5_HAS_EXT_ERROR) || defined(MHD_SHA256_HAS_EXT_ERROR) /** * Indicates that digest algorithm has external error status */ #define MHD_DIGEST_HAS_EXT_ERROR 1 #endif /* MHD_MD5_HAS_EXT_ERROR || MHD_SHA256_HAS_EXT_ERROR */ #ifdef MHD_DIGEST_HAS_EXT_ERROR /** * Get external error code. * * When external digest calculation used, an error may occur during * initialisation or hashing data. This function checks whether external * error has been reported for digest calculation. * @param da the digest calculation * @return true if external error occurs */ _MHD_static_inline bool digest_ext_error (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); #ifdef MHD_MD5_HAS_EXT_ERROR if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) return 0 != da->ctx.md5_ctx.ext_error; #endif /* MHD_MD5_HAS_EXT_ERROR */ #ifdef MHD_SHA256_HAS_EXT_ERROR if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) return 0 != da->ctx.sha256_ctx.ext_error; #endif /* MHD_MD5_HAS_EXT_ERROR */ return false; } #else /* ! MHD_DIGEST_HAS_EXT_ERROR */ #define digest_ext_error(da) (false) #endif /* ! MHD_DIGEST_HAS_EXT_ERROR */ /** * Extract timestamp from the given nonce. * @param nonce the nonce to check * @param noncelen the length of the nonce, zero for autodetect * @param[out] ptimestamp the pointer to store extracted timestamp * @return true if timestamp was extracted, * false if nonce does not have valid timestamp. */ static bool get_nonce_timestamp (const char *const nonce, size_t noncelen, uint64_t *const ptimestamp) { if (0 == noncelen) noncelen = strlen (nonce); if (true #ifdef MHD_MD5_SUPPORT && (NONCE_STD_LEN (MD5_DIGEST_SIZE) != noncelen) #endif /* MHD_MD5_SUPPORT */ #if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT) && (NONCE_STD_LEN (SHA256_SHA512_256_DIGEST_SIZE) != noncelen) #endif /* MHD_SHA256_SUPPORT */ ) return false; if (TIMESTAMP_CHARS_LEN != MHD_strx_to_uint64_n_ (nonce + noncelen - TIMESTAMP_CHARS_LEN, TIMESTAMP_CHARS_LEN, ptimestamp)) return false; return true; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Super-fast xor-based "hash" function * * @param data the data to calculate hash for * @param data_size the size of the data in bytes * @return the "hash" */ static uint32_t fast_simple_hash (const uint8_t *data, size_t data_size) { uint32_t hash; if (0 != data_size) { size_t i; hash = data[0]; for (i = 1; i < data_size; i++) hash = _MHD_ROTL32 (hash, 7) ^ data[i]; } else hash = 0; return hash; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /** * Get index of the nonce in the nonce-nc map array. * * @param arr_size the size of nonce_nc array * @param nonce the pointer that referenced a zero-terminated array of nonce * @param noncelen the length of @a nonce, in characters * @return #MHD_YES if successful, #MHD_NO if invalid (or we have no NC array) */ static size_t get_nonce_nc_idx (size_t arr_size, const char *nonce, size_t noncelen) { mhd_assert (0 != arr_size); mhd_assert (0 != noncelen); return fast_simple_hash ((const uint8_t *) nonce, noncelen) % arr_size; } /** * Check nonce-nc map array with the new nonce counter. * * @param connection The MHD connection structure * @param nonce the pointer that referenced hex nonce, does not need to be * zero-terminated * @param noncelen the length of @a nonce, in characters * @param nc The nonce counter * @return #MHD_DAUTH_NONCENC_OK if successful, * #MHD_DAUTH_NONCENC_STALE if nonce is stale (or no nonce-nc array * is available), * #MHD_DAUTH_NONCENC_WRONG if nonce was not recodered in nonce-nc map * array, while it should. */ static enum MHD_CheckNonceNC_ check_nonce_nc (struct MHD_Connection *connection, const char *nonce, size_t noncelen, uint64_t nonce_time, uint64_t nc) { struct MHD_Daemon *daemon = MHD_get_master (connection->daemon); struct MHD_NonceNc *nn; uint32_t mod; enum MHD_CheckNonceNC_ ret; mhd_assert (0 != noncelen); mhd_assert (0 != nc); if (MAX_DIGEST_NONCE_LENGTH < noncelen) return MHD_CHECK_NONCENC_WRONG; /* This should be impossible, but static analysis tools have a hard time with it *and* this also protects against unsafe modifications that may happen in the future... */ mod = daemon->nonce_nc_size; if (0 == mod) return MHD_CHECK_NONCENC_STALE; /* no array! */ if (nc >= UINT32_MAX - 64) return MHD_CHECK_NONCENC_STALE; /* Overflow, unrealistically high value */ nn = &daemon->nnc[get_nonce_nc_idx (mod, nonce, noncelen)]; MHD_mutex_lock_chk_ (&daemon->nnc_lock); mhd_assert (0 == nn->nonce[noncelen]); /* The old value must be valid */ if ( (0 != memcmp (nn->nonce, nonce, noncelen)) || (0 != nn->nonce[noncelen]) ) { /* The nonce in the slot does not match nonce from the client */ if (0 == nn->nonce[0]) { /* The slot was never used, while the client's nonce value should be * recorded when it was generated by MHD */ ret = MHD_CHECK_NONCENC_WRONG; } else if (0 != nn->nonce[noncelen]) { /* The value is the slot is wrong */ ret = MHD_CHECK_NONCENC_STALE; } else { uint64_t slot_ts; /**< The timestamp in the slot */ if (! get_nonce_timestamp (nn->nonce, noncelen, &slot_ts)) { mhd_assert (0); /* The value is the slot is wrong */ ret = MHD_CHECK_NONCENC_STALE; } else { /* Unsigned value, will be large if nonce_time is less than slot_ts */ const uint64_t ts_diff = TRIM_TO_TIMESTAMP (nonce_time - slot_ts); if ((REUSE_TIMEOUT * 1000) >= ts_diff) { /* The nonce from the client may not have been placed in the slot * because another nonce in that slot has not yet expired. */ ret = MHD_CHECK_NONCENC_STALE; } else if (TRIM_TO_TIMESTAMP (UINT64_MAX) / 2 >= ts_diff) { /* Too large value means that nonce_time is less than slot_ts. * The nonce from the client may have been overwritten by the newer * nonce. */ ret = MHD_CHECK_NONCENC_STALE; } else { /* The nonce from the client should be generated after the nonce * in the slot has been expired, the nonce must be recorded, but * it's not. */ ret = MHD_CHECK_NONCENC_WRONG; } } } } else if (nc > nn->nc) { /* 'nc' is larger, shift bitmask and bump limit */ const uint32_t jump_size = (uint32_t) nc - nn->nc; if (64 > jump_size) { /* small jump, less than mask width */ nn->nmask <<= jump_size; /* Set bit for the old 'nc' value */ nn->nmask |= (UINT64_C (1) << (jump_size - 1)); } else if (64 == jump_size) nn->nmask = (UINT64_C (1) << 63); else nn->nmask = 0; /* big jump, unset all bits in the mask */ nn->nc = (uint32_t) nc; ret = MHD_CHECK_NONCENC_OK; } else if (nc < nn->nc) { /* Note that we use 64 here, as we do not store the bit for 'nn->nc' itself in 'nn->nmask' */ if ( (nc + 64 >= nn->nc) && (0 == ((UINT64_C (1) << (nn->nc - nc - 1)) & nn->nmask)) ) { /* Out-of-order nonce, but within 64-bit bitmask, set bit */ nn->nmask |= (UINT64_C (1) << (nn->nc - nc - 1)); ret = MHD_CHECK_NONCENC_OK; } else /* 'nc' was already used or too old (more then 64 values ago) */ ret = MHD_CHECK_NONCENC_STALE; } else /* if (nc == nn->nc) */ /* 'nc' was already used */ ret = MHD_CHECK_NONCENC_STALE; MHD_mutex_unlock_chk_ (&daemon->nnc_lock); return ret; } /** * Get username type used by the client. * This function does not check whether userhash can be decoded or * extended notation (if used) is valid. * @param params the Digest Authorization parameters * @return the type of username */ _MHD_static_inline enum MHD_DigestAuthUsernameType get_rq_uname_type (const struct MHD_RqDAuth *params) { if (NULL != params->username.value.str) { if (NULL == params->username_ext.value.str) return params->userhash ? MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH : MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD; else /* Both 'username' and 'username*' are used */ return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } else if (NULL != params->username_ext.value.str) { if (! params->username_ext.quoted && ! params->userhash && (MHD_DAUTH_EXT_PARAM_MIN_LEN <= params->username_ext.value.len) ) return MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED; else return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } return MHD_DIGEST_AUTH_UNAME_TYPE_MISSING; } /** * Get total size required for 'username' and 'userhash_bin' * @param params the Digest Authorization parameters * @param uname_type the type of username * @return the total size required for 'username' and * 'userhash_bin' is userhash is used */ _MHD_static_inline size_t get_rq_unames_size (const struct MHD_RqDAuth *params, enum MHD_DigestAuthUsernameType uname_type) { size_t s; mhd_assert (get_rq_uname_type (params) == uname_type); s = 0; if ((MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type) || (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) ) { s += params->username.value.len + 1; /* Add one byte for zero-termination */ if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) s += (params->username.value.len + 1) / 2; } else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type) s += params->username_ext.value.len - MHD_DAUTH_EXT_PARAM_MIN_LEN + 1; /* Add one byte for zero-termination */ return s; } /** * Get unquoted version of Digest Authorization parameter. * This function automatically zero-teminate the result. * @param param the parameter to extract * @param[out] buf the output buffer, must be enough size to hold the result, * the recommended size is 'param->value.len + 1' * @return the size of the result, not including the terminating zero */ static size_t get_rq_param_unquoted_copy_z (const struct MHD_RqDAuthParam *param, char *buf) { size_t len; mhd_assert (NULL != param->value.str); if (! param->quoted) { memcpy (buf, param->value.str, param->value.len); buf [param->value.len] = 0; return param->value.len; } len = MHD_str_unquote (param->value.str, param->value.len, buf); mhd_assert (0 != len); mhd_assert (len < param->value.len); buf[len] = 0; return len; } /** * Get decoded version of username from extended notation. * This function automatically zero-teminate the result. * @param uname_ext the string of client's 'username*' parameter value * @param uname_ext_len the length of @a uname_ext in chars * @param[out] buf the output buffer to put decoded username value * @param buf_size the size of @a buf * @return the number of characters copied to the output buffer or * -1 if wrong extended notation is used. */ static ssize_t get_rq_extended_uname_copy_z (const char *uname_ext, size_t uname_ext_len, char *buf, size_t buf_size) { size_t r; size_t w; if ((size_t) SSIZE_MAX < uname_ext_len) return -1; /* Too long input string */ if (MHD_DAUTH_EXT_PARAM_MIN_LEN > uname_ext_len) return -1; /* Required prefix is missing */ if (! MHD_str_equal_caseless_bin_n_ (uname_ext, MHD_DAUTH_EXT_PARAM_PREFIX, MHD_STATICSTR_LEN_ ( \ MHD_DAUTH_EXT_PARAM_PREFIX))) return -1; /* Only UTF-8 is supported, as it is implied by RFC 7616 */ r = MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX); /* Skip language tag */ while (r < uname_ext_len && '\'' != uname_ext[r]) { const char chr = uname_ext[r]; if ((' ' == chr) || ('\t' == chr) || ('\"' == chr) || (',' == chr) || (';' == chr) ) return -1; /* Wrong char in language tag */ r++; } if (r >= uname_ext_len) return -1; /* The end of the language tag was not found */ r++; /* Advance to the next char */ w = MHD_str_pct_decode_strict_n_ (uname_ext + r, uname_ext_len - r, buf, buf_size); if ((0 == w) && (0 != uname_ext_len - r)) return -1; /* Broken percent encoding */ buf[w] = 0; /* Zero terminate the result */ mhd_assert (SSIZE_MAX > w); return (ssize_t) w; } /** * Get copy of username used by the client. * @param params the Digest Authorization parameters * @param uname_type the type of username * @param[out] uname_info the pointer to the structure to be filled * @param buf the buffer to be used for usernames * @param buf_size the size of the @a buf * @return the size of the @a buf used by pointers in @a unames structure */ static size_t get_rq_uname (const struct MHD_RqDAuth *params, enum MHD_DigestAuthUsernameType uname_type, struct MHD_DigestAuthUsernameInfo *uname_info, uint8_t *buf, size_t buf_size) { size_t buf_used; buf_used = 0; mhd_assert (get_rq_uname_type (params) == uname_type); mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type); mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type); uname_info->username = NULL; uname_info->username_len = 0; uname_info->userhash_hex = NULL; uname_info->userhash_hex_len = 0; uname_info->userhash_bin = NULL; if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type) { uname_info->username = (char *) (buf + buf_used); uname_info->username_len = get_rq_param_unquoted_copy_z (¶ms->username, uname_info->username); buf_used += uname_info->username_len + 1; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD; } else if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) { size_t res; uname_info->userhash_hex = (char *) (buf + buf_used); uname_info->userhash_hex_len = get_rq_param_unquoted_copy_z (¶ms->username, uname_info->userhash_hex); buf_used += uname_info->userhash_hex_len + 1; uname_info->userhash_bin = (uint8_t *) (buf + buf_used); res = MHD_hex_to_bin (uname_info->userhash_hex, uname_info->userhash_hex_len, uname_info->userhash_bin); if (res != uname_info->userhash_hex_len / 2) { uname_info->userhash_bin = NULL; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } else { /* Avoid pointers outside allocated region when the size is zero */ if (0 == res) uname_info->userhash_bin = (uint8_t *) uname_info->username; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH; buf_used += res; } } else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type) { ssize_t res; res = get_rq_extended_uname_copy_z (params->username_ext.value.str, params->username_ext.value.len, (char *) (buf + buf_used), buf_size - buf_used); if (0 > res) uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; else { uname_info->username = (char *) (buf + buf_used); uname_info->username_len = (size_t) res; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED; buf_used += uname_info->username_len + 1; } } else { mhd_assert (0); uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } mhd_assert (buf_size >= buf_used); return buf_used; } /** * Result of request's Digest Authorization 'nc' value extraction */ enum MHD_GetRqNCResult { MHD_GET_RQ_NC_NONE = -1, /**< No 'nc' value */ MHD_GET_RQ_NC_VALID = 0, /**< Readable 'nc' value */ MHD_GET_RQ_NC_TOO_LONG = 1, /**< The 'nc' value is too long */ MHD_GET_RQ_NC_TOO_LARGE = 2,/**< The 'nc' value is too big to fit uint32_t */ MHD_GET_RQ_NC_BROKEN = 3 /**< The 'nc' value is not a number */ }; /** * Get 'nc' value from request's Authorization header * @param params the request digest authentication * @param[out] nc the pointer to put nc value to * @return enum value indicating the result */ static enum MHD_GetRqNCResult get_rq_nc (const struct MHD_RqDAuth *params, uint32_t *nc) { const struct MHD_RqDAuthParam *const nc_param = ¶ms->nc; char unq[16]; const char *val; size_t val_len; size_t res; uint64_t nc_val; if (NULL == nc_param->value.str) return MHD_GET_RQ_NC_NONE; if (0 == nc_param->value.len) return MHD_GET_RQ_NC_BROKEN; if (! nc_param->quoted) { val = nc_param->value.str; val_len = nc_param->value.len; } else { /* Actually no backslashes must be used in 'nc' */ if (sizeof(unq) < params->nc.value.len) return MHD_GET_RQ_NC_TOO_LONG; val_len = MHD_str_unquote (nc_param->value.str, nc_param->value.len, unq); if (0 == val_len) return MHD_GET_RQ_NC_BROKEN; val = unq; } res = MHD_strx_to_uint64_n_ (val, val_len, &nc_val); if (0 == res) { const char f = val[0]; if ( (('9' >= f) && ('0' <= f)) || (('F' >= f) && ('A' <= f)) || (('a' <= f) && ('f' >= f)) ) return MHD_GET_RQ_NC_TOO_LARGE; else return MHD_GET_RQ_NC_BROKEN; } if (val_len != res) return MHD_GET_RQ_NC_BROKEN; if (UINT32_MAX < nc_val) return MHD_GET_RQ_NC_TOO_LARGE; *nc = (uint32_t) nc_val; return MHD_GET_RQ_NC_VALID; } /** * Get information about Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL no valid Digest Authorization header is used in the request; * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthInfo * MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; struct MHD_DigestAuthInfo *info; enum MHD_DigestAuthUsernameType uname_type; size_t unif_buf_size; uint8_t *unif_buf_ptr; size_t unif_buf_used; enum MHD_GetRqNCResult nc_res; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; unif_buf_size = 0; uname_type = get_rq_uname_type (params); unif_buf_size += get_rq_unames_size (params, uname_type); if (NULL != params->opaque.value.str) unif_buf_size += params->opaque.value.len + 1; /* Add one for zero-termination */ if (NULL != params->realm.value.str) unif_buf_size += params->realm.value.len + 1; /* Add one for zero-termination */ info = (struct MHD_DigestAuthInfo *) MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthInfo)) + unif_buf_size); unif_buf_ptr = (uint8_t *) (info + 1); unif_buf_used = 0; info->algo3 = params->algo3; if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type) && (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type) ) unif_buf_used += get_rq_uname (params, uname_type, (struct MHD_DigestAuthUsernameInfo *) info, unif_buf_ptr + unif_buf_used, unif_buf_size - unif_buf_used); else info->uname_type = uname_type; if (NULL != params->opaque.value.str) { info->opaque = (char *) (unif_buf_ptr + unif_buf_used); info->opaque_len = get_rq_param_unquoted_copy_z (¶ms->opaque, info->opaque); unif_buf_used += info->opaque_len + 1; } if (NULL != params->realm.value.str) { info->realm = (char *) (unif_buf_ptr + unif_buf_used); info->realm_len = get_rq_param_unquoted_copy_z (¶ms->realm, info->realm); unif_buf_used += info->realm_len + 1; } mhd_assert (unif_buf_size >= unif_buf_used); info->qop = params->qop; if (NULL != params->cnonce.value.str) info->cnonce_len = params->cnonce.value.len; else info->cnonce_len = 0; nc_res = get_rq_nc (params, &info->nc); if (MHD_GET_RQ_NC_VALID != nc_res) info->nc = MHD_DIGEST_AUTH_INVALID_NC_VALUE; return info; } /** * Get the username from Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request, * or no username parameter is present in the header, or username is * provided incorrectly by client (see description for * #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID); * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @sa MHD_digest_auth_get_request_info3() provides more complete information * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthUsernameInfo * MHD_digest_auth_get_username3 (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; struct MHD_DigestAuthUsernameInfo *uname_info; enum MHD_DigestAuthUsernameType uname_type; size_t unif_buf_size; uint8_t *unif_buf_ptr; size_t unif_buf_used; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; uname_type = get_rq_uname_type (params); if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING == uname_type) || (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_type) ) return NULL; unif_buf_size = get_rq_unames_size (params, uname_type); uname_info = (struct MHD_DigestAuthUsernameInfo *) MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthUsernameInfo)) + unif_buf_size); unif_buf_ptr = (uint8_t *) (uname_info + 1); unif_buf_used = get_rq_uname (params, uname_type, uname_info, unif_buf_ptr, unif_buf_size); mhd_assert (unif_buf_size >= unif_buf_used); (void) unif_buf_used; /* Mute compiler warning on non-debug builds */ mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_info->uname_type); if (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_info->uname_type) { free (uname_info); return NULL; } mhd_assert (uname_type == uname_info->uname_type); uname_info->algo3 = params->algo3; return uname_info; } /** * Get the username from the authorization header sent by the client * * This function supports username in standard and extended notations. * "userhash" is not supported by this function. * * @param connection The MHD connection structure * @return NULL if no username could be found, username provided as * "userhash", extended notation broken or memory allocation error * occurs; * a pointer to the username if found, free using #MHD_free(). * @warning Returned value must be freed by #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @ingroup authentication */ _MHD_EXTERN char * MHD_digest_auth_get_username (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; char *username; size_t buf_size; enum MHD_DigestAuthUsernameType uname_type; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; uname_type = get_rq_uname_type (params); if ( (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname_type) && (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != uname_type) ) return NULL; buf_size = get_rq_unames_size (params, uname_type); mhd_assert (0 != buf_size); username = (char *) MHD_calloc_ (1, buf_size); if (NULL == username) return NULL; if (1) { struct MHD_DigestAuthUsernameInfo uname_strct; size_t used; memset (&uname_strct, 0, sizeof(uname_strct)); used = get_rq_uname (params, uname_type, &uname_strct, (uint8_t *) username, buf_size); if (uname_type != uname_strct.uname_type) { /* Broken encoding for extended notation */ free (username); return NULL; } (void) used; /* Mute compiler warning for non-debug builds */ mhd_assert (buf_size >= used); } return username; } /** * Calculate the server nonce so that it mitigates replay attacks * The current format of the nonce is ... * H(timestamp:random data:various parameters) + Hex(timestamp) * * @param nonce_time The amount of time in seconds for a nonce to be invalid * @param mthd_e HTTP method as enum value * @param method HTTP method as a string * @param rnd the pointer to a character array for the random seed * @param rnd_size The size of the random seed array @a rnd * @param saddr the pointer to the socket address structure * @param saddr_size the size of the socket address structure @a saddr * @param uri the HTTP URI (in MHD, without the arguments ("?k=v") * @param uri_len the length of the @a uri * @param first_header the pointer to the first request's header * @param realm A string of characters that describes the realm of auth. * @param realm_len the length of the @a realm. * @param bind_options the nonce bind options (#MHD_DAuthBindNonce values). * @param da digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated */ static void calculate_nonce (uint64_t nonce_time, enum MHD_HTTP_Method mthd_e, const char *method, const char *rnd, size_t rnd_size, const struct sockaddr_storage *saddr, size_t saddr_size, const char *uri, size_t uri_len, const struct MHD_HTTP_Req_Header *first_header, const char *realm, size_t realm_len, unsigned int bind_options, struct DigestAlgorithm *da, char *nonce) { mhd_assert (! da->hashing); if (1) { /* Add the timestamp to the hash calculation */ uint8_t timestamp[TIMESTAMP_BIN_SIZE]; /* If the nonce_time is milliseconds, then the same 48 bit value will repeat * every 8 919 years, which is more than enough to mitigate a replay attack */ #if TIMESTAMP_BIN_SIZE != 6 #error The code needs to be updated here #endif timestamp[0] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 0))); timestamp[1] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 1))); timestamp[2] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 2))); timestamp[3] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 3))); timestamp[4] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 4))); timestamp[5] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 5))); MHD_bin_to_hex (timestamp, sizeof (timestamp), nonce + digest_get_size (da) * 2); digest_update (da, timestamp, sizeof (timestamp)); } if (rnd_size > 0) { /* Add the unique random value to the hash calculation */ digest_update_with_colon (da); digest_update (da, rnd, rnd_size); } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) && (0 != saddr_size) ) { /* Add full client address including source port to make unique nonces * for requests received exactly at the same time */ digest_update_with_colon (da); digest_update (da, saddr, saddr_size); } if ( (0 != (bind_options & MHD_DAUTH_BIND_NONCE_CLIENT_IP)) && (0 != saddr_size) ) { /* Add the client's IP address to the hash calculation */ digest_update_with_colon (da); if (AF_INET == saddr->ss_family) digest_update (da, &((const struct sockaddr_in *) saddr)->sin_addr, sizeof(((const struct sockaddr_in *) saddr)->sin_addr)); #ifdef HAVE_INET6 else if (AF_INET6 == saddr->ss_family) digest_update (da, &((const struct sockaddr_in6 *) saddr)->sin6_addr, sizeof(((const struct sockaddr_in6 *) saddr)->sin6_addr)); #endif /* HAVE_INET6 */ } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) || (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI))) { /* Add the request method to the hash calculation */ digest_update_with_colon (da); if (MHD_HTTP_MTHD_OTHER != mthd_e) { uint8_t mthd_for_hash; if (MHD_HTTP_MTHD_HEAD != mthd_e) mthd_for_hash = (uint8_t) mthd_e; else /* Treat HEAD method in the same way as GET method */ mthd_for_hash = (uint8_t) MHD_HTTP_MTHD_GET; digest_update (da, &mthd_for_hash, sizeof(mthd_for_hash)); } else digest_update_str (da, method); } if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI)) { /* Add the request URI to the hash calculation */ digest_update_with_colon (da); digest_update (da, uri, uri_len); } if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI_PARAMS)) { /* Add the request URI parameters to the hash calculation */ const struct MHD_HTTP_Req_Header *h; digest_update_with_colon (da); for (h = first_header; NULL != h; h = h->next) { if (MHD_GET_ARGUMENT_KIND != h->kind) continue; digest_update (da, "\0", 2); if (0 != h->header_size) digest_update (da, h->header, h->header_size); digest_update (da, "", 1); if (0 != h->value_size) digest_update (da, h->value, h->value_size); } } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) || (0 != (bind_options & MHD_DAUTH_BIND_NONCE_REALM))) { /* Add the realm to the hash calculation */ digest_update_with_colon (da); digest_update (da, realm, realm_len); } if (1) { uint8_t hash[MAX_DIGEST]; digest_calc_hash (da, hash); MHD_bin_to_hex (hash, digest_get_size (da), nonce); } } /** * Check whether it is possible to use slot in nonce-nc map array. * * Should be called with mutex held to avoid external modification of * the slot data. * * @param nn the pointer to the nonce-nc slot * @param now the current time * @param new_nonce the new nonce supposed to be stored in this slot, * zero-terminated * @param new_nonce_len the length of the @a new_nonce in chars, not including * the terminating zero. * @return true if the slot can be used to store the new nonce, * false otherwise. */ static bool is_slot_available (const struct MHD_NonceNc *const nn, const uint64_t now, const char *const new_nonce, size_t new_nonce_len) { uint64_t timestamp; bool timestamp_valid; mhd_assert (new_nonce_len <= NONCE_STD_LEN (MAX_DIGEST)); mhd_assert (NONCE_STD_LEN (MAX_DIGEST) <= MAX_DIGEST_NONCE_LENGTH); if (0 == nn->nonce[0]) return true; /* The slot is empty */ if (0 == memcmp (nn->nonce, new_nonce, new_nonce_len)) { /* The slot has the same nonce already. This nonce cannot be registered * again as it would just clear 'nc' usage history. */ return false; } if (0 != nn->nc) return true; /* Client already used the nonce in this slot at least one time, re-use the slot */ /* The nonce must be zero-terminated */ mhd_assert (0 == nn->nonce[sizeof(nn->nonce) - 1]); if (0 != nn->nonce[sizeof(nn->nonce) - 1]) return true; /* Wrong nonce format in the slot */ timestamp_valid = get_nonce_timestamp (nn->nonce, 0, ×tamp); mhd_assert (timestamp_valid); if (! timestamp_valid) return true; /* Invalid timestamp in nonce-nc, should not be possible */ if ((REUSE_TIMEOUT * 1000) < TRIM_TO_TIMESTAMP (now - timestamp)) return true; return false; } /** * Calculate the server nonce so that it mitigates replay attacks and add * the new nonce to the nonce-nc map array. * * @param connection the MHD connection structure * @param timestamp the current timestamp * @param realm the string of characters that describes the realm of auth * @param realm_len the length of the @a realm * @param da the digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated * @return true if the new nonce has been added to the nonce-nc map array, * false otherwise. */ static bool calculate_add_nonce (struct MHD_Connection *const connection, uint64_t timestamp, const char *realm, size_t realm_len, struct DigestAlgorithm *da, char *nonce) { struct MHD_Daemon *const daemon = MHD_get_master (connection->daemon); struct MHD_NonceNc *nn; const size_t nonce_size = NONCE_STD_LEN (digest_get_size (da)); bool ret; mhd_assert (! da->hashing); mhd_assert (MAX_DIGEST_NONCE_LENGTH >= nonce_size); mhd_assert (0 != nonce_size); calculate_nonce (timestamp, connection->rq.http_mthd, connection->rq.method, daemon->digest_auth_random, daemon->digest_auth_rand_size, connection->addr, (size_t) connection->addr_len, connection->rq.url, connection->rq.url_len, connection->rq.headers_received, realm, realm_len, daemon->dauth_bind_type, da, nonce); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return false; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 == daemon->nonce_nc_size) return false; /* Sanity check for values */ mhd_assert (MAX_DIGEST_NONCE_LENGTH == NONCE_STD_LEN (MAX_DIGEST)); nn = daemon->nnc + get_nonce_nc_idx (daemon->nonce_nc_size, nonce, nonce_size); MHD_mutex_lock_chk_ (&daemon->nnc_lock); if (is_slot_available (nn, timestamp, nonce, nonce_size)) { memcpy (nn->nonce, nonce, nonce_size); nn->nonce[nonce_size] = 0; /* With terminating zero */ nn->nc = 0; nn->nmask = 0; ret = true; } else ret = false; MHD_mutex_unlock_chk_ (&daemon->nnc_lock); return ret; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Calculate the server nonce so that it mitigates replay attacks and add * the new nonce to the nonce-nc map array. * * @param connection the MHD connection structure * @param realm A string of characters that describes the realm of auth. * @param da digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated */ static bool calculate_add_nonce_with_retry (struct MHD_Connection *const connection, const char *realm, struct DigestAlgorithm *da, char *nonce) { const uint64_t timestamp1 = MHD_monotonic_msec_counter (); const size_t realm_len = strlen (realm); mhd_assert (! da->hashing); #ifdef HAVE_MESSAGES if (0 == MHD_get_master (connection->daemon)->digest_auth_rand_size) MHD_DLOG (connection->daemon, _ ("Random value was not initialised by " \ "MHD_OPTION_DIGEST_AUTH_RANDOM or " \ "MHD_OPTION_DIGEST_AUTH_RANDOM_COPY, generated nonces " \ "are predictable.\n")); #endif if (! calculate_add_nonce (connection, timestamp1, realm, realm_len, da, nonce)) { /* Either: * 1. The same nonce was already generated. If it will be used then one * of the clients will fail (as no initial 'nc' value could be given to * the client, the second client which will use 'nc=00000001' will fail). * 2. Another nonce uses the same slot, and this nonce never has been * used by the client and this nonce is still fresh enough. */ const size_t digest_size = digest_get_size (da); char nonce2[NONCE_STD_LEN (MAX_DIGEST) + 1]; uint64_t timestamp2; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return false; /* No need to re-try */ #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 == MHD_get_master (connection->daemon)->nonce_nc_size) return false; /* No need to re-try */ timestamp2 = MHD_monotonic_msec_counter (); if (timestamp1 == timestamp2) { /* The timestamps are equal, need to generate some arbitrary * difference for nonce. */ /* As the number is needed only to differentiate clients, weak * pseudo-random generators could be used. Seeding is not needed. */ uint64_t base1; uint32_t base2; uint16_t base3; uint8_t base4; #ifdef HAVE_RANDOM base1 = ((uint64_t) random ()) ^ UINT64_C (0x54a5acff5be47e63); base4 = 0xb8; #elif defined(HAVE_RAND) base1 = ((uint64_t) rand ()) ^ UINT64_C (0xc4bcf553b12f3965); base4 = 0x92; #else /* Monotonic msec counter alone does not really help here as it is already known that this value is not unique. */ base1 = ((uint64_t) (uintptr_t) nonce2) ^ UINT64_C (0xf2e1b21bc6c92655); base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1); base2 = _MHD_ROTR32 (base2, 4); base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2); base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3); base1 = ((uint64_t) MHD_monotonic_msec_counter ()) ^ UINT64_C (0xccab93f72cf5b15); #endif base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1); base2 = _MHD_ROTL32 (base2, (((base4 >> 4) ^ base4) % 32)); base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2); base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3); /* Use up to 127 ms difference */ timestamp2 -= (base4 & DAUTH_JUMPBACK_MAX); if (timestamp1 == timestamp2) timestamp2 -= 2; /* Fallback value */ } digest_reset (da); if (! calculate_add_nonce (connection, timestamp2, realm, realm_len, da, nonce2)) { /* No free slot has been found. Re-tries are expensive, just use * the generated nonce. As it is not stored in nonce-nc map array, * the next request of the client will be recognized as valid, but 'stale' * so client should re-try automatically. */ return false; } memcpy (nonce, nonce2, NONCE_STD_LEN (digest_size)); } return true; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /** * Calculate userdigest, return it as binary data. * * It is equal to H(A1) for non-session algorithms. * * MHD internal version. * * @param da the digest algorithm * @param username the username to use * @param username_len the length of the @a username * @param realm the realm to use * @param realm_len the length of the @a realm * @param password the password, must be zero-terminated * @param[out] ha1_bin the output buffer, must have at least * #digest_get_size(da) bytes available */ _MHD_static_inline void calc_userdigest (struct DigestAlgorithm *da, const char *username, const size_t username_len, const char *realm, const size_t realm_len, const char *password, uint8_t *ha1_bin) { mhd_assert (! da->hashing); digest_update (da, username, username_len); digest_update_with_colon (da); digest_update (da, realm, realm_len); digest_update_with_colon (da); digest_update_str (da, password); digest_calc_hash (da, ha1_bin); } /** * Calculate userdigest, return it as a binary data. * * The "userdigest" is the hash of the "username:realm:password" string. * * The "userdigest" can be used to avoid storing the password in clear text * in database/files * * This function is designed to improve security of stored credentials, * the "userdigest" does not improve security of the authentication process. * * The results can be used to store username & userdigest pairs instead of * username & password pairs. To further improve security, application may * store username & userhash & userdigest triplets. * * @param algo3 the digest algorithm * @param username the username * @param realm the realm * @param password the password * @param[out] userdigest_bin the output buffer for userdigest; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of * userdigest upon return * @param bin_buf_size the size of the @a userdigest_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, const char *password, void *userdigest_bin, size_t bin_buf_size) { struct DigestAlgorithm da; enum MHD_Result ret; if (! digest_init_one_time (&da, get_base_digest_algo (algo3))) return MHD_NO; if (digest_get_size (&da) > bin_buf_size) ret = MHD_NO; else { calc_userdigest (&da, username, strlen (username), realm, strlen (realm), password, userdigest_bin); ret = MHD_YES; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (&da)) ret = MHD_NO; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ } digest_deinit (&da); return ret; } /** * Calculate userhash, return it as binary data. * * MHD internal version. * * @param da the digest algorithm * @param username the username to use * @param username_len the length of the @a username * @param realm the realm to use * @param realm_len the length of the @a realm * @param[out] digest_bin the output buffer, must have at least * #MHD_digest_get_hash_size(algo3) bytes available */ _MHD_static_inline void calc_userhash (struct DigestAlgorithm *da, const char *username, const size_t username_len, const char *realm, const size_t realm_len, uint8_t *digest_bin) { mhd_assert (NULL != username); mhd_assert (! da->hashing); digest_update (da, username, username_len); digest_update_with_colon (da); digest_update (da, realm, realm_len); digest_calc_hash (da, digest_bin); } /** * Calculate "userhash", return it as binary data. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_bin the output buffer for userhash as binary data; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of userhash * upon return * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH) * @sa #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, void *userhash_bin, size_t bin_buf_size) { struct DigestAlgorithm da; enum MHD_Result ret; if (! digest_init_one_time (&da, get_base_digest_algo (algo3))) return MHD_NO; if (digest_get_size (&da) > bin_buf_size) ret = MHD_NO; else { calc_userhash (&da, username, strlen (username), realm, strlen (realm), userhash_bin); ret = MHD_YES; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (&da)) ret = MHD_NO; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ } digest_deinit (&da); return ret; } /** * Calculate "userhash", return it as hexadecimal string. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_hex the output buffer for userhash as hex string; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3)*2 chars long * userhash zero-terminated string * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3)*2+1 chars long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_calc_userhash() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, char *userhash_hex, size_t hex_buf_size) { uint8_t userhash_bin[MAX_DIGEST]; size_t digest_size; digest_size = digest_get_hash_size (algo3); if (digest_size * 2 + 1 > hex_buf_size) return MHD_NO; if (MHD_NO == MHD_digest_auth_calc_userhash (algo3, username, realm, userhash_bin, MAX_DIGEST)) return MHD_NO; MHD_bin_to_hex_z (userhash_bin, digest_size, userhash_hex); return MHD_YES; } struct test_header_param { struct MHD_Connection *connection; size_t num_headers; }; /** * Test if the given key-value pair is in the headers for the * given connection. * * @param cls the test context * @param key the key * @param key_size number of bytes in @a key * @param value the value, can be NULL * @param value_size number of bytes in @a value * @param kind type of the header * @return #MHD_YES if the key-value pair is in the headers, * #MHD_NO if not */ static enum MHD_Result test_header (void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind) { struct test_header_param *const param = (struct test_header_param *) cls; struct MHD_Connection *connection = param->connection; struct MHD_HTTP_Req_Header *pos; size_t i; param->num_headers++; i = 0; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (kind != pos->kind) continue; if (++i == param->num_headers) { if (key_size != pos->header_size) return MHD_NO; if (value_size != pos->value_size) return MHD_NO; if (0 != key_size) { mhd_assert (NULL != key); mhd_assert (NULL != pos->header); if (0 != memcmp (key, pos->header, key_size)) return MHD_NO; } if (0 != value_size) { mhd_assert (NULL != value); mhd_assert (NULL != pos->value); if (0 != memcmp (value, pos->value, value_size)) return MHD_NO; } return MHD_YES; } } return MHD_NO; } /** * Check that the arguments given by the client as part * of the authentication header match the arguments we * got as part of the HTTP request URI. * * @param connection connections with headers to compare against * @param args the copy of argument URI string (after "?" in URI), will be * modified by this function * @return boolean true if the arguments match, * boolean false if not */ static bool check_argument_match (struct MHD_Connection *connection, char *args) { struct MHD_HTTP_Req_Header *pos; enum MHD_Result ret; struct test_header_param param; param.connection = connection; param.num_headers = 0; ret = MHD_parse_arguments_ (connection, MHD_GET_ARGUMENT_KIND, args, &test_header, ¶m); if (MHD_NO == ret) { return false; } /* also check that the number of headers matches */ for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (MHD_GET_ARGUMENT_KIND != pos->kind) continue; param.num_headers--; } if (0 != param.num_headers) { /* argument count mismatch */ return false; } return true; } /** * Check that the URI provided by the client as part * of the authentication header match the real HTTP request URI. * * @param connection connections with headers to compare against * @param uri the copy of URI in the authentication header, should point to * modifiable buffer at least @a uri_len + 1 characters long, * will be modified by this function, not valid upon return * @param uri_len the length of the @a uri string in characters * @return boolean true if the URIs match, * boolean false if not */ static bool check_uri_match (struct MHD_Connection *connection, char *uri, size_t uri_len) { char *qmark; char *args; struct MHD_Daemon *const daemon = connection->daemon; uri[uri_len] = 0; qmark = memchr (uri, '?', uri_len); if (NULL != qmark) *qmark = '\0'; /* Need to unescape URI before comparing with connection->url */ uri_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, uri); if ((uri_len != connection->rq.url_len) || (0 != memcmp (uri, connection->rq.url, uri_len))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, URI does not match.\n")); #endif return false; } args = (NULL != qmark) ? (qmark + 1) : uri + uri_len; if (! check_argument_match (connection, args) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, arguments do not match.\n")); #endif return false; } return true; } /** * The size of the unquoting buffer in stack */ #define _MHD_STATIC_UNQ_BUFFER_SIZE 128 /** * Get the pointer to buffer with required size * @param tmp1 the first buffer with fixed size * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param required_size the required size in buffer * @return the pointer to the buffer or NULL if failed to allocate buffer with * requested size */ static char * get_buffer_for_size (char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, size_t required_size) { mhd_assert ((0 == *ptmp2_size) || (NULL != *ptmp2)); mhd_assert ((NULL != *ptmp2) || (0 == *ptmp2_size)); mhd_assert ((0 == *ptmp2_size) || \ (_MHD_STATIC_UNQ_BUFFER_SIZE < *ptmp2_size)); if (required_size <= _MHD_STATIC_UNQ_BUFFER_SIZE) return tmp1; if (required_size <= *ptmp2_size) return *ptmp2; if (required_size > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) return NULL; if (NULL != *ptmp2) free (*ptmp2); *ptmp2 = (char *) malloc (required_size); if (NULL == *ptmp2) *ptmp2_size = 0; else *ptmp2_size = required_size; return *ptmp2; } /** * The result of parameter unquoting */ enum _MHD_GetUnqResult { _MHD_UNQ_OK = 0, /**< Got unquoted string */ _MHD_UNQ_TOO_LARGE = -7, /**< The string is too large to unquote */ _MHD_UNQ_OUT_OF_MEM = 3 /**< Out of memory error */ }; /** * Get Digest authorisation parameter as unquoted string. * @param param the parameter to process * @param tmp1 the small buffer in stack * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param[out] unquoted the pointer to store the result, NOT zero terminated * @return enum code indicating result of the process */ static enum _MHD_GetUnqResult get_unquoted_param (const struct MHD_RqDAuthParam *param, char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, struct _MHD_str_w_len *unquoted) { char *str; size_t len; mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (! param->quoted) { unquoted->str = param->value.str; unquoted->len = param->value.len; return _MHD_UNQ_OK; } /* The value is present and is quoted, needs to be copied and unquoted */ str = get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len); if (NULL == str) return (param->value.len > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ? _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM; len = MHD_str_unquote (param->value.str, param->value.len, str); unquoted->str = str; unquoted->len = len; mhd_assert (0 != unquoted->len); mhd_assert (unquoted->len < param->value.len); return _MHD_UNQ_OK; } /** * Get copy of Digest authorisation parameter as unquoted string. * @param param the parameter to process * @param tmp1 the small buffer in stack * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param[out] unquoted the pointer to store the result, NOT zero terminated, * but with enough space to zero-terminate * @return enum code indicating result of the process */ static enum _MHD_GetUnqResult get_unquoted_param_copy (const struct MHD_RqDAuthParam *param, char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, struct _MHD_mstr_w_len *unquoted) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); /* The value is present and is quoted, needs to be copied and unquoted */ /* Allocate buffer with one more additional byte for zero-termination */ unquoted->str = get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len + 1); if (NULL == unquoted->str) return (param->value.len + 1 > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ? _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM; if (! param->quoted) { memcpy (unquoted->str, param->value.str, param->value.len); unquoted->len = param->value.len; return _MHD_UNQ_OK; } unquoted->len = MHD_str_unquote (param->value.str, param->value.len, unquoted->str); mhd_assert (0 != unquoted->len); mhd_assert (unquoted->len < param->value.len); return _MHD_UNQ_OK; } /** * Check whether Digest Auth request parameter is equal to given string * @param param the parameter to check * @param str the string to compare with, does not need to be zero-terminated * @param str_len the length of the @a str * @return true is parameter is equal to the given string, * false otherwise */ _MHD_static_inline bool is_param_equal (const struct MHD_RqDAuthParam *param, const char *const str, const size_t str_len) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (param->quoted) return MHD_str_equal_quoted_bin_n (param->value.str, param->value.len, str, str_len); return (str_len == param->value.len) && (0 == memcmp (str, param->value.str, str_len)); } /** * Check whether Digest Auth request parameter is caseless equal to given string * @param param the parameter to check * @param str the string to compare with, does not need to be zero-terminated * @param str_len the length of the @a str * @return true is parameter is caseless equal to the given string, * false otherwise */ _MHD_static_inline bool is_param_equal_caseless (const struct MHD_RqDAuthParam *param, const char *const str, const size_t str_len) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (param->quoted) return MHD_str_equal_quoted_bin_n (param->value.str, param->value.len, str, str_len); return (str_len == param->value.len) && (0 == memcmp (str, param->value.str, str_len)); } /** * Authenticates the authorization header sent by the client * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request new nonce must be * generated and client repeat all requests twice (the first time to get a new * nonce and the second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password used in the authentication, * must be NULL if @a userdigest is not NULL * @param userdigest the precalculated binary hash of the string * "username:realm:password", * must be NULL if @a password is not NULL * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * unlike #digest_auth_check_all() zero is used literally * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * unlike #digest_auth_check_all() zero is treated as "no limit" * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm specified * by the client is not allowed by this parameter * @param[out] pbuf the pointer to pointer to internally malloc'ed buffer, * to be freed if not NULL upon return * @return #MHD_DAUTH_OK if authenticated, * error code otherwise. * @ingroup authentication */ static enum MHD_DigestAuthResult digest_auth_check_all_inner (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, const uint8_t *userdigest, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, char **pbuf, struct DigestAlgorithm *da) { struct MHD_Daemon *daemon = MHD_get_master (connection->daemon); enum MHD_DigestAuthAlgo3 c_algo; /**< Client's algorithm */ enum MHD_DigestAuthQOP c_qop; /**< Client's QOP */ unsigned int digest_size; uint8_t hash1_bin[MAX_DIGEST]; uint8_t hash2_bin[MAX_DIGEST]; #if 0 const char *hentity = NULL; /* "auth-int" is not supported */ #endif uint64_t nonce_time; uint64_t nci; const struct MHD_RqDAuth *params; /** * Temporal buffer in stack for unquoting and other needs */ char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE]; char **const ptmp2 = pbuf; /**< Temporal malloc'ed buffer for unquoting */ size_t tmp2_size; /**< The size of @a tmp2 buffer */ struct _MHD_str_w_len unquoted; struct _MHD_mstr_w_len unq_copy; enum _MHD_GetUnqResult unq_res; size_t username_len; size_t realm_len; mhd_assert ((NULL != password) || (NULL != userdigest)); mhd_assert (! ((NULL != userdigest) && (NULL != password))); tmp2_size = 0; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return MHD_DAUTH_WRONG_HEADER; /* ** Initial parameters checks and setup ** */ /* Get client's algorithm */ c_algo = params->algo3; /* Check whether client's algorithm is allowed by function parameter */ if (((unsigned int) c_algo) != (((unsigned int) c_algo) & ((unsigned int) malgo3))) return MHD_DAUTH_WRONG_ALGO; /* Check whether client's algorithm is supported */ if (0 != (((unsigned int) c_algo) & MHD_DIGEST_AUTH_ALGO3_SESSION)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'session' algorithms are not supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #ifndef MHD_MD5_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The MD5 algorithm is not supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_MD5_SUPPORT */ #ifndef MHD_SHA256_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA256_SUPPORT */ #ifndef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA512_256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-512/256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA512_256_SUPPORT */ if (! digest_init_one_time (da, get_base_digest_algo (c_algo))) MHD_PANIC (_ ("Wrong 'malgo3' value, API violation")); /* Check 'mqop' value */ c_qop = params->qop; /* Check whether client's QOP is allowed by function parameter */ if (((unsigned int) c_qop) != (((unsigned int) c_qop) & ((unsigned int) mqop))) return MHD_DAUTH_WRONG_QOP; if (0 != (((unsigned int) c_qop) & MHD_DIGEST_AUTH_QOP_AUTH_INT)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'auth-int' QOP is not supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_QOP; } #ifdef HAVE_MESSAGES if ((MHD_DIGEST_AUTH_QOP_NONE == c_qop) && (0 == (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5))) MHD_DLOG (connection->daemon, _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \ "non-standard extension.\n")); #endif /* HAVE_MESSAGES */ digest_size = digest_get_size (da); /* ** A quick check for presence of all required parameters ** */ if ((NULL == params->username.value.str) && (NULL == params->username_ext.value.str)) return MHD_DAUTH_WRONG_USERNAME; else if ((NULL != params->username.value.str) && (NULL != params->username_ext.value.str)) return MHD_DAUTH_WRONG_USERNAME; /* Parameters cannot be used together */ else if ((NULL != params->username_ext.value.str) && (MHD_DAUTH_EXT_PARAM_MIN_LEN > params->username_ext.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Broken extended notation */ else if (params->userhash && (NULL == params->username.value.str)) return MHD_DAUTH_WRONG_USERNAME; /* Userhash cannot be used with extended notation */ else if (params->userhash && (digest_size * 2 > params->username.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Too few chars for correct userhash */ else if (params->userhash && (digest_size * 4 < params->username.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Too many chars for correct userhash */ if (NULL == params->realm.value.str) return MHD_DAUTH_WRONG_REALM; else if (((NULL == userdigest) || params->userhash) && (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->realm.value.len)) return MHD_DAUTH_TOO_LARGE; /* Realm is too large and should be used in hash calculations */ if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { if (NULL == params->nc.value.str) return MHD_DAUTH_WRONG_HEADER; else if (0 == params->nc.value.len) return MHD_DAUTH_WRONG_HEADER; else if (4 * 8 < params->nc.value.len) /* Four times more than needed */ return MHD_DAUTH_WRONG_HEADER; if (NULL == params->cnonce.value.str) return MHD_DAUTH_WRONG_HEADER; else if (0 == params->cnonce.value.len) return MHD_DAUTH_WRONG_HEADER; else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->cnonce.value.len) return MHD_DAUTH_TOO_LARGE; } /* The QOP parameter was checked already */ if (NULL == params->uri.value.str) return MHD_DAUTH_WRONG_URI; else if (0 == params->uri.value.len) return MHD_DAUTH_WRONG_URI; else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->uri.value.len) return MHD_DAUTH_TOO_LARGE; if (NULL == params->nonce.value.str) return MHD_DAUTH_NONCE_WRONG; else if (0 == params->nonce.value.len) return MHD_DAUTH_NONCE_WRONG; else if (NONCE_STD_LEN (digest_size) * 2 < params->nonce.value.len) return MHD_DAUTH_NONCE_WRONG; if (NULL == params->response.value.str) return MHD_DAUTH_RESPONSE_WRONG; else if (0 == params->response.value.len) return MHD_DAUTH_RESPONSE_WRONG; else if (digest_size * 4 < params->response.value.len) return MHD_DAUTH_RESPONSE_WRONG; /* ** Check simple parameters match ** */ /* Check 'algorithm' */ /* The 'algorithm' was checked at the start of the function */ /* 'algorithm' valid */ /* Check 'qop' */ /* The 'qop' was checked at the start of the function */ /* 'qop' valid */ /* Check 'realm' */ realm_len = strlen (realm); if (! is_param_equal (¶ms->realm, realm, realm_len)) return MHD_DAUTH_WRONG_REALM; /* 'realm' valid */ /* Check 'username' */ username_len = strlen (username); if (! params->userhash) { if (NULL != params->username.value.str) { /* Username in standard notation */ if (! is_param_equal (¶ms->username, username, username_len)) return MHD_DAUTH_WRONG_USERNAME; } else { /* Username in extended notation */ char *r_uname; size_t buf_size = params->username_ext.value.len; ssize_t res; mhd_assert (NULL != params->username_ext.value.str); mhd_assert (MHD_DAUTH_EXT_PARAM_MIN_LEN <= buf_size); /* It was checked already */ buf_size += 1; /* For zero-termination */ buf_size -= MHD_DAUTH_EXT_PARAM_MIN_LEN; r_uname = get_buffer_for_size (tmp1, ptmp2, &tmp2_size, buf_size); if (NULL == r_uname) return (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < buf_size) ? MHD_DAUTH_TOO_LARGE : MHD_DAUTH_ERROR; res = get_rq_extended_uname_copy_z (params->username_ext.value.str, params->username_ext.value.len, r_uname, buf_size); if (0 > res) return MHD_DAUTH_WRONG_HEADER; /* Broken extended notation */ if ((username_len != (size_t) res) || (0 != memcmp (username, r_uname, username_len))) return MHD_DAUTH_WRONG_USERNAME; } } else { /* Userhash */ mhd_assert (NULL != params->username.value.str); calc_userhash (da, username, username_len, realm, realm_len, hash1_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ mhd_assert (sizeof (tmp1) >= (2 * digest_size)); MHD_bin_to_hex (hash1_bin, digest_size, tmp1); if (! is_param_equal_caseless (¶ms->username, tmp1, 2 * digest_size)) return MHD_DAUTH_WRONG_USERNAME; /* To simplify the logic, the digest is reset here instead of resetting before the next hash calculation. */ digest_reset (da); } /* 'username' valid */ /* ** Do basic nonce and nonce-counter checks (size, timestamp) ** */ /* Get 'nc' digital value */ if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { unq_res = get_unquoted_param (¶ms->nc, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if (unquoted.len != MHD_strx_to_uint64_n_ (unquoted.str, unquoted.len, &nci)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid nc format.\n")); #endif return MHD_DAUTH_WRONG_HEADER; /* invalid nonce format */ } if (0 == nci) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid 'nc' value.\n")); #endif return MHD_DAUTH_WRONG_HEADER; /* invalid nc value */ } if ((0 != max_nc) && (max_nc < nci)) return MHD_DAUTH_NONCE_STALE; /* Too large 'nc' value */ } else nci = 1; /* Force 'nc' value */ /* Got 'nc' digital value */ /* Get 'nonce' with basic checks */ unq_res = get_unquoted_param (¶ms->nonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if ((NONCE_STD_LEN (digest_size) != unquoted.len) || (! get_nonce_timestamp (unquoted.str, unquoted.len, &nonce_time))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid nonce format.\n")); #endif return MHD_DAUTH_NONCE_WRONG; } if (1) { uint64_t t; t = MHD_monotonic_msec_counter (); /* * First level vetting for the nonce validity: if the timestamp * attached to the nonce exceeds `nonce_timeout', then the nonce is * stale. */ if (TRIM_TO_TIMESTAMP (t - nonce_time) > (nonce_timeout * 1000)) return MHD_DAUTH_NONCE_STALE; /* too old */ } if (1) { enum MHD_CheckNonceNC_ nonce_nc_check; /* * Checking if that combination of nonce and nc is sound * and not a replay attack attempt. Refuse if nonce was not * generated previously. */ nonce_nc_check = check_nonce_nc (connection, unquoted.str, NONCE_STD_LEN (digest_size), nonce_time, nci); if (MHD_CHECK_NONCENC_STALE == nonce_nc_check) { #ifdef HAVE_MESSAGES if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) MHD_DLOG (daemon, _ ("Stale nonce received. If this happens a lot, you should " "probably increase the size of the nonce array.\n")); else MHD_DLOG (daemon, _ ("Stale nonce received. This is expected when client " \ "uses RFC2069-compatible mode and makes more than one " \ "request.\n")); #endif return MHD_DAUTH_NONCE_STALE; } else if (MHD_CHECK_NONCENC_WRONG == nonce_nc_check) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Received nonce that was not " "generated by MHD. This may indicate an attack attempt.\n")); #endif return MHD_DAUTH_NONCE_WRONG; } mhd_assert (MHD_CHECK_NONCENC_OK == nonce_nc_check); } /* The nonce was generated by MHD, is not stale and nonce-nc combination was not used before */ /* ** Build H(A2) and check URI match in the header and in the request ** */ /* Get 'uri' */ mhd_assert (! da->hashing); digest_update_str (da, connection->rq.method); digest_update_with_colon (da); #if 0 /* TODO: add support for "auth-int" */ digest_update_str (da, hentity); digest_update_with_colon (da); #endif unq_res = get_unquoted_param_copy (¶ms->uri, tmp1, ptmp2, &tmp2_size, &unq_copy); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, unq_copy.str, unq_copy.len); /* The next check will modify copied URI string */ if (! check_uri_match (connection, unq_copy.str, unq_copy.len)) return MHD_DAUTH_WRONG_URI; digest_calc_hash (da, hash2_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR /* Skip digest calculation external error check, the next one checks both */ #endif /* MHD_DIGEST_HAS_EXT_ERROR */ /* Got H(A2) */ /* ** Build H(A1) ** */ if (NULL == userdigest) { mhd_assert (! da->hashing); digest_reset (da); calc_userdigest (da, username, username_len, realm, realm_len, password, hash1_bin); } /* TODO: support '-sess' versions */ #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ /* Got H(A1) */ /* ** Check 'response' ** */ mhd_assert (! da->hashing); digest_reset (da); /* Update digest with H(A1) */ mhd_assert (sizeof (tmp1) >= (digest_size * 2)); if (NULL == userdigest) MHD_bin_to_hex (hash1_bin, digest_size, tmp1); else MHD_bin_to_hex (userdigest, digest_size, tmp1); digest_update (da, (const uint8_t *) tmp1, digest_size * 2); /* H(A1) is not needed anymore, reuse the buffer. * Use hash1_bin for the client's 'response' decoded to binary form. */ unq_res = get_unquoted_param (¶ms->response, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if (digest_size != MHD_hex_to_bin (unquoted.str, unquoted.len, hash1_bin)) return MHD_DAUTH_RESPONSE_WRONG; /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'nonce' text value */ unq_res = get_unquoted_param (¶ms->nonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { /* Update digest with 'nc' text value */ unq_res = get_unquoted_param (¶ms->nc, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'cnonce' value */ unq_res = get_unquoted_param (¶ms->cnonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'qop' value */ unq_res = get_unquoted_param (¶ms->qop_raw, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); } /* Update digest with H(A2) */ MHD_bin_to_hex (hash2_bin, digest_size, tmp1); digest_update (da, (const uint8_t *) tmp1, digest_size * 2); /* H(A2) is not needed anymore, reuse the buffer. * Use hash2_bin for the calculated response in binary form */ digest_calc_hash (da, hash2_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 != memcmp (hash1_bin, hash2_bin, digest_size)) return MHD_DAUTH_RESPONSE_WRONG; if (MHD_DAUTH_BIND_NONCE_NONE != daemon->dauth_bind_type) { mhd_assert (sizeof(tmp1) >= (NONCE_STD_LEN (digest_size) + 1)); /* It was already checked that 'nonce' (including timestamp) was generated by MHD. */ mhd_assert (! da->hashing); digest_reset (da); calculate_nonce (nonce_time, connection->rq.http_mthd, connection->rq.method, daemon->digest_auth_random, daemon->digest_auth_rand_size, connection->addr, (size_t) connection->addr_len, connection->rq.url, connection->rq.url_len, connection->rq.headers_received, realm, realm_len, daemon->dauth_bind_type, da, tmp1); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (! is_param_equal (¶ms->nonce, tmp1, NONCE_STD_LEN (digest_size))) return MHD_DAUTH_NONCE_OTHER_COND; /* The 'nonce' was generated in the same conditions */ } return MHD_DAUTH_OK; } /** * Authenticates the authorization header sent by the client * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request new nonce must be * generated and client repeat all requests twice (the first time to get a new * nonce and the second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password used in the authentication, * must be NULL if @a userdigest is not NULL * @param userdigest the precalculated binary hash of the string * "username:realm:password", * must be NULL if @a password is not NULL * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if set to zero then daemon's default value is used * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if set to zero then daemon's default value is used * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm specified * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * error code otherwise. * @ingroup authentication */ static enum MHD_DigestAuthResult digest_auth_check_all (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, const uint8_t *userdigest, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { enum MHD_DigestAuthResult res; char *buf; struct DigestAlgorithm da; buf = NULL; digest_setup_zero (&da); if (0 == nonce_timeout) nonce_timeout = connection->daemon->dauth_def_nonce_timeout; if (0 == max_nc) max_nc = connection->daemon->dauth_def_max_nc; res = digest_auth_check_all_inner (connection, realm, username, password, userdigest, nonce_timeout, max_nc, mqop, malgo3, &buf, &da); digest_deinit (&da); if (NULL != buf) free (buf); return res; } /** * Authenticates the authorization header sent by the client. * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility). * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future. * If you want to be sure you get MD5, use #MHD_digest_auth_check2() * and specify MD5 explicitly. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout) { return MHD_digest_auth_check2 (connection, realm, username, password, nonce_timeout, MHD_DIGEST_ALG_MD5); } /** * Authenticates the authorization header sent by the client. * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password matching the @a username (and the @a realm) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { mhd_assert (NULL != password); return digest_auth_check_all (connection, realm, username, password, NULL, nonce_timeout, max_nc, mqop, malgo3); } /** * Authenticates the authorization header sent by the client by using * hash of "username:realm:password". * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param userdigest the precalculated binary hash of the string * "username:realm:password", * see #MHD_digest_auth_calc_userdigest() * @param userdigest_size the size of the @a userdigest in bytes, must match the * hashing algorithm (see #MHD_MD5_DIGEST_SIZE, * #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE, * #MHD_digest_get_hash_size()) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter; * more than one base algorithms (MD5, SHA-256, SHA-512/256) * cannot be used at the same time for this function * as @a userdigest must match specified algorithm * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @sa #MHD_digest_auth_calc_userdigest() * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const void *userdigest, size_t userdigest_size, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { if (1 != (((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0) + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0) + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0))) MHD_PANIC (_ ("Wrong 'malgo3' value, only one base hashing algorithm " \ "(MD5, SHA-256 or SHA-512/256) must be specified, " \ "API violation")); #ifndef MHD_MD5_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The MD5 algorithm is not supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_MD5_SUPPORT */ #ifndef MHD_SHA256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA256_SUPPORT */ #ifndef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-512/256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA512_256_SUPPORT */ if (digest_get_hash_size ((enum MHD_DigestAuthAlgo3) malgo3) != userdigest_size) MHD_PANIC (_ ("Wrong 'userdigest_size' value, does not match 'malgo3', " "API violation")); return digest_auth_check_all (connection, realm, username, NULL, (const uint8_t *) userdigest, nonce_timeout, max_nc, mqop, malgo3); } /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthResult res; enum MHD_DigestAuthMultiAlgo3 malgo3; if (MHD_DIGEST_ALG_AUTO == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; else if (MHD_DIGEST_ALG_MD5 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else MHD_PANIC (_ ("Wrong 'algo' value, API violation")); res = MHD_digest_auth_check3 (connection, realm, username, password, nonce_timeout, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, malgo3); if (MHD_DAUTH_OK == res) return MHD_YES; else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) || (MHD_DAUTH_NONCE_OTHER_COND == res) ) return MHD_INVALID_NONCE; return MHD_NO; } /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary MD5 sum * for the precalculated hash value "username:realm:password" * of @a digest_size bytes * @param digest_size number of bytes in @a digest (size must match @a algo!) * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, size_t digest_size, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthResult res; enum MHD_DigestAuthMultiAlgo3 malgo3; if (MHD_DIGEST_ALG_AUTO == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; else if (MHD_DIGEST_ALG_MD5 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else MHD_PANIC (_ ("Wrong 'algo' value, API violation")); res = MHD_digest_auth_check_digest3 (connection, realm, username, digest, digest_size, nonce_timeout, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, malgo3); if (MHD_DAUTH_OK == res) return MHD_YES; else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) || (MHD_DAUTH_NONCE_OTHER_COND == res) ) return MHD_INVALID_NONCE; return MHD_NO; } /** * Authenticates the authorization header sent by the client * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed * size). * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary hash * for the precalculated hash value "username:realm:password"; * length must be #MHD_MD5_DIGEST_SIZE bytes * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096000 * @deprecated use #MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout) { return MHD_digest_auth_check_digest2 (connection, realm, username, digest, MHD_MD5_DIGEST_SIZE, nonce_timeout, MHD_DIGEST_ALG_MD5); } /** * Internal version of #MHD_queue_auth_required_response3() to simplify * cleanups. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host) * @param response the reply to send; should contain the "access denied" * body; note that this function sets the "WWW Authenticate" * header and that the caller should not do this; * the NULL is tolerated * @param signal_stale set to #MHD_YES if the nonce is stale to add 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use, MHD selects; if several algorithms * are allowed then MD5 is preferred (currently, may be changed * in next versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, the client may provide * hash("username:realm") instead of username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding * is preferred * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding * is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ static enum MHD_Result queue_auth_required_response3_inner (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, int userhash_support, int prefer_utf8, char **buf_ptr, struct DigestAlgorithm *da) { static const char prefix_realm[] = "realm=\""; static const char prefix_qop[] = "qop=\""; static const char prefix_algo[] = "algorithm="; static const char prefix_nonce[] = "nonce=\""; static const char prefix_opaque[] = "opaque=\""; static const char prefix_domain[] = "domain=\""; static const char str_charset[] = "charset=UTF-8"; static const char str_userhash[] = "userhash=true"; static const char str_stale[] = "stale=true"; enum MHD_DigestAuthAlgo3 s_algo; /**< Selected algorithm */ size_t realm_len; size_t opaque_len; size_t domain_len; size_t buf_size; char *buf; size_t p; /* The position in the buffer */ char *hdr_name; if ((0 == (((unsigned int) malgo3) & MHD_DIGEST_AUTH_ALGO3_NON_SESSION)) || (0 != (((unsigned int) malgo3) & MHD_DIGEST_AUTH_ALGO3_SESSION))) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Only non-'session' algorithms are supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } malgo3 = (enum MHD_DigestAuthMultiAlgo3) (malgo3 & (~((enum MHD_DigestAuthMultiAlgo3) MHD_DIGEST_AUTH_ALGO3_NON_SESSION))); #ifdef MHD_MD5_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5)) s_algo = MHD_DIGEST_AUTH_ALGO3_MD5; else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256)) s_algo = MHD_DIGEST_AUTH_ALGO3_SHA256; else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256)) s_algo = MHD_DIGEST_AUTH_ALGO3_SHA512_256; else #endif /* MHD_SHA512_256_SUPPORT */ { if (0 == (((unsigned int) malgo3) & (MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_BASE_ALGO_SHA512_256))) MHD_PANIC (_ ("Wrong 'malgo3' value, API violation")); else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("No requested algorithm is supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ } return MHD_NO; } if (MHD_DIGEST_AUTH_MULT_QOP_AUTH_INT == mqop) MHD_PANIC (_ ("Wrong 'mqop' value, API violation")); mqop = (enum MHD_DigestAuthMultiQOP) (mqop & (~((enum MHD_DigestAuthMultiQOP) MHD_DIGEST_AUTH_QOP_AUTH_INT))); if (! digest_init_one_time (da, get_base_digest_algo (s_algo))) MHD_PANIC (_ ("Wrong 'algo' value, API violation")); if (MHD_DIGEST_AUTH_MULT_QOP_NONE == mqop) { #ifdef HAVE_MESSAGES if ((0 != userhash_support) || (0 != prefer_utf8)) MHD_DLOG (connection->daemon, _ ("The 'userhash' and 'charset' ('prefer_utf8') parameters " \ "are not compatible with RFC2069 and ignored.\n")); if (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5)) MHD_DLOG (connection->daemon, _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \ "non-standard extension.\n")); #endif userhash_support = 0; prefer_utf8 = 0; } if (0 == MHD_get_master (connection->daemon)->nonce_nc_size) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The nonce array size is zero.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } /* Calculate required size */ buf_size = 0; /* 'Digest ' */ buf_size += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE) + 1; /* 1 for ' ' */ buf_size += MHD_STATICSTR_LEN_ (prefix_realm) + 3; /* 3 for '", ' */ /* 'realm="xxxx", ' */ realm_len = strlen (realm); if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < realm_len) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'realm' is too large.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } if ((NULL != memchr (realm, '\r', realm_len)) || (NULL != memchr (realm, '\n', realm_len))) return MHD_NO; buf_size += realm_len * 2; /* Quoting may double the size */ /* 'qop="xxxx", ' */ if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop) { buf_size += MHD_STATICSTR_LEN_ (prefix_qop) + 3; /* 3 for '", ' */ buf_size += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_); } /* 'algorithm="xxxx", ' */ if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) || (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5))) { buf_size += MHD_STATICSTR_LEN_ (prefix_algo) + 2; /* 2 for ', ' */ #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN); else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN); else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN); else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); } /* 'nonce="xxxx", ' */ buf_size += MHD_STATICSTR_LEN_ (prefix_nonce) + 3; /* 3 for '", ' */ buf_size += NONCE_STD_LEN (digest_get_size (da)); /* Escaping not needed */ /* 'opaque="xxxx", ' */ if (NULL != opaque) { buf_size += MHD_STATICSTR_LEN_ (prefix_opaque) + 3; /* 3 for '", ' */ opaque_len = strlen (opaque); if ((NULL != memchr (opaque, '\r', opaque_len)) || (NULL != memchr (opaque, '\n', opaque_len))) return MHD_NO; buf_size += opaque_len * 2; /* Quoting may double the size */ } else opaque_len = 0; /* 'domain="xxxx", ' */ if (NULL != domain) { buf_size += MHD_STATICSTR_LEN_ (prefix_domain) + 3; /* 3 for '", ' */ domain_len = strlen (domain); if ((NULL != memchr (domain, '\r', domain_len)) || (NULL != memchr (domain, '\n', domain_len))) return MHD_NO; buf_size += domain_len * 2; /* Quoting may double the size */ } else domain_len = 0; /* 'charset=UTF-8' */ if (MHD_NO != prefer_utf8) buf_size += MHD_STATICSTR_LEN_ (str_charset) + 2; /* 2 for ', ' */ /* 'userhash=true' */ if (MHD_NO != userhash_support) buf_size += MHD_STATICSTR_LEN_ (str_userhash) + 2; /* 2 for ', ' */ /* 'stale=true' */ if (MHD_NO != signal_stale) buf_size += MHD_STATICSTR_LEN_ (str_stale) + 2; /* 2 for ', ' */ /* The calculated length is for string ended with ", ". One character will * be used for zero-termination, the last one will not be used. */ /* Allocate the buffer */ buf = malloc (buf_size); if (NULL == buf) return MHD_NO; *buf_ptr = buf; /* Build the challenge string */ p = 0; /* 'Digest: ' */ memcpy (buf + p, _MHD_AUTH_DIGEST_BASE, MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE)); p += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE); buf[p++] = ' '; /* 'realm="xxxx", ' */ memcpy (buf + p, prefix_realm, MHD_STATICSTR_LEN_ (prefix_realm)); p += MHD_STATICSTR_LEN_ (prefix_realm); mhd_assert ((buf_size - p) >= (realm_len * 2)); if (1) { size_t quoted_size; quoted_size = MHD_str_quote (realm, realm_len, buf + p, buf_size - p); if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < quoted_size) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'realm' is too large after 'quoting'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } p += quoted_size; } buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; /* 'qop="xxxx", ' */ if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop) { memcpy (buf + p, prefix_qop, MHD_STATICSTR_LEN_ (prefix_qop)); p += MHD_STATICSTR_LEN_ (prefix_qop); memcpy (buf + p, MHD_TOKEN_AUTH_, MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_)); p += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'algorithm="xxxx", ' */ if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) || (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5))) { memcpy (buf + p, prefix_algo, MHD_STATICSTR_LEN_ (prefix_algo)); p += MHD_STATICSTR_LEN_ (prefix_algo); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo) { memcpy (buf + p, _MHD_MD5_TOKEN, MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN); } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo) { memcpy (buf + p, _MHD_SHA256_TOKEN, MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN); } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo) { memcpy (buf + p, _MHD_SHA512_256_TOKEN, MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN); } else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); buf[p++] = ','; buf[p++] = ' '; } /* 'nonce="xxxx", ' */ memcpy (buf + p, prefix_nonce, MHD_STATICSTR_LEN_ (prefix_nonce)); p += MHD_STATICSTR_LEN_ (prefix_nonce); mhd_assert ((buf_size - p) >= (NONCE_STD_LEN (digest_get_size (da)))); if (! calculate_add_nonce_with_retry (connection, realm, da, buf + p)) { #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("TLS library reported hash calculation error, nonce could " "not be generated.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* MHD_DIGEST_HAS_EXT_ERROR */ #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Could not register nonce. Client's requests with this " "nonce will be always 'stale'. Probably clients' requests " "are too intensive.\n")); #endif /* HAVE_MESSAGES */ (void) 0; /* Mute compiler warning for builds without messages */ } p += NONCE_STD_LEN (digest_get_size (da)); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; /* 'opaque="xxxx", ' */ if (NULL != opaque) { memcpy (buf + p, prefix_opaque, MHD_STATICSTR_LEN_ (prefix_opaque)); p += MHD_STATICSTR_LEN_ (prefix_opaque); mhd_assert ((buf_size - p) >= (opaque_len * 2)); p += MHD_str_quote (opaque, opaque_len, buf + p, buf_size - p); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'domain="xxxx", ' */ if (NULL != domain) { memcpy (buf + p, prefix_domain, MHD_STATICSTR_LEN_ (prefix_domain)); p += MHD_STATICSTR_LEN_ (prefix_domain); mhd_assert ((buf_size - p) >= (domain_len * 2)); p += MHD_str_quote (domain, domain_len, buf + p, buf_size - p); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'charset=UTF-8' */ if (MHD_NO != prefer_utf8) { memcpy (buf + p, str_charset, MHD_STATICSTR_LEN_ (str_charset)); p += MHD_STATICSTR_LEN_ (str_charset); buf[p++] = ','; buf[p++] = ' '; } /* 'userhash=true' */ if (MHD_NO != userhash_support) { memcpy (buf + p, str_userhash, MHD_STATICSTR_LEN_ (str_userhash)); p += MHD_STATICSTR_LEN_ (str_userhash); buf[p++] = ','; buf[p++] = ' '; } /* 'stale=true' */ if (MHD_NO != signal_stale) { memcpy (buf + p, str_stale, MHD_STATICSTR_LEN_ (str_stale)); p += MHD_STATICSTR_LEN_ (str_stale); buf[p++] = ','; buf[p++] = ' '; } mhd_assert (buf_size >= p); /* The built string ends with ", ". Replace comma with zero-termination. */ --p; buf[--p] = 0; hdr_name = malloc (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1); if (NULL != hdr_name) { memcpy (hdr_name, MHD_HTTP_HEADER_WWW_AUTHENTICATE, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1); if (MHD_add_response_entry_no_alloc_ (response, MHD_HEADER_KIND, hdr_name, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_WWW_AUTHENTICATE), buf, p)) { *buf_ptr = NULL; /* The buffer will be free()ed when the response is destroyed */ return MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response); } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Failed to add Digest auth header.\n")); } #endif /* HAVE_MESSAGES */ free (hdr_name); } return MHD_NO; } /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed (by #MHD_destroy_response()) after call of * this function. * * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was * not set, because such response should be backward-compatible with RFC 2069. * * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no * 'charset'). For better compatibility with clients, it is recommended (but * not required) to set @a domain to NULL in this mode. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host); * this list provides information for the client only and does * not actually restrict anything on the server side * @param response the reply to send; should contain the "access denied" * body; * note: this function sets the "WWW Authenticate" header and * the caller should not set this header; * the NULL is tolerated * @param signal_stale if set to #MHD_YES then indication of stale nonce used in * the client's request is signalled by adding 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use; if several algorithms are allowed * then MD5 is preferred (currently, may be changed in next * versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, allowing client to provide * hash("username:realm") instead of the username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding for * the username is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_required_response3 (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, int userhash_support, int prefer_utf8) { struct DigestAlgorithm da; char *buf_ptr; enum MHD_Result ret; buf_ptr = NULL; digest_setup_zero (&da); ret = queue_auth_required_response3_inner (connection, realm, opaque, domain, response, signal_stale, mqop, malgo3, userhash_support, prefer_utf8, &buf_ptr, &da); digest_deinit (&da); if (NULL != buf_ptr) free (buf_ptr); return ret; } /** * Queues a response to request authentication from the client * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @param algo digest algorithm to use * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00096200 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthMultiAlgo3 algo3; if (MHD_DIGEST_ALG_MD5 == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else if (MHD_DIGEST_ALG_AUTO == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; else MHD_PANIC (_ ("Wrong algo value.\n")); /* API violation! */ return MHD_queue_auth_required_response3 (connection, realm, opaque, NULL, response, signal_stale, MHD_DIGEST_AUTH_MULT_QOP_AUTH, algo3, 0, 0); } /** * Queues a response to request authentication from the client. * For now uses MD5 (for backwards-compatibility). Still, if you * need to be sure, use #MHD_queue_auth_fail_response2(). * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @return #MHD_YES on success, #MHD_NO otherwise * @ingroup authentication * @deprecated use MHD_queue_auth_fail_response2() */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale) { return MHD_queue_auth_fail_response2 (connection, realm, opaque, response, signal_stale, MHD_DIGEST_ALG_MD5); } /* end of digestauth.c */ libmicrohttpd-1.0.2/src/microhttpd/mhd_limits.h0000644000175000017500000001033715035214301016543 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_limits.h * @brief limits values definitions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_LIMITS_H #define MHD_LIMITS_H #include "platform.h" #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #define MHD_UNSIGNED_TYPE_MAX_(type) ((type) - 1) /* Assume 8 bits per byte, no padding bits. */ #define MHD_SIGNED_TYPE_MAX_(type) \ ( (type) ((( ((type) 1) << (sizeof(type) * 8 - 2)) - 1) * 2 + 1) ) #define MHD_TYPE_IS_SIGNED_(type) (((type) 0)>((type) - 1)) #ifndef INT_MAX #ifdef __INT_MAX__ #define INT_MAX __INT_MAX__ #else /* ! __UINT_MAX__ */ #define INT_MAX MHD_SIGNED_TYPE_MAX_ (int) #endif /* ! __UINT_MAX__ */ #endif /* !UINT_MAX */ #ifndef UINT_MAX #ifdef __UINT_MAX__ #define UINT_MAX __UINT_MAX__ #else /* ! __UINT_MAX__ */ #define UINT_MAX MHD_UNSIGNED_TYPE_MAX_ (unsigned int) #endif /* ! __UINT_MAX__ */ #endif /* !UINT_MAX */ #ifndef LONG_MAX #ifdef __LONG_MAX__ #define LONG_MAX __LONG_MAX__ #else /* ! __LONG_MAX__ */ #define LONG_MAX MHD_SIGNED_TYPE_MAX (long) #endif /* ! __LONG_MAX__ */ #endif /* !LONG_MAX */ #ifndef ULLONG_MAX #ifdef ULONGLONG_MAX #define ULLONG_MAX ULONGLONG_MAX #else /* ! ULONGLONG_MAX */ #define ULLONG_MAX MHD_UNSIGNED_TYPE_MAX_ (MHD_UNSIGNED_LONG_LONG) #endif /* ! ULONGLONG_MAX */ #endif /* !ULLONG_MAX */ #ifndef INT32_MAX #ifdef __INT32_MAX__ #define INT32_MAX __INT32_MAX__ #else /* ! __INT32_MAX__ */ #define INT32_MAX ((int32_t) 0x7FFFFFFF) #endif /* ! __INT32_MAX__ */ #endif /* !INT32_MAX */ #ifndef UINT32_MAX #ifdef __UINT32_MAX__ #define UINT32_MAX __UINT32_MAX__ #else /* ! __UINT32_MAX__ */ #define UINT32_MAX ((int32_t) 0xFFFFFFFF) #endif /* ! __UINT32_MAX__ */ #endif /* !UINT32_MAX */ #ifndef UINT64_MAX #ifdef __UINT64_MAX__ #define UINT64_MAX __UINT64_MAX__ #else /* ! __UINT64_MAX__ */ #define UINT64_MAX ((uint64_t) 0xFFFFFFFFFFFFFFFF) #endif /* ! __UINT64_MAX__ */ #endif /* !UINT64_MAX */ #ifndef INT64_MAX #ifdef __INT64_MAX__ #define INT64_MAX __INT64_MAX__ #else /* ! __INT64_MAX__ */ #define INT64_MAX ((int64_t) 0x7FFFFFFFFFFFFFFF) #endif /* ! __UINT64_MAX__ */ #endif /* !INT64_MAX */ #ifndef SIZE_MAX #ifdef __SIZE_MAX__ #define SIZE_MAX __SIZE_MAX__ #elif defined(UINTPTR_MAX) #define SIZE_MAX UINTPTR_MAX #else /* ! __SIZE_MAX__ */ #define SIZE_MAX MHD_UNSIGNED_TYPE_MAX_ (size_t) #endif /* ! __SIZE_MAX__ */ #endif /* !SIZE_MAX */ #ifndef SSIZE_MAX #ifdef __SSIZE_MAX__ #define SSIZE_MAX __SSIZE_MAX__ #elif defined(INTPTR_MAX) #define SSIZE_MAX INTPTR_MAX #else #define SSIZE_MAX MHD_SIGNED_TYPE_MAX_ (ssize_t) #endif #endif /* ! SSIZE_MAX */ #ifndef OFF_T_MAX #ifdef OFF_MAX #define OFF_T_MAX OFF_MAX #elif defined(OFFT_MAX) #define OFF_T_MAX OFFT_MAX #elif defined(__APPLE__) && defined(__MACH__) #define OFF_T_MAX INT64_MAX #else #define OFF_T_MAX MHD_SIGNED_TYPE_MAX_ (off_t) #endif #endif /* !OFF_T_MAX */ #if defined(_LARGEFILE64_SOURCE) && ! defined(OFF64_T_MAX) #define OFF64_T_MAX MHD_SIGNED_TYPE_MAX_ (uint64_t) #endif /* _LARGEFILE64_SOURCE && !OFF64_T_MAX */ #ifndef TIME_T_MAX #define TIME_T_MAX ((time_t) \ (MHD_TYPE_IS_SIGNED_ (time_t) ? \ MHD_SIGNED_TYPE_MAX_ (time_t) : \ MHD_UNSIGNED_TYPE_MAX_ (time_t))) #endif /* !TIME_T_MAX */ #ifndef TIMEVAL_TV_SEC_MAX #ifndef _WIN32 #define TIMEVAL_TV_SEC_MAX TIME_T_MAX #else /* _WIN32 */ #define TIMEVAL_TV_SEC_MAX LONG_MAX #endif /* _WIN32 */ #endif /* !TIMEVAL_TV_SEC_MAX */ #endif /* MHD_LIMITS_H */ libmicrohttpd-1.0.2/src/microhttpd/test_str_pct.c0000644000175000017500000011247514760713574017154 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_pct.c * @brief Unit tests for percent (URL) encoded strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str, size_t len) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); size_t r_pos = 0; size_t w_pos = 0; if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0]))) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (len > r_pos && w_pos + 1 < buf_size) { const unsigned char c = (unsigned char) str[r_pos]; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } r_pos++; } if (len != r_pos) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } #define TEST_BIN_MAX_SIZE 1024 /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_n (const char *const encoded, const size_t encoded_len, const char *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1); mhd_assert (encoded_len >= decoded_size); ret = 0; /* check MHD_str_pct_decode_strict_n_() with small out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size + 1); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_strict_n_() with large out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, encoded_len + 1); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with small out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->false) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with large out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, encoded_len + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->false) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } if (strlen (encoded) == encoded_len) { /* check MHD_str_pct_decode_in_place_strict_() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_strict_ (buf); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "A char written outside the buffer:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_in_place_lenient_() */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "A char written outside the buffer:\n"); } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->%s) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->false) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded(e,d) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ d,MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded ("", ""); /* Base sequences without percent symbol */ r += expect_decoded ("aaa", "aaa"); r += expect_decoded ("bbb", "bbb"); r += expect_decoded ("ccc", "ccc"); r += expect_decoded ("ddd", "ddd"); r += expect_decoded ("lll", "lll"); r += expect_decoded ("mmm", "mmm"); r += expect_decoded ("nnn", "nnn"); r += expect_decoded ("ooo", "ooo"); r += expect_decoded ("www", "www"); r += expect_decoded ("xxx", "xxx"); r += expect_decoded ("yyy", "yyy"); r += expect_decoded ("zzz", "zzz"); r += expect_decoded ("AAA", "AAA"); r += expect_decoded ("GGG", "GGG"); r += expect_decoded ("MMM", "MMM"); r += expect_decoded ("TTT", "TTT"); r += expect_decoded ("ZZZ", "ZZZ"); r += expect_decoded ("012", "012"); r += expect_decoded ("345", "345"); r += expect_decoded ("678", "678"); r += expect_decoded ("901", "901"); r += expect_decoded ("aaaaaa", "aaaaaa"); r += expect_decoded ("bbbbbb", "bbbbbb"); r += expect_decoded ("cccccc", "cccccc"); r += expect_decoded ("dddddd", "dddddd"); r += expect_decoded ("llllll", "llllll"); r += expect_decoded ("mmmmmm", "mmmmmm"); r += expect_decoded ("nnnnnn", "nnnnnn"); r += expect_decoded ("oooooo", "oooooo"); r += expect_decoded ("wwwwww", "wwwwww"); r += expect_decoded ("xxxxxx", "xxxxxx"); r += expect_decoded ("yyyyyy", "yyyyyy"); r += expect_decoded ("zzzzzz", "zzzzzz"); r += expect_decoded ("AAAAAA", "AAAAAA"); r += expect_decoded ("GGGGGG", "GGGGGG"); r += expect_decoded ("MMMMMM", "MMMMMM"); r += expect_decoded ("TTTTTT", "TTTTTT"); r += expect_decoded ("ZZZZZZ", "ZZZZZZ"); r += expect_decoded ("012012", "012012"); r += expect_decoded ("345345", "345345"); r += expect_decoded ("678678", "678678"); r += expect_decoded ("901901", "901901"); r += expect_decoded ("a", "a"); r += expect_decoded ("bc", "bc"); r += expect_decoded ("DEFG", "DEFG"); r += expect_decoded ("123t", "123t"); r += expect_decoded ("12345", "12345"); r += expect_decoded ("TestStr", "TestStr"); r += expect_decoded ("Teststring", "Teststring"); r += expect_decoded ("Teststring.", "Teststring."); r += expect_decoded ("Longerstring", "Longerstring"); r += expect_decoded ("Longerstring.", "Longerstring."); r += expect_decoded ("Longerstring2.", "Longerstring2."); /* Simple percent-encoded strings */ r += expect_decoded ("Test%20string", "Test string"); r += expect_decoded ("Test%3Fstring.", "Test?string."); r += expect_decoded ("100%25", "100%"); r += expect_decoded ("a%2C%20b%3Dc%26e%3Dg", "a, b=c&e=g"); r += expect_decoded ("%20%21%23%24%25%26%27%28%29%2A%2B%2C" "%2F%3A%3B%3D%3F%40%5B%5D%09", " !#$%&'()*+,/:;=?@[]\t"); return r; } #define expect_decoded_arr(e,a) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ (const char *)a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The lower case */ r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e" \ "%0f%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d" \ "%1e%1f%20%21%22%23%24%25%26%27%28%29%2a%2b%2c" \ "%2d%2e%2f%30%31%32%33%34%35%36%37%38%39%3a%3b" \ "%3c%3d%3e%3f%40%41%42%43%44%45%46%47%48%49%4a" \ "%4b%4c%4d%4e%4f%50%51%52%53%54%55%56%57%58%59" \ "%5a%5b%5c%5d%5e%5f%60%61%62%63%64%65%66%67%68" \ "%69%6a%6b%6c%6d%6e%6f%70%71%72%73%74%75%76%77" \ "%78%79%7a%7b%7c%7d%7e%7f%80%81%82%83%84%85%86" \ "%87%88%89%8a%8b%8c%8d%8e%8f%90%91%92%93%94%95" \ "%96%97%98%99%9a%9b%9c%9d%9e%9f%a0%a1%a2%a3%a4" \ "%a5%a6%a7%a8%a9%aa%ab%ac%ad%ae%af%b0%b1%b2%b3" \ "%b4%b5%b6%b7%b8%b9%ba%bb%bc%bd%be%bf%c0%c1%c2" \ "%c3%c4%c5%c6%c7%c8%c9%ca%cb%cc%cd%ce%cf%d0%d1" \ "%d2%d3%d4%d5%d6%d7%d8%d9%da%db%dc%dd%de%df%e0" \ "%e1%e2%e3%e4%e5%e6%e7%e8%e9%ea%eb%ec%ed%ee%ef" \ "%f0%f1%f2%f3%f4%f5%f6%f7%f8%f9%fa%fb%fc%fd%fe" \ "%ff", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The upper case */ r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E" \ "%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D" \ "%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C" \ "%2D%2E%2F%30%31%32%33%34%35%36%37%38%39%3A%3B" \ "%3C%3D%3E%3F%40%41%42%43%44%45%46%47%48%49%4A" \ "%4B%4C%4D%4E%4F%50%51%52%53%54%55%56%57%58%59" \ "%5A%5B%5C%5D%5E%5F%60%61%62%63%64%65%66%67%68" \ "%69%6A%6B%6C%6D%6E%6F%70%71%72%73%74%75%76%77" \ "%78%79%7A%7B%7C%7D%7E%7F%80%81%82%83%84%85%86" \ "%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95" \ "%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4" \ "%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3" \ "%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2" \ "%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1" \ "%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0" \ "%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF" \ "%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE" \ "%FF", bin); } return r; } /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_bad_n (const char *const encoded, const size_t encoded_len, const char *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1); mhd_assert (encoded_len >= decoded_size); ret = 0; /* check MHD_str_pct_decode_strict_n_() with small out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->(not defined), %u) -> 0\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_strict_n_() with large out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, encoded_len + 1); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->(not defined), %u) -> 0\n", n_prnt (encoded, encoded_len), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with small out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->true) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with large out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, encoded_len + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->true) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } if (strlen (encoded) == encoded_len) { /* check MHD_str_pct_decode_in_place_strict_() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_strict_ (buf); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> (not defined)) -> 0\n", n_prnt (encoded, encoded_len)); } } /* check MHD_str_pct_decode_in_place_lenient_() */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "A char written outside the buffer:\n"); } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->%s) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->true) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded_bad(e,d) \ expect_decoded_bad_n(e,MHD_STATICSTR_LEN_(e),\ d,MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_bad_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded_bad ("50%/50%", "50%/50%"); r += expect_decoded_bad ("This is 100% incorrect.", "This is 100% incorrect."); r += expect_decoded_bad ("Some %%", "Some %%"); r += expect_decoded_bad ("1 %", "1 %"); r += expect_decoded_bad ("%", "%"); r += expect_decoded_bad ("%a", "%a"); r += expect_decoded_bad ("%0", "%0"); r += expect_decoded_bad ("%0x", "%0x"); r += expect_decoded_bad ("%FX", "%FX"); r += expect_decoded_bad ("Valid%20and%2invalid", "Valid and%2invalid"); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_str (); errcount += check_decode_bin (); errcount += check_decode_bad_str (); if (0 == errcount) printf ("All tests have been passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/mhd_sockets.h0000644000175000017500000007701214760713577016747 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2014-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_sockets.c * @brief Header for platform-independent sockets abstraction * @author Karlson2k (Evgeny Grin) * * Provides basic abstraction for sockets. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_SOCKETS_H #define MHD_SOCKETS_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) # include # define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #if ! defined(MHD_POSIX_SOCKETS) && ! defined(MHD_WINSOCK_SOCKETS) # if ! defined(_WIN32) || defined(__CYGWIN__) # define MHD_POSIX_SOCKETS 1 # else /* defined(_WIN32) && !defined(__CYGWIN__) */ # define MHD_WINSOCK_SOCKETS 1 # endif /* defined(_WIN32) && !defined(__CYGWIN__) */ #endif /* !MHD_POSIX_SOCKETS && !MHD_WINSOCK_SOCKETS */ /* * MHD require headers that define socket type, socket basic functions * (socket(), accept(), listen(), bind(), send(), recv(), select()), socket * parameters like SOCK_CLOEXEC, SOCK_NONBLOCK, additional socket functions * (poll(), epoll(), accept4()), struct timeval and other types, required * for socket function. */ #if defined(MHD_POSIX_SOCKETS) # ifdef HAVE_SYS_TYPES_H # include /* required on old platforms */ # endif # ifdef HAVE_SYS_TIME_H # include # endif # ifdef HAVE_TIME_H # include # endif # ifdef HAVE_STRING_H # include /* for strerror() */ # endif # ifdef HAVE_SYS_SOCKET_H # include # endif # if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) # include /* required for FD_SET (bzero() function) */ # ifdef HAVE_SOCKLIB_H # include # endif /* HAVE_SOCKLIB_H */ # ifdef HAVE_INETLIB_H # include # endif /* HAVE_INETLIB_H */ # endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */ # ifdef HAVE_NETINET_IN_H # include # endif /* HAVE_NETINET_IN_H */ # ifdef HAVE_ARPA_INET_H # include # endif # ifdef HAVE_NET_IF_H # include # endif # ifdef HAVE_NETDB_H # include # endif # ifdef HAVE_SYS_SELECT_H # include # endif # ifdef EPOLL_SUPPORT # include # endif # ifdef HAVE_NETINET_TCP_H /* for TCP_FASTOPEN and TCP_CORK */ # include # endif #elif defined(MHD_WINSOCK_SOCKETS) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include # include #endif /* MHD_WINSOCK_SOCKETS */ #if defined(HAVE_POLL_H) && defined(HAVE_POLL) # include #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include /* For __FreeBSD_version */ #endif /* __FreeBSD__ */ #include "mhd_limits.h" #ifdef _MHD_FD_SETSIZE_IS_DEFAULT # define _MHD_SYS_DEFAULT_FD_SETSIZE FD_SETSIZE #else /* ! _MHD_FD_SETSIZE_IS_DEFAULT */ # ifndef MHD_SYS_FD_SETSIZE_ # include "sysfdsetsize.h" # define _MHD_SYS_DEFAULT_FD_SETSIZE get_system_fdsetsize_value () # else /* MHD_SYS_FD_SETSIZE_ */ # define _MHD_SYS_DEFAULT_FD_SETSIZE MHD_SYS_FD_SETSIZE_ # endif /* MHD_SYS_FD_SETSIZE_ */ #endif /* ! _MHD_FD_SETSIZE_IS_DEFAULT */ #ifndef MHD_PANIC # include # include /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #ifndef MHD_SOCKET_DEFINED /** * MHD_socket is type for socket FDs */ # if defined(MHD_POSIX_SOCKETS) typedef int MHD_socket; # define MHD_INVALID_SOCKET (-1) # elif defined(MHD_WINSOCK_SOCKETS) typedef SOCKET MHD_socket; # define MHD_INVALID_SOCKET (INVALID_SOCKET) # endif /* MHD_WINSOCK_SOCKETS */ # define MHD_SOCKET_DEFINED 1 #endif /* ! MHD_SOCKET_DEFINED */ #ifdef SOCK_CLOEXEC # define SOCK_CLOEXEC_OR_ZERO SOCK_CLOEXEC #else /* ! SOCK_CLOEXEC */ # define SOCK_CLOEXEC_OR_ZERO 0 #endif /* ! SOCK_CLOEXEC */ #ifdef HAVE_SOCK_NONBLOCK # define SOCK_NONBLOCK_OR_ZERO SOCK_NONBLOCK #else /* ! HAVE_SOCK_NONBLOCK */ # define SOCK_NONBLOCK_OR_ZERO 0 #endif /* ! HAVE_SOCK_NONBLOCK */ #ifdef SOCK_NOSIGPIPE # define SOCK_NOSIGPIPE_OR_ZERO SOCK_NOSIGPIPE #else /* ! HAVE_SOCK_NONBLOCK */ # define SOCK_NOSIGPIPE_OR_ZERO 0 #endif /* ! HAVE_SOCK_NONBLOCK */ #ifdef MSG_NOSIGNAL # define MSG_NOSIGNAL_OR_ZERO MSG_NOSIGNAL #else /* ! MSG_NOSIGNAL */ # define MSG_NOSIGNAL_OR_ZERO 0 #endif /* ! MSG_NOSIGNAL */ #if ! defined(SHUT_WR) && defined(SD_SEND) # define SHUT_WR SD_SEND #endif #if ! defined(SHUT_RD) && defined(SD_RECEIVE) # define SHUT_RD SD_RECEIVE #endif #if ! defined(SHUT_RDWR) && defined(SD_BOTH) # define SHUT_RDWR SD_BOTH #endif #if defined(HAVE_ACCEPT4) && (defined(HAVE_SOCK_NONBLOCK) || \ defined(SOCK_CLOEXEC) || defined(SOCK_NOSIGPIPE)) # define USE_ACCEPT4 1 #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \ defined(__OpenBSD__) || defined(__NetBSD__) || \ defined(MHD_WINSOCK_SOCKETS) || defined(__MACH__) || defined(__sun) || \ defined(SOMEBSD) /* Most of OSes inherit nonblocking setting from the listen socket */ #define MHD_ACCEPT_INHERIT_NONBLOCK 1 #endif #if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC) # define USE_EPOLL_CREATE1 1 #endif /* HAVE_EPOLL_CREATE1 && EPOLL_CLOEXEC */ #ifdef TCP_FASTOPEN /** * Default TCP fastopen queue size. */ #define MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT 10 #endif #if defined(TCP_CORK) /** * Value of TCP_CORK or TCP_NOPUSH */ #define MHD_TCP_CORK_NOPUSH TCP_CORK #elif defined(TCP_NOPUSH) /** * Value of TCP_CORK or TCP_NOPUSH */ #define MHD_TCP_CORK_NOPUSH TCP_NOPUSH #endif /* TCP_NOPUSH */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef __linux__ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network * even if TCP_CORK/TCP_NOPUSH was in switched off state. */ #define _MHD_CORK_RESET_PUSH_DATA_ALWAYS 1 #endif /* __linux__ */ #if (defined(__FreeBSD__) && \ ((__FreeBSD__ + 0) >= 5 || (__FreeBSD_version + 0) >= 450000)) || \ (defined(__FreeBSD_kernel_version) && \ (__FreeBSD_kernel_version + 0) >= 450000) /* FreeBSD pushes data to the network with reset of TCP_NOPUSH * starting from version 4.5. */ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 #endif /* __FreeBSD_version >= 450000 */ #ifdef __OpenBSD__ /* OpenBSD took implementation from FreeBSD */ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 #endif /* __OpenBSD__ */ #endif /* MHD_TCP_CORK_NOPUSH */ #ifdef __linux__ /** * Indicate that set of TCP_NODELAY push data to the network */ #define _MHD_NODELAY_SET_PUSH_DATA 1 /** * Indicate that set of TCP_NODELAY push data to the network even * if TCP_DELAY was already set and regardless of TCP_CORK / TCP_NOPUSH state */ #define _MHD_NODELAY_SET_PUSH_DATA_ALWAYS 1 #endif /* __linux__ */ #ifdef MSG_MORE #ifdef __linux__ /* MSG_MORE signal kernel to buffer outbond data and works like * TCP_CORK per call without actually setting TCP_CORK value. * It's known to work on Linux. Add more OSes if they are compatible. */ /** * Indicate MSG_MORE is usable for buffered send(). */ #define MHD_USE_MSG_MORE 1 #endif /* __linux__ */ #endif /* MSG_MORE */ /** * MHD_SCKT_OPT_BOOL_ is type for bool parameters for setsockopt()/getsockopt() */ #ifdef MHD_POSIX_SOCKETS typedef int MHD_SCKT_OPT_BOOL_; #else /* MHD_WINSOCK_SOCKETS */ typedef BOOL MHD_SCKT_OPT_BOOL_; #endif /* MHD_WINSOCK_SOCKETS */ /** * MHD_SCKT_SEND_SIZE_ is type used to specify size for send and recv * functions */ #if ! defined(MHD_WINSOCK_SOCKETS) typedef size_t MHD_SCKT_SEND_SIZE_; #else typedef int MHD_SCKT_SEND_SIZE_; #endif /** * MHD_SCKT_SEND_MAX_SIZE_ is maximum send()/recv() size value. */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_SEND_MAX_SIZE_ SSIZE_MAX #else # define MHD_SCKT_SEND_MAX_SIZE_ INT_MAX #endif /** * MHD_socket_close_(fd) close any FDs (non-W32) / close only socket * FDs (W32). Note that on HP-UNIX, this function may leak the FD if * errno is set to EINTR. Do not use HP-UNIX. * * @param fd descriptor to close * @return boolean true on success (error codes like EINTR and EIO are * counted as success, only EBADF counts as an error!), * boolean false otherwise. */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_close_(fd) ((0 == close ((fd))) || (EBADF != errno)) #else # define MHD_socket_close_(fd) (0 == closesocket ((fd))) #endif /** * MHD_socket_close_chk_(fd) close socket and abort execution * if error is detected. * @param fd socket to close */ #define MHD_socket_close_chk_(fd) do { \ if (! MHD_socket_close_ (fd)) \ MHD_PANIC (_ ("Close socket failed.\n")); \ } while (0) /** * MHD_send4_ is a wrapper for system's send() * @param s the socket to use * @param b the buffer with data to send * @param l the length of data in @a b * @param f the additional flags * @return ssize_t type value */ #define MHD_send4_(s,b,l,f) \ ((ssize_t) send ((s),(const void*) (b),(MHD_SCKT_SEND_SIZE_) (l), \ ((MSG_NOSIGNAL_OR_ZERO) | (f)))) /** * MHD_send_ is a simple wrapper for system's send() * @param s the socket to use * @param b the buffer with data to send * @param l the length of data in @a b * @return ssize_t type value */ #define MHD_send_(s,b,l) MHD_send4_((s),(b),(l), 0) /** * MHD_recv_ is wrapper for system's recv() * @param s the socket to use * @param b the buffer for data to receive * @param l the length of @a b * @return ssize_t type value */ #define MHD_recv_(s,b,l) \ ((ssize_t) recv ((s),(void*) (b),(MHD_SCKT_SEND_SIZE_) (l), 0)) /** * Check whether FD can be added to fd_set with specified FD_SETSIZE. * @param fd the fd to check * @param pset the pointer to fd_set to check or NULL to check * whether FD can be used with fd_sets. * @param setsize the value of FD_SETSIZE. * @return boolean true if FD can be added to fd_set, * boolean false otherwise. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \ ((fd) < ((MHD_socket) (setsize))) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \ ( ((void*) (pset)== (void*) 0) || \ (((fd_set*) (pset))->fd_count < ((unsigned) setsize)) || \ (FD_ISSET ((fd), (pset))) ) #endif /** * Check whether FD can be added to fd_set with current FD_SETSIZE. * @param fd the fd to check * @param pset the pointer to fd_set to check or NULL to check * whether FD can be used with fd_sets. * @return boolean true if FD can be added to fd_set, * boolean false otherwise. */ #define MHD_SCKT_FD_FITS_FDSET_(fd,pset) \ MHD_SCKT_FD_FITS_FDSET_SETSIZE_ ((fd), (pset), FD_SETSIZE) /** * Add FD to fd_set with specified FD_SETSIZE. * @param fd the fd to add * @param pset the valid pointer to fd_set. * @param setsize the value of FD_SETSIZE. * @note To work on W32 with value of FD_SETSIZE different from currently defined value, * system definition of FD_SET() is not used. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) \ FD_SET ((fd), (pset)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) \ do { \ u_int _i_ = 0; \ fd_set*const _s_ = (fd_set*) (pset); \ while ((_i_ < _s_->fd_count) && ((fd) != _s_->fd_array [_i_])) {++_i_;} \ if ((_i_ == _s_->fd_count)) {_s_->fd_array [_s_->fd_count ++] = (fd);} \ } while (0) #endif /* MHD_SYS_select_ is wrapper macro for system select() function */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_SYS_select_(n,r,w,e,t) select ((n),(r),(w),(e),(t)) #else # define MHD_SYS_select_(n,r,w,e,t) \ ( ( (((void*) (r) == (void*) 0) || ((fd_set*) (r))->fd_count == 0) && \ (((void*) (w) == (void*) 0) || ((fd_set*) (w))->fd_count == 0) && \ (((void*) (e) == (void*) 0) || ((fd_set*) (e))->fd_count == 0) ) ? \ ( ((void*) (t) == (void*) 0) ? 0 : \ (Sleep ((DWORD)((struct timeval*) (t))->tv_sec * 1000 \ + (DWORD)((struct timeval*) (t))->tv_usec / 1000), 0) ) : \ (select ((int) 0,(r),(w),(e),(t))) ) #endif #if defined(HAVE_POLL) /* MHD_sys_poll_ is wrapper macro for system poll() function */ # if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_sys_poll_ poll # else /* MHD_WINSOCK_SOCKETS */ # define MHD_sys_poll_ WSAPoll # endif /* MHD_WINSOCK_SOCKETS */ # ifdef POLLPRI # define MHD_POLLPRI_OR_ZERO POLLPRI # else /* ! POLLPRI */ # define MHD_POLLPRI_OR_ZERO 0 # endif /* ! POLLPRI */ # ifdef POLLRDBAND # define MHD_POLLRDBAND_OR_ZERO POLLRDBAND # else /* ! POLLRDBAND */ # define MHD_POLLRDBAND_OR_ZERO 0 # endif /* ! POLLRDBAND */ # ifdef POLLNVAL # define MHD_POLLNVAL_OR_ZERO POLLNVAL # else /* ! POLLNVAL */ # define MHD_POLLNVAL_OR_ZERO 0 # endif /* ! POLLNVAL */ /* MHD_POLL_EVENTS_ERR_DISC is 'events' mask for errors and disconnect. * Note: Out-of-band data is treated as error. */ # if defined(_WIN32) && ! defined(__CYGWIN__) # define MHD_POLL_EVENTS_ERR_DISC POLLRDBAND # elif defined(__linux__) # define MHD_POLL_EVENTS_ERR_DISC POLLPRI # else /* ! __linux__ */ # define MHD_POLL_EVENTS_ERR_DISC \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO) # endif /* ! __linux__ */ /* MHD_POLL_REVENTS_ERR_DISC is 'revents' mask for errors and disconnect. * Note: Out-of-band data is treated as error. */ # define MHD_POLL_REVENTS_ERR_DISC \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \ | POLLERR | POLLHUP) /* MHD_POLL_REVENTS_ERRROR is 'revents' mask for errors. * Note: Out-of-band data is treated as error. */ # define MHD_POLL_REVENTS_ERRROR \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \ | POLLERR) #endif /* HAVE_POLL */ #define MHD_SCKT_MISSING_ERR_CODE_ 31450 #if defined(MHD_POSIX_SOCKETS) # if defined(EAGAIN) # define MHD_SCKT_EAGAIN_ EAGAIN # elif defined(EWOULDBLOCK) # define MHD_SCKT_EAGAIN_ EWOULDBLOCK # else /* !EAGAIN && !EWOULDBLOCK */ # define MHD_SCKT_EAGAIN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* !EAGAIN && !EWOULDBLOCK */ # if defined(EWOULDBLOCK) # define MHD_SCKT_EWOULDBLOCK_ EWOULDBLOCK # elif defined(EAGAIN) # define MHD_SCKT_EWOULDBLOCK_ EAGAIN # else /* !EWOULDBLOCK && !EAGAIN */ # define MHD_SCKT_EWOULDBLOCK_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* !EWOULDBLOCK && !EAGAIN */ # ifdef EINTR # define MHD_SCKT_EINTR_ EINTR # else /* ! EINTR */ # define MHD_SCKT_EINTR_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINTR */ # ifdef ECONNRESET # define MHD_SCKT_ECONNRESET_ ECONNRESET # else /* ! ECONNRESET */ # define MHD_SCKT_ECONNRESET_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ECONNRESET */ # ifdef ECONNABORTED # define MHD_SCKT_ECONNABORTED_ ECONNABORTED # else /* ! ECONNABORTED */ # define MHD_SCKT_ECONNABORTED_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ECONNABORTED */ # ifdef ENOTCONN # define MHD_SCKT_ENOTCONN_ ENOTCONN # else /* ! ENOTCONN */ # define MHD_SCKT_ENOTCONN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTCONN */ # ifdef EMFILE # define MHD_SCKT_EMFILE_ EMFILE # else /* ! EMFILE */ # define MHD_SCKT_EMFILE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EMFILE */ # ifdef ENFILE # define MHD_SCKT_ENFILE_ ENFILE # else /* ! ENFILE */ # define MHD_SCKT_ENFILE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENFILE */ # ifdef ENOMEM # define MHD_SCKT_ENOMEM_ ENOMEM # else /* ! ENOMEM */ # define MHD_SCKT_ENOMEM_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOMEM */ # ifdef ENOBUFS # define MHD_SCKT_ENOBUFS_ ENOBUFS # else /* ! ENOBUFS */ # define MHD_SCKT_ENOBUFS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOBUFS */ # ifdef EBADF # define MHD_SCKT_EBADF_ EBADF # else /* ! EBADF */ # define MHD_SCKT_EBADF_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EBADF */ # ifdef ENOTSOCK # define MHD_SCKT_ENOTSOCK_ ENOTSOCK # else /* ! ENOTSOCK */ # define MHD_SCKT_ENOTSOCK_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTSOCK */ # ifdef EINVAL # define MHD_SCKT_EINVAL_ EINVAL # else /* ! EINVAL */ # define MHD_SCKT_EINVAL_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINVAL */ # ifdef EPIPE # define MHD_SCKT_EPIPE_ EPIPE # else /* ! EPIPE */ # define MHD_SCKT_EPIPE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EPIPE */ # ifdef EFAULT # define MHD_SCKT_EFAUL_ EFAULT # else /* ! EFAULT */ # define MHD_SCKT_EFAUL_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EFAULT */ # ifdef ENOSYS # define MHD_SCKT_ENOSYS_ ENOSYS # else /* ! ENOSYS */ # define MHD_SCKT_ENOSYS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOSYS */ # ifdef ENOPROTOOPT # define MHD_SCKT_ENOPROTOOPT_ ENOPROTOOPT # else /* ! ENOPROTOOPT */ # define MHD_SCKT_ENOPROTOOPT_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOPROTOOPT */ # ifdef ENOTSUP # define MHD_SCKT_ENOTSUP_ ENOTSUP # else /* ! ENOTSUP */ # define MHD_SCKT_ENOTSUP_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTSUP */ # ifdef EOPNOTSUPP # define MHD_SCKT_EOPNOTSUPP_ EOPNOTSUPP # else /* ! EOPNOTSUPP */ # define MHD_SCKT_EOPNOTSUPP_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EOPNOTSUPP */ # ifdef EACCES # define MHD_SCKT_EACCESS_ EACCES # else /* ! EACCES */ # define MHD_SCKT_EACCESS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EACCES */ # ifdef ENETDOWN # define MHD_SCKT_ENETDOWN_ ENETDOWN # else /* ! ENETDOWN */ # define MHD_SCKT_ENETDOWN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENETDOWN */ # ifdef EALREADY # define MHD_SCKT_EALREADY_ EALREADY # else /* ! EALREADY */ # define MHD_SCKT_EALREADY_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EALREADY */ # ifdef EINPROGRESS # define MHD_SCKT_EINPROGRESS_ EINPROGRESS # else /* ! EINPROGRESS */ # define MHD_SCKT_EINPROGRESS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINPROGRESS */ # ifdef EISCONN # define MHD_SCKT_EISCONN_ EISCONN # else /* ! EISCONN */ # define MHD_SCKT_EISCONN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EISCONN */ #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_EAGAIN_ WSAEWOULDBLOCK # define MHD_SCKT_EWOULDBLOCK_ WSAEWOULDBLOCK # define MHD_SCKT_EINTR_ WSAEINTR # define MHD_SCKT_ECONNRESET_ WSAECONNRESET # define MHD_SCKT_ECONNABORTED_ WSAECONNABORTED # define MHD_SCKT_ENOTCONN_ WSAENOTCONN # define MHD_SCKT_EMFILE_ WSAEMFILE # define MHD_SCKT_ENFILE_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOMEM_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOBUFS_ WSAENOBUFS # define MHD_SCKT_EBADF_ WSAEBADF # define MHD_SCKT_ENOTSOCK_ WSAENOTSOCK # define MHD_SCKT_EINVAL_ WSAEINVAL # define MHD_SCKT_EPIPE_ WSAESHUTDOWN # define MHD_SCKT_EFAUL_ WSAEFAULT # define MHD_SCKT_ENOSYS_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOPROTOOPT_ WSAENOPROTOOPT # define MHD_SCKT_ENOTSUP_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_EOPNOTSUPP_ WSAEOPNOTSUPP # define MHD_SCKT_EACCESS_ WSAEACCES # define MHD_SCKT_ENETDOWN_ WSAENETDOWN # define MHD_SCKT_EALREADY_ WSAEALREADY # define MHD_SCKT_EINPROGRESS_ WSAEINPROGRESS # define MHD_SCKT_EISCONN_ WSAEISCONN #endif /** * MHD_socket_error_ return system native error code for last socket error. * @return system error code for last socket error. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_get_error_() (errno) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_get_error_() WSAGetLastError () #endif #ifdef MHD_WINSOCK_SOCKETS /* POSIX-W32 sockets compatibility functions */ /** * Return pointer to string description of specified WinSock error * @param err the WinSock error code. * @return pointer to string description of specified WinSock error. */ const char *MHD_W32_strerror_winsock_ (int err); #endif /* MHD_WINSOCK_SOCKETS */ /* MHD_socket_last_strerr_ is description string of specified socket error code */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_strerr_(err) strerror ((err)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_strerr_(err) MHD_W32_strerror_winsock_ ((err)) #endif /* MHD_socket_last_strerr_ is description string of last errno (non-W32) / * description string of last socket error (W32) */ #define MHD_socket_last_strerr_() MHD_socket_strerr_ (MHD_socket_get_error_ ()) /** * MHD_socket_fset_error_() set socket system native error code. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_fset_error_(err) (errno = (err)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_fset_error_(err) (WSASetLastError ((err))) #endif /** * MHD_socket_try_set_error_() set socket system native error code if * specified code is defined on system. * @return non-zero if specified @a err code is defined on system * and error was set; * zero if specified @a err code is not defined on system * and error was not set. */ #define MHD_socket_try_set_error_(err) \ ( (MHD_SCKT_MISSING_ERR_CODE_ != (err)) ? \ (MHD_socket_fset_error_ ((err)), ! 0) : 0) /** * MHD_socket_set_error_() set socket system native error code to * specified code or replacement code if specified code is not * defined on system. */ #if defined(MHD_POSIX_SOCKETS) # if defined(ENOSYS) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = ENOSYS) : (errno = (err)) ) # elif defined(EOPNOTSUPP) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EOPNOTSUPP) : (errno = \ (err)) ) # elif defined(EFAULT) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EFAULT) : (errno = (err)) ) # elif defined(EINVAL) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EINVAL) : (errno = (err)) ) # else /* !EOPNOTSUPP && !EFAULT && !EINVAL */ # warning \ No suitable replacement for missing socket error code is found. Edit this file and add replacement code which is defined on system. # define MHD_socket_set_error_(err) (errno = (err)) # endif /* !EOPNOTSUPP && !EFAULT && !EINVAL*/ #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (WSASetLastError ((WSAEOPNOTSUPP))) : \ (WSASetLastError ((err))) ) #endif /** * Check whether given socket error is equal to specified system * native MHD_SCKT_E*_ code. * If platform don't have specific error code, result is * always boolean false. * @return boolean true if @a code is real error code and * @a err equals to MHD_SCKT_E*_ @a code; * boolean false otherwise */ #define MHD_SCKT_ERR_IS_(err,code) \ ( (MHD_SCKT_MISSING_ERR_CODE_ != (code)) && ((code) == (err)) ) /** * Check whether last socket error is equal to specified system * native MHD_SCKT_E*_ code. * If platform don't have specific error code, result is * always boolean false. * @return boolean true if @a code is real error code and * last socket error equals to MHD_SCKT_E*_ @a code; * boolean false otherwise */ #define MHD_SCKT_LAST_ERR_IS_(code) \ MHD_SCKT_ERR_IS_ (MHD_socket_get_error_ (), (code)) /* Specific error code checks */ /** * Check whether given socket error is equal to system's * socket error codes for EINTR. * @return boolean true if @a err is equal to sockets' EINTR code; * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_EINTR_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EINTR_) /** * Check whether given socket error is equal to system's * socket error codes for EAGAIN or EWOULDBLOCK. * @return boolean true if @a err is equal to sockets' EAGAIN or EWOULDBLOCK codes; * boolean false otherwise. */ #if MHD_SCKT_EAGAIN_ == MHD_SCKT_EWOULDBLOCK_ # define MHD_SCKT_ERR_IS_EAGAIN_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EAGAIN_) #else /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */ # define MHD_SCKT_ERR_IS_EAGAIN_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EAGAIN_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EWOULDBLOCK_) ) #endif /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */ /** * Check whether given socket error is any kind of "low resource" error. * @return boolean true if @a err is any kind of "low resource" error, * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_LOW_RESOURCES_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EMFILE_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENFILE_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOMEM_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOBUFS_) ) /** * Check whether is given socket error is type of "incoming connection * was disconnected before 'accept()' is called". * @return boolean true is @a err match described socket error code, * boolean false otherwise. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_) #endif /** * Check whether is given socket error is type of "connection was terminated * by remote side". * @return boolean true is @a err match described socket error code, * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_REMOTE_DISCNN_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_) ) /* Specific error code set */ /** * Set socket's error code to ENOMEM or equivalent if ENOMEM is not * available on platform. */ #if MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOMEM_ # define MHD_socket_set_error_to_ENOMEM() \ MHD_socket_set_error_ (MHD_SCKT_ENOMEM_) #elif MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOBUFS_ # define MHD_socket_set_error_to_ENOMEM() \ MHD_socket_set_error_ (MHD_SCKT_ENOBUFS_) #else # warning \ No suitable replacement for ENOMEM error codes is found. Edit this file and add replacement code which is defined on system. # define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \ MHD_SCKT_ENOMEM_) #endif /* Socket functions */ #if defined(AF_LOCAL) # define MHD_SCKT_LOCAL AF_LOCAL #elif defined(AF_UNIX) # define MHD_SCKT_LOCAL AF_UNIX #endif /* AF_UNIX */ #if defined(MHD_POSIX_SOCKETS) && defined(MHD_SCKT_LOCAL) # define MHD_socket_pair_(fdarr) \ (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM, 0, (fdarr))) # if defined(HAVE_SOCK_NONBLOCK) # define MHD_socket_pair_nblk_(fdarr) \ (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM | SOCK_NONBLOCK, 0, (fdarr))) # endif /* HAVE_SOCK_NONBLOCK*/ #elif defined(MHD_WINSOCK_SOCKETS) /** * Create pair of mutually connected TCP/IP sockets on loopback address * @param sockets_pair array to receive resulted sockets * @param non_blk if set to non-zero value, sockets created in non-blocking mode * otherwise sockets will be in blocking mode * @return non-zero if succeeded, zero otherwise */ int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk); # define MHD_socket_pair_(fdarr) MHD_W32_socket_pair_ ((fdarr), 0) # define MHD_socket_pair_nblk_(fdarr) MHD_W32_socket_pair_ ((fdarr), 1) #endif /** * Add @a fd to the @a set. If @a fd is * greater than @a max_fd, set @a max_fd to @a fd. * * @param fd file descriptor to add to the @a set * @param set set to modify * @param max_fd maximum value to potentially update * @param fd_setsize value of FD_SETSIZE * @return non-zero if succeeded, zero otherwise */ int MHD_add_to_fd_set_ (MHD_socket fd, fd_set *set, MHD_socket *max_fd, int fd_setsize); /** * Change socket options to be non-blocking. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_socket_nonblocking_ (MHD_socket sock); /** * Disable Nagle's algorithm on @a sock. This is what we do by default for * all TCP sockets in MHD, unless the platform does not support the MSG_MORE * or MSG_CORK or MSG_NOPUSH options. * * @param sock socket to manipulate * @param on value to use * @return 0 on success */ int MHD_socket_set_nodelay_ (MHD_socket sock, bool on); /** * Change socket options to be non-inheritable. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise * @warning Does not set socket error on W32. */ int MHD_socket_noninheritable_ (MHD_socket sock); #if defined(SOL_SOCKET) && defined(SO_NOSIGPIPE) static const int _MHD_socket_int_one = 1; /** * Change socket options to no signal on remote disconnect. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ #define MHD_socket_nosignal_(sock) \ (! setsockopt ((sock),SOL_SOCKET,SO_NOSIGPIPE,&_MHD_socket_int_one, \ sizeof(_MHD_socket_int_one))) #endif /* SOL_SOCKET && SO_NOSIGPIPE */ #if defined(MHD_socket_nosignal_) || defined(MSG_NOSIGNAL) /** * Indicate that SIGPIPE can be suppressed by MHD for normal send() by flags * or socket options. * If this macro is undefined, MHD cannot suppress SIGPIPE for socket functions * so sendfile() or writev() calls are avoided in application threads. */ #define MHD_SEND_SPIPE_SUPPRESS_POSSIBLE 1 #endif /* MHD_WINSOCK_SOCKETS || MHD_socket_nosignal_ || MSG_NOSIGNAL */ #if ! defined(MHD_WINSOCK_SOCKETS) /** * Indicate that suppression of SIGPIPE is required. */ #define MHD_SEND_SPIPE_SUPPRESS_NEEDED 1 #endif /** * Create a listen socket, with noninheritable flag if possible. * * @param pf protocol family to use * @return created socket or MHD_INVALID_SOCKET in case of errors */ MHD_socket MHD_socket_create_listen_ (int pf); #endif /* ! MHD_SOCKETS_H */ libmicrohttpd-1.0.2/src/microhttpd/connection.h0000644000175000017500000001350314760713577016576 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection.h * @brief Methods for managing connections * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef CONNECTION_H #define CONNECTION_H #include "internal.h" /** * Error code similar to EGAIN or EINTR */ #define MHD_ERR_AGAIN_ (-3073) /** * Connection was hard-closed by remote peer. */ #define MHD_ERR_CONNRESET_ (-3074) /** * Connection is not connected anymore due to * network error or any other reason. */ #define MHD_ERR_NOTCONN_ (-3075) /** * "Not enough memory" error code */ #define MHD_ERR_NOMEM_ (-3076) /** * "Bad FD" error code */ #define MHD_ERR_BADF_ (-3077) /** * Error code similar to EINVAL */ #define MHD_ERR_INVAL_ (-3078) /** * Argument values are not supported */ #define MHD_ERR_OPNOTSUPP_ (-3079) /** * Socket is shut down for writing or no longer connected */ #define MHD_ERR_PIPE_ (-3080) /** * General TLS encryption or decryption error */ #define MHD_ERR_TLS_ (-4097) /** * Set callbacks for this connection to those for HTTP. * * @param connection connection to initialize */ void MHD_set_http_callbacks_ (struct MHD_Connection *connection); /** * Set initial internal states for the connection to start reading and * processing incoming data. * @param c the connection to process */ void MHD_connection_set_initial_state_ (struct MHD_Connection *c); /** * This function handles a particular connection when it has been * determined that there is data to be read off a socket. All * implementations (multithreaded, external polling, internal polling) * call this function to handle reads. * * @param connection connection to handle * @param socket_error set to true if socket error was detected */ void MHD_connection_handle_read (struct MHD_Connection *connection, bool socket_error); /** * This function was created to handle writes to sockets when it has * been determined that the socket can be written to. All * implementations (multithreaded, external select, internal select) * call this function * * @param connection connection to handle */ void MHD_connection_handle_write (struct MHD_Connection *connection); /** * This function was created to handle per-connection processing that * has to happen even if the socket cannot be read or written to. * All implementations (multithreaded, external select, internal select) * call this function. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection connection to handle * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_handle_idle (struct MHD_Connection *connection); /** * Mark connection as "closed". * @remark To be called from any thread. * * @param connection connection to close */ void MHD_connection_mark_closed_ (struct MHD_Connection *connection); /** * Close the given connection and give the * specified termination code to the user. * @remark To be called only from thread that * process connection's recv(), send() and response. * * @param connection connection to close * @param termination_code termination reason to give */ void MHD_connection_close_ (struct MHD_Connection *connection, enum MHD_RequestTerminationCode termination_code); #ifdef HTTPS_SUPPORT /** * Stop TLS forwarding on upgraded connection and * reflect remote disconnect state to socketpair. * @param connection the upgraded connection */ void MHD_connection_finish_forward_ (struct MHD_Connection *connection); #else /* ! HTTPS_SUPPORT */ #define MHD_connection_finish_forward_(conn) (void) conn #endif /* ! HTTPS_SUPPORT */ #ifdef EPOLL_SUPPORT /** * Perform epoll processing, possibly moving the connection back into * the epoll set if needed. * * @param connection connection to process * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_epoll_update_ (struct MHD_Connection *connection); #endif /** * Update the 'last_activity' field of the connection to the current time * and move the connection to the head of the 'normal_timeout' list if * the timeout for the connection uses the default value. * * @param connection the connection that saw some activity */ void MHD_update_last_activity_ (struct MHD_Connection *connection); /** * Allocate memory from connection's memory pool. * If memory pool doesn't have enough free memory but read or write buffer * have some unused memory, the size of the buffer will be reduced as needed. * @param connection the connection to use * @param size the size of allocated memory area * @return pointer to allocated memory region in the pool or * NULL if no memory is available */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size); #endif libmicrohttpd-1.0.2/src/microhttpd/test_daemon.c0000644000175000017500000001366414760713574016741 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2017 Christian Grothoff Copyright (C) 2014--2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_daemon.c * @brief Testcase for libmicrohttpd starts and stops * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifndef WINDOWS #include #endif static unsigned int testStartError (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, NULL, NULL); if (NULL != d) { MHD_stop_daemon (d); fprintf (stderr, "Succeeded to start without MHD_AccessHandlerCallback?\n"); return 1; } return 0; } static enum MHD_Result apc_nothing (void *cls, const struct sockaddr *addr, socklen_t addrlen) { (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */ return MHD_NO; } static enum MHD_Result apc_all (void *cls, const struct sockaddr *addr, socklen_t addrlen) { (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */ return MHD_YES; } static enum MHD_Result ahc_nothing (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return MHD_NO; } static unsigned int testStartStop (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, &apc_nothing, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } MHD_stop_daemon (d); return 0; } static unsigned int testExternalRun (int use_no_thread_safe) { struct MHD_Daemon *d; fd_set rs; MHD_socket maxfd; int i; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (use_no_thread_safe ? MHD_USE_NO_THREAD_SAFETY : 0), 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } for (i = 0; i < 15; ++i) { maxfd = 0; FD_ZERO (&rs); if (MHD_YES != MHD_get_fdset (d, &rs, &rs, &rs, &maxfd)) { MHD_stop_daemon (d); fprintf (stderr, "Failed in MHD_get_fdset().\n"); return 256; } if (MHD_NO == MHD_run (d)) { MHD_stop_daemon (d); fprintf (stderr, "Failed in MHD_run().\n"); return 8; } } MHD_stop_daemon (d); return 0; } static unsigned int testThread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD, 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u.\n", (unsigned int) 0); exit (3); } if (MHD_run (d) != MHD_NO) { fprintf (stderr, "Failed in MHD_run().\n"); return 32; } MHD_stop_daemon (d); return 0; } static unsigned int testMultithread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } if (MHD_run (d) != MHD_NO) { fprintf (stderr, "Failed in MHD_run().\n"); return 128; } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; int has_threads_support; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ has_threads_support = (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_THREADS)); errorCount += testStartError (); if (has_threads_support) errorCount += testStartStop (); if (has_threads_support) errorCount += testExternalRun (0); errorCount += testExternalRun (! 0); if (has_threads_support) { errorCount += testThread (); errorCount += testMultithread (); } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); return 0 != errorCount; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/mhd_str_types.h0000644000175000017500000000321214760713577017317 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str_types.h * @brief Header for string manipulating helpers types * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_STR_TYPES_H #define MHD_STR_TYPES_H 1 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Constant string with length */ struct _MHD_cstr_w_len { const char *const str; const size_t len; }; /** * String with length */ struct _MHD_str_w_len { const char *str; size_t len; }; /** * Modifiable string with length */ struct _MHD_mstr_w_len { char *str; size_t len; }; /** * Static string initialiser for struct _MHD_str_w_len */ #define _MHD_S_STR_W_LEN(str) { str, MHD_STATICSTR_LEN_(str) } #endif /* MHD_STR_TYPES_H */ libmicrohttpd-1.0.2/src/microhttpd/Makefile.in0000644000175000017500000067122515035216310016321 00000000000000# Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @W32_SHARED_LIB_EXP_TRUE@am__append_1 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def @W32_SHARED_LIB_EXP_TRUE@am__append_2 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@am__append_3 = $(lt_cv_objdir)/libmicrohttpd.exp @W32_STATIC_LIB_TRUE@am__append_4 = $(lt_cv_objdir)/libmicrohttpd-static.lib @W32_STATIC_LIB_TRUE@am__append_5 = $(lt_cv_objdir)/libmicrohttpd-static.lib @USE_POSIX_THREADS_TRUE@am__append_6 = \ @USE_POSIX_THREADS_TRUE@ mhd_threads.c mhd_threads.h \ @USE_POSIX_THREADS_TRUE@ mhd_locks.h @USE_W32_THREADS_TRUE@am__append_7 = \ @USE_W32_THREADS_TRUE@ mhd_threads.c mhd_threads.h \ @USE_W32_THREADS_TRUE@ mhd_locks.h @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@am__append_8 = \ @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@ sysfdsetsize.c @USE_COVERAGE_TRUE@am__append_9 = --coverage @MHD_USE_SYS_TSEARCH_FALSE@am__append_10 = \ @MHD_USE_SYS_TSEARCH_FALSE@ tsearch.c tsearch.h @HAVE_POSTPROCESSOR_TRUE@am__append_11 = \ @HAVE_POSTPROCESSOR_TRUE@ postprocessor.c postprocessor.h @HAVE_ANYAUTH_TRUE@am__append_12 = \ @HAVE_ANYAUTH_TRUE@ gen_auth.c gen_auth.h @ENABLE_DAUTH_TRUE@am__append_13 = \ @ENABLE_DAUTH_TRUE@ digestauth.c digestauth.h \ @ENABLE_DAUTH_TRUE@ mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@am__append_14 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@ mhd_md5_wrap.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@am__append_15 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@ md5.c md5.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@am__append_16 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@ md5_ext.c md5_ext.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@am__append_17 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@ mhd_sha256_wrap.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@am__append_18 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@ sha256.c sha256.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@am__append_19 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@ sha256_ext.c sha256_ext.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@am__append_20 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@ sha512_256.c sha512_256.h @ENABLE_BAUTH_TRUE@am__append_21 = \ @ENABLE_BAUTH_TRUE@ basicauth.c basicauth.h @ENABLE_HTTPS_TRUE@am__append_22 = \ @ENABLE_HTTPS_TRUE@ connection_https.c connection_https.h check_PROGRAMS = test_str_compare$(EXEEXT) test_str_to_value$(EXEEXT) \ test_str_from_value$(EXEEXT) test_str_token$(EXEEXT) \ test_str_token_remove$(EXEEXT) test_str_tokens_remove$(EXEEXT) \ test_str_pct$(EXEEXT) test_str_bin_hex$(EXEEXT) \ test_http_reasons$(EXEEXT) test_sha1$(EXEEXT) \ test_start_stop$(EXEEXT) test_daemon$(EXEEXT) \ test_response_entries$(EXEEXT) test_postprocessor_md$(EXEEXT) \ test_client_put_shutdown$(EXEEXT) \ test_client_put_close$(EXEEXT) \ test_client_put_hard_close$(EXEEXT) \ test_client_put_steps_shutdown$(EXEEXT) \ test_client_put_steps_close$(EXEEXT) \ test_client_put_steps_hard_close$(EXEEXT) \ test_client_put_chunked_shutdown$(EXEEXT) \ test_client_put_chunked_close$(EXEEXT) \ test_client_put_chunked_hard_close$(EXEEXT) \ test_client_put_chunked_steps_shutdown$(EXEEXT) \ test_client_put_chunked_steps_close$(EXEEXT) \ test_client_put_chunked_steps_hard_close$(EXEEXT) \ test_options$(EXEEXT) test_mhd_version$(EXEEXT) \ test_set_panic$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_2) \ $(am__EXEEXT_3) $(am__EXEEXT_4) $(am__EXEEXT_5) \ $(am__EXEEXT_6) $(am__EXEEXT_7) $(am__EXEEXT_8) \ $(am__EXEEXT_9) $(am__EXEEXT_10) $(am__EXEEXT_11) \ $(am__EXEEXT_12) @ENABLE_MD5_TRUE@am__append_23 = \ @ENABLE_MD5_TRUE@ test_md5 @ENABLE_SHA256_TRUE@am__append_24 = \ @ENABLE_SHA256_TRUE@ test_sha256 @ENABLE_SHA512_256_TRUE@am__append_25 = \ @ENABLE_SHA512_256_TRUE@ test_sha512_256 @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@am__append_26 = test_upgrade test_upgrade_large test_upgrade_vlarge @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@am__append_27 = test_upgrade_tls test_upgrade_large_tls test_upgrade_vlarge_tls @HAVE_POSTPROCESSOR_TRUE@am__append_28 = \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_large \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_amp # Do not test trigger of select by shutdown of listen socket # on Cygwin as this ability is deliberately ignored on Cygwin # to improve compatibility with core OS. @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_29 = \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_select \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@am__append_30 = \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_select_ignore \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll_ignore @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@am__append_31 = \ @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@ test_auth_parse @ENABLE_DAUTH_TRUE@am__append_32 = \ @ENABLE_DAUTH_TRUE@ test_str_quote \ @ENABLE_DAUTH_TRUE@ test_dauth_userdigest \ @ENABLE_DAUTH_TRUE@ test_dauth_userhash @ENABLE_BAUTH_TRUE@am__append_33 = \ @ENABLE_BAUTH_TRUE@ test_str_base64 @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@am__append_34 = \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_hard_close_stress_os \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_steps_hard_close_stress_os \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_chunked_steps_hard_close_stress_os @USE_POSIX_THREADS_TRUE@am__append_35 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_36 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_37 = \ @USE_POSIX_THREADS_TRUE@ $(AM_CFLAGS) $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_38 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_39 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_40 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_41 = \ @USE_POSIX_THREADS_TRUE@ $(AM_CFLAGS) $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_42 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @ENABLE_MD5_EXT_FALSE@am__append_43 = \ @ENABLE_MD5_EXT_FALSE@ md5.c md5.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_MD5_EXT_TRUE@am__append_44 = \ @ENABLE_MD5_EXT_TRUE@ md5_ext.c md5_ext.h @ENABLE_SHA256_EXT_FALSE@am__append_45 = \ @ENABLE_SHA256_EXT_FALSE@ sha256.c sha256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_SHA256_EXT_TRUE@am__append_46 = \ @ENABLE_SHA256_EXT_TRUE@ sha256_ext.c sha256_ext.h subdir = src/microhttpd ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = microhttpd_dll_res.rc CONFIG_CLEAN_VPATH_FILES = @ENABLE_MD5_TRUE@am__EXEEXT_1 = test_md5$(EXEEXT) @ENABLE_SHA256_TRUE@am__EXEEXT_2 = test_sha256$(EXEEXT) @ENABLE_SHA512_256_TRUE@am__EXEEXT_3 = test_sha512_256$(EXEEXT) @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@am__EXEEXT_4 = test_upgrade$(EXEEXT) \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@ test_upgrade_large$(EXEEXT) \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@ test_upgrade_vlarge$(EXEEXT) @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@am__EXEEXT_5 = test_upgrade_tls$(EXEEXT) \ @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@ test_upgrade_large_tls$(EXEEXT) \ @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@ test_upgrade_vlarge_tls$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_6 = test_postprocessor$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_large$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_amp$(EXEEXT) @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_7 = test_shutdown_select$(EXEEXT) \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll$(EXEEXT) @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_8 = test_shutdown_select_ignore$(EXEEXT) \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll_ignore$(EXEEXT) @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@am__EXEEXT_9 = test_auth_parse$(EXEEXT) @ENABLE_DAUTH_TRUE@am__EXEEXT_10 = test_str_quote$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_dauth_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_dauth_userhash$(EXEEXT) @ENABLE_BAUTH_TRUE@am__EXEEXT_11 = test_str_base64$(EXEEXT) @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@am__EXEEXT_12 = test_client_put_hard_close_stress_os$(EXEEXT) \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_steps_hard_close_stress_os$(EXEEXT) \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = @HAVE_W32_TRUE@am__DEPENDENCIES_2 = \ @HAVE_W32_TRUE@ libmicrohttpd_la-microhttpd_dll_res.lo libmicrohttpd_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) am__libmicrohttpd_la_SOURCES_DIST = connection.c connection.h \ reason_phrase.c daemon.c internal.c internal.h memorypool.c \ memorypool.h mhd_mono_clock.c mhd_mono_clock.h mhd_limits.h \ sysfdsetsize.h mhd_str.c mhd_str.h mhd_str_types.h mhd_send.h \ mhd_send.c mhd_assert.h mhd_sockets.c mhd_sockets.h mhd_itc.c \ mhd_itc.h mhd_itc_types.h mhd_compat.c mhd_compat.h \ mhd_panic.c mhd_panic.h response.c response.h mhd_threads.c \ mhd_threads.h mhd_locks.h sysfdsetsize.c tsearch.c tsearch.h \ postprocessor.c postprocessor.h gen_auth.c gen_auth.h \ digestauth.c digestauth.h mhd_bithelpers.h mhd_byteorder.h \ mhd_align.h mhd_md5_wrap.h md5.c md5.h md5_ext.c md5_ext.h \ mhd_sha256_wrap.h sha256.c sha256.h sha256_ext.c sha256_ext.h \ sha512_256.c sha512_256.h basicauth.c basicauth.h \ connection_https.c connection_https.h @USE_POSIX_THREADS_TRUE@am__objects_1 = \ @USE_POSIX_THREADS_TRUE@ libmicrohttpd_la-mhd_threads.lo @USE_W32_THREADS_TRUE@am__objects_2 = libmicrohttpd_la-mhd_threads.lo @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@am__objects_3 = libmicrohttpd_la-sysfdsetsize.lo @MHD_USE_SYS_TSEARCH_FALSE@am__objects_4 = \ @MHD_USE_SYS_TSEARCH_FALSE@ libmicrohttpd_la-tsearch.lo @HAVE_POSTPROCESSOR_TRUE@am__objects_5 = \ @HAVE_POSTPROCESSOR_TRUE@ libmicrohttpd_la-postprocessor.lo @HAVE_ANYAUTH_TRUE@am__objects_6 = libmicrohttpd_la-gen_auth.lo @ENABLE_DAUTH_TRUE@am__objects_7 = libmicrohttpd_la-digestauth.lo am__objects_8 = @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@am__objects_9 = libmicrohttpd_la-md5.lo @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@am__objects_10 = libmicrohttpd_la-md5_ext.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@am__objects_11 = libmicrohttpd_la-sha256.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@am__objects_12 = libmicrohttpd_la-sha256_ext.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@am__objects_13 = libmicrohttpd_la-sha512_256.lo @ENABLE_BAUTH_TRUE@am__objects_14 = libmicrohttpd_la-basicauth.lo @ENABLE_HTTPS_TRUE@am__objects_15 = \ @ENABLE_HTTPS_TRUE@ libmicrohttpd_la-connection_https.lo am_libmicrohttpd_la_OBJECTS = libmicrohttpd_la-connection.lo \ libmicrohttpd_la-reason_phrase.lo libmicrohttpd_la-daemon.lo \ libmicrohttpd_la-internal.lo libmicrohttpd_la-memorypool.lo \ libmicrohttpd_la-mhd_mono_clock.lo libmicrohttpd_la-mhd_str.lo \ libmicrohttpd_la-mhd_send.lo libmicrohttpd_la-mhd_sockets.lo \ libmicrohttpd_la-mhd_itc.lo libmicrohttpd_la-mhd_compat.lo \ libmicrohttpd_la-mhd_panic.lo libmicrohttpd_la-response.lo \ $(am__objects_1) $(am__objects_2) $(am__objects_3) \ $(am__objects_4) $(am__objects_5) $(am__objects_6) \ $(am__objects_7) $(am__objects_8) $(am__objects_9) \ $(am__objects_10) $(am__objects_8) $(am__objects_11) \ $(am__objects_12) $(am__objects_13) $(am__objects_14) \ $(am__objects_15) libmicrohttpd_la_OBJECTS = $(am_libmicrohttpd_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libmicrohttpd_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(libmicrohttpd_la_CFLAGS) $(CFLAGS) \ $(libmicrohttpd_la_LDFLAGS) $(LDFLAGS) -o $@ am_test_auth_parse_OBJECTS = \ test_auth_parse-test_auth_parse.$(OBJEXT) \ test_auth_parse-gen_auth.$(OBJEXT) \ test_auth_parse-mhd_str.$(OBJEXT) test_auth_parse_OBJECTS = $(am_test_auth_parse_OBJECTS) test_auth_parse_LDADD = $(LDADD) am_test_client_put_chunked_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_close_OBJECTS = \ $(am_test_client_put_chunked_close_OBJECTS) test_client_put_chunked_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_hard_close_OBJECTS = \ $(am_test_client_put_chunked_hard_close_OBJECTS) test_client_put_chunked_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_shutdown_OBJECTS = \ $(am_test_client_put_chunked_shutdown_OBJECTS) test_client_put_chunked_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_steps_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_close_OBJECTS = \ $(am_test_client_put_chunked_steps_close_OBJECTS) test_client_put_chunked_steps_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_steps_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_hard_close_OBJECTS = \ $(am_test_client_put_chunked_steps_hard_close_OBJECTS) test_client_put_chunked_steps_hard_close_DEPENDENCIES = \ libmicrohttpd.la am__objects_16 = test_client_put_stop.$(OBJEXT) am_test_client_put_chunked_steps_hard_close_stress_os_OBJECTS = \ $(am__objects_16) test_client_put_chunked_steps_hard_close_stress_os_OBJECTS = $(am_test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_chunked_steps_hard_close_LDADD) am_test_client_put_chunked_steps_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_shutdown_OBJECTS = \ $(am_test_client_put_chunked_steps_shutdown_OBJECTS) test_client_put_chunked_steps_shutdown_DEPENDENCIES = \ libmicrohttpd.la am_test_client_put_close_OBJECTS = test_client_put_stop.$(OBJEXT) test_client_put_close_OBJECTS = $(am_test_client_put_close_OBJECTS) test_client_put_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_hard_close_OBJECTS = \ $(am_test_client_put_hard_close_OBJECTS) test_client_put_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_hard_close_stress_os_OBJECTS = $(am__objects_16) test_client_put_hard_close_stress_os_OBJECTS = \ $(am_test_client_put_hard_close_stress_os_OBJECTS) test_client_put_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_hard_close_LDADD) am_test_client_put_shutdown_OBJECTS = test_client_put_stop.$(OBJEXT) test_client_put_shutdown_OBJECTS = \ $(am_test_client_put_shutdown_OBJECTS) test_client_put_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_close_OBJECTS = \ $(am_test_client_put_steps_close_OBJECTS) test_client_put_steps_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_hard_close_OBJECTS = \ $(am_test_client_put_steps_hard_close_OBJECTS) test_client_put_steps_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_hard_close_stress_os_OBJECTS = \ $(am__objects_16) test_client_put_steps_hard_close_stress_os_OBJECTS = \ $(am_test_client_put_steps_hard_close_stress_os_OBJECTS) test_client_put_steps_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_steps_hard_close_LDADD) am_test_client_put_steps_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_shutdown_OBJECTS = \ $(am_test_client_put_steps_shutdown_OBJECTS) test_client_put_steps_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_daemon_OBJECTS = test_daemon.$(OBJEXT) test_daemon_OBJECTS = $(am_test_daemon_OBJECTS) test_daemon_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_dauth_userdigest_OBJECTS = test_dauth_userdigest.$(OBJEXT) test_dauth_userdigest_OBJECTS = $(am_test_dauth_userdigest_OBJECTS) test_dauth_userdigest_DEPENDENCIES = libmicrohttpd.la am_test_dauth_userhash_OBJECTS = test_dauth_userhash.$(OBJEXT) test_dauth_userhash_OBJECTS = $(am_test_dauth_userhash_OBJECTS) test_dauth_userhash_DEPENDENCIES = libmicrohttpd.la am_test_http_reasons_OBJECTS = test_http_reasons.$(OBJEXT) \ reason_phrase.$(OBJEXT) mhd_str.$(OBJEXT) test_http_reasons_OBJECTS = $(am_test_http_reasons_OBJECTS) test_http_reasons_LDADD = $(LDADD) am__test_md5_SOURCES_DIST = test_md5.c test_helpers.h mhd_md5_wrap.h \ ../include/mhd_options.h md5.c md5.h mhd_bithelpers.h \ mhd_byteorder.h mhd_align.h md5_ext.c md5_ext.h @ENABLE_MD5_EXT_FALSE@am__objects_17 = test_md5-md5.$(OBJEXT) @ENABLE_MD5_EXT_TRUE@am__objects_18 = test_md5-md5_ext.$(OBJEXT) am_test_md5_OBJECTS = test_md5-test_md5.$(OBJEXT) $(am__objects_17) \ $(am__objects_18) test_md5_OBJECTS = $(am_test_md5_OBJECTS) @ENABLE_MD5_EXT_TRUE@test_md5_DEPENDENCIES = $(am__DEPENDENCIES_1) test_md5_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_md5_CFLAGS) \ $(CFLAGS) $(test_md5_LDFLAGS) $(LDFLAGS) -o $@ am_test_mhd_version_OBJECTS = test_mhd_version.$(OBJEXT) test_mhd_version_OBJECTS = $(am_test_mhd_version_OBJECTS) test_mhd_version_DEPENDENCIES = libmicrohttpd.la am_test_options_OBJECTS = test_options.$(OBJEXT) test_options_OBJECTS = $(am_test_options_OBJECTS) test_options_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_postprocessor_OBJECTS = \ test_postprocessor-test_postprocessor.$(OBJEXT) test_postprocessor_OBJECTS = $(am_test_postprocessor_OBJECTS) test_postprocessor_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_amp_OBJECTS = \ test_postprocessor_amp-test_postprocessor_amp.$(OBJEXT) test_postprocessor_amp_OBJECTS = $(am_test_postprocessor_amp_OBJECTS) test_postprocessor_amp_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_amp_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_amp_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_large_OBJECTS = \ test_postprocessor_large-test_postprocessor_large.$(OBJEXT) test_postprocessor_large_OBJECTS = \ $(am_test_postprocessor_large_OBJECTS) test_postprocessor_large_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_large_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_large_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_md_OBJECTS = \ test_postprocessor_md-test_postprocessor_md.$(OBJEXT) \ test_postprocessor_md-postprocessor.$(OBJEXT) \ test_postprocessor_md-internal.$(OBJEXT) \ test_postprocessor_md-mhd_str.$(OBJEXT) \ test_postprocessor_md-mhd_panic.$(OBJEXT) test_postprocessor_md_OBJECTS = $(am_test_postprocessor_md_OBJECTS) test_postprocessor_md_LDADD = $(LDADD) am_test_response_entries_OBJECTS = test_response_entries.$(OBJEXT) test_response_entries_OBJECTS = $(am_test_response_entries_OBJECTS) test_response_entries_DEPENDENCIES = libmicrohttpd.la am_test_set_panic_OBJECTS = test_set_panic.$(OBJEXT) test_set_panic_OBJECTS = $(am_test_set_panic_OBJECTS) test_set_panic_DEPENDENCIES = libmicrohttpd.la am_test_sha1_OBJECTS = test_sha1.$(OBJEXT) sha1.$(OBJEXT) test_sha1_OBJECTS = $(am_test_sha1_OBJECTS) test_sha1_LDADD = $(LDADD) am__test_sha256_SOURCES_DIST = test_sha256.c test_helpers.h \ mhd_sha256_wrap.h ../include/mhd_options.h sha256.c sha256.h \ mhd_bithelpers.h mhd_byteorder.h mhd_align.h sha256_ext.c \ sha256_ext.h @ENABLE_SHA256_EXT_FALSE@am__objects_19 = \ @ENABLE_SHA256_EXT_FALSE@ test_sha256-sha256.$(OBJEXT) @ENABLE_SHA256_EXT_TRUE@am__objects_20 = \ @ENABLE_SHA256_EXT_TRUE@ test_sha256-sha256_ext.$(OBJEXT) am_test_sha256_OBJECTS = test_sha256-test_sha256.$(OBJEXT) \ $(am__objects_19) $(am__objects_20) test_sha256_OBJECTS = $(am_test_sha256_OBJECTS) @ENABLE_SHA256_EXT_TRUE@test_sha256_DEPENDENCIES = \ @ENABLE_SHA256_EXT_TRUE@ $(am__DEPENDENCIES_1) test_sha256_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_sha256_CFLAGS) \ $(CFLAGS) $(test_sha256_LDFLAGS) $(LDFLAGS) -o $@ am_test_sha512_256_OBJECTS = test_sha512_256.$(OBJEXT) \ sha512_256.$(OBJEXT) test_sha512_256_OBJECTS = $(am_test_sha512_256_OBJECTS) test_sha512_256_LDADD = $(LDADD) am_test_shutdown_poll_OBJECTS = \ test_shutdown_poll-test_shutdown_select.$(OBJEXT) test_shutdown_poll_OBJECTS = $(am_test_shutdown_poll_OBJECTS) @USE_POSIX_THREADS_TRUE@am__DEPENDENCIES_3 = $(am__DEPENDENCIES_1) test_shutdown_poll_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_poll_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_poll_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_poll_ignore_OBJECTS = \ test_shutdown_poll_ignore-test_shutdown_select.$(OBJEXT) test_shutdown_poll_ignore_OBJECTS = \ $(am_test_shutdown_poll_ignore_OBJECTS) test_shutdown_poll_ignore_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_poll_ignore_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_select_OBJECTS = \ test_shutdown_select-test_shutdown_select.$(OBJEXT) test_shutdown_select_OBJECTS = $(am_test_shutdown_select_OBJECTS) test_shutdown_select_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_select_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_select_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_select_ignore_OBJECTS = \ test_shutdown_select_ignore-test_shutdown_select.$(OBJEXT) test_shutdown_select_ignore_OBJECTS = \ $(am_test_shutdown_select_ignore_OBJECTS) test_shutdown_select_ignore_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_select_ignore_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_start_stop_OBJECTS = test_start_stop.$(OBJEXT) test_start_stop_OBJECTS = $(am_test_start_stop_OBJECTS) test_start_stop_DEPENDENCIES = libmicrohttpd.la am_test_str_base64_OBJECTS = test_str_base64.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_base64_OBJECTS = $(am_test_str_base64_OBJECTS) test_str_base64_LDADD = $(LDADD) am_test_str_bin_hex_OBJECTS = test_str_bin_hex.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_bin_hex_OBJECTS = $(am_test_str_bin_hex_OBJECTS) test_str_bin_hex_LDADD = $(LDADD) am_test_str_compare_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_compare_OBJECTS = $(am_test_str_compare_OBJECTS) test_str_compare_LDADD = $(LDADD) am_test_str_from_value_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_from_value_OBJECTS = $(am_test_str_from_value_OBJECTS) test_str_from_value_LDADD = $(LDADD) am_test_str_pct_OBJECTS = test_str_pct.$(OBJEXT) mhd_str.$(OBJEXT) test_str_pct_OBJECTS = $(am_test_str_pct_OBJECTS) test_str_pct_LDADD = $(LDADD) am_test_str_quote_OBJECTS = test_str_quote.$(OBJEXT) mhd_str.$(OBJEXT) test_str_quote_OBJECTS = $(am_test_str_quote_OBJECTS) test_str_quote_LDADD = $(LDADD) am_test_str_to_value_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_to_value_OBJECTS = $(am_test_str_to_value_OBJECTS) test_str_to_value_LDADD = $(LDADD) am_test_str_token_OBJECTS = test_str_token.$(OBJEXT) mhd_str.$(OBJEXT) test_str_token_OBJECTS = $(am_test_str_token_OBJECTS) test_str_token_LDADD = $(LDADD) am_test_str_token_remove_OBJECTS = test_str_token_remove.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_token_remove_OBJECTS = $(am_test_str_token_remove_OBJECTS) test_str_token_remove_LDADD = $(LDADD) am_test_str_tokens_remove_OBJECTS = test_str_tokens_remove.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_tokens_remove_OBJECTS = $(am_test_str_tokens_remove_OBJECTS) test_str_tokens_remove_LDADD = $(LDADD) am_test_upgrade_OBJECTS = test_upgrade-test_upgrade.$(OBJEXT) test_upgrade_OBJECTS = $(am_test_upgrade_OBJECTS) test_upgrade_DEPENDENCIES = $(builddir)/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_upgrade_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_upgrade_CFLAGS) \ $(CFLAGS) $(test_upgrade_LDFLAGS) $(LDFLAGS) -o $@ am__objects_21 = test_upgrade_large-test_upgrade.$(OBJEXT) am_test_upgrade_large_OBJECTS = $(am__objects_21) test_upgrade_large_OBJECTS = $(am_test_upgrade_large_OBJECTS) am__DEPENDENCIES_4 = $(builddir)/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_upgrade_large_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_large_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_large_CFLAGS) $(CFLAGS) \ $(test_upgrade_large_LDFLAGS) $(LDFLAGS) -o $@ am__objects_22 = test_upgrade_large_tls-test_upgrade.$(OBJEXT) am_test_upgrade_large_tls_OBJECTS = $(am__objects_22) test_upgrade_large_tls_OBJECTS = $(am_test_upgrade_large_tls_OBJECTS) test_upgrade_large_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_large_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_large_tls_LDFLAGS) $(LDFLAGS) -o $@ am__objects_23 = test_upgrade_tls-test_upgrade.$(OBJEXT) am_test_upgrade_tls_OBJECTS = $(am__objects_23) test_upgrade_tls_OBJECTS = $(am_test_upgrade_tls_OBJECTS) test_upgrade_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_tls_LDFLAGS) $(LDFLAGS) -o $@ am__objects_24 = test_upgrade_vlarge-test_upgrade.$(OBJEXT) am_test_upgrade_vlarge_OBJECTS = $(am__objects_24) test_upgrade_vlarge_OBJECTS = $(am_test_upgrade_vlarge_OBJECTS) test_upgrade_vlarge_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_vlarge_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) \ $(test_upgrade_vlarge_LDFLAGS) $(LDFLAGS) -o $@ am__objects_25 = test_upgrade_vlarge_tls-test_upgrade.$(OBJEXT) am_test_upgrade_vlarge_tls_OBJECTS = $(am__objects_25) test_upgrade_vlarge_tls_OBJECTS = \ $(am_test_upgrade_vlarge_tls_OBJECTS) test_upgrade_vlarge_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_vlarge_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_vlarge_tls_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-connection.Plo \ ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo \ ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo \ ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-internal.Plo \ ./$(DEPDIR)/libmicrohttpd_la-md5.Plo \ ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo \ ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo \ ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo \ ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo \ ./$(DEPDIR)/libmicrohttpd_la-response.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo \ ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo \ ./$(DEPDIR)/mhd_str.Po ./$(DEPDIR)/reason_phrase.Po \ ./$(DEPDIR)/sha1.Po ./$(DEPDIR)/sha512_256.Po \ ./$(DEPDIR)/test_auth_parse-gen_auth.Po \ ./$(DEPDIR)/test_auth_parse-mhd_str.Po \ ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po \ ./$(DEPDIR)/test_client_put_stop.Po ./$(DEPDIR)/test_daemon.Po \ ./$(DEPDIR)/test_dauth_userdigest.Po \ ./$(DEPDIR)/test_dauth_userhash.Po \ ./$(DEPDIR)/test_http_reasons.Po ./$(DEPDIR)/test_md5-md5.Po \ ./$(DEPDIR)/test_md5-md5_ext.Po \ ./$(DEPDIR)/test_md5-test_md5.Po \ ./$(DEPDIR)/test_mhd_version.Po ./$(DEPDIR)/test_options.Po \ ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po \ ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po \ ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po \ ./$(DEPDIR)/test_postprocessor_md-internal.Po \ ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po \ ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po \ ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po \ ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po \ ./$(DEPDIR)/test_response_entries.Po \ ./$(DEPDIR)/test_set_panic.Po ./$(DEPDIR)/test_sha1.Po \ ./$(DEPDIR)/test_sha256-sha256.Po \ ./$(DEPDIR)/test_sha256-sha256_ext.Po \ ./$(DEPDIR)/test_sha256-test_sha256.Po \ ./$(DEPDIR)/test_sha512_256.Po \ ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po \ ./$(DEPDIR)/test_start_stop.Po ./$(DEPDIR)/test_str.Po \ ./$(DEPDIR)/test_str_base64.Po ./$(DEPDIR)/test_str_bin_hex.Po \ ./$(DEPDIR)/test_str_pct.Po ./$(DEPDIR)/test_str_quote.Po \ ./$(DEPDIR)/test_str_token.Po \ ./$(DEPDIR)/test_str_token_remove.Po \ ./$(DEPDIR)/test_str_tokens_remove.Po \ ./$(DEPDIR)/test_upgrade-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libmicrohttpd_la_SOURCES) $(test_auth_parse_SOURCES) \ $(test_client_put_chunked_close_SOURCES) \ $(test_client_put_chunked_hard_close_SOURCES) \ $(test_client_put_chunked_shutdown_SOURCES) \ $(test_client_put_chunked_steps_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_chunked_steps_shutdown_SOURCES) \ $(test_client_put_close_SOURCES) \ $(test_client_put_hard_close_SOURCES) \ $(test_client_put_hard_close_stress_os_SOURCES) \ $(test_client_put_shutdown_SOURCES) \ $(test_client_put_steps_close_SOURCES) \ $(test_client_put_steps_hard_close_SOURCES) \ $(test_client_put_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_steps_shutdown_SOURCES) \ $(test_daemon_SOURCES) $(test_dauth_userdigest_SOURCES) \ $(test_dauth_userhash_SOURCES) $(test_http_reasons_SOURCES) \ $(test_md5_SOURCES) $(test_mhd_version_SOURCES) \ $(test_options_SOURCES) $(test_postprocessor_SOURCES) \ $(test_postprocessor_amp_SOURCES) \ $(test_postprocessor_large_SOURCES) \ $(test_postprocessor_md_SOURCES) \ $(test_response_entries_SOURCES) $(test_set_panic_SOURCES) \ $(test_sha1_SOURCES) $(test_sha256_SOURCES) \ $(test_sha512_256_SOURCES) $(test_shutdown_poll_SOURCES) \ $(test_shutdown_poll_ignore_SOURCES) \ $(test_shutdown_select_SOURCES) \ $(test_shutdown_select_ignore_SOURCES) \ $(test_start_stop_SOURCES) $(test_str_base64_SOURCES) \ $(test_str_bin_hex_SOURCES) $(test_str_compare_SOURCES) \ $(test_str_from_value_SOURCES) $(test_str_pct_SOURCES) \ $(test_str_quote_SOURCES) $(test_str_to_value_SOURCES) \ $(test_str_token_SOURCES) $(test_str_token_remove_SOURCES) \ $(test_str_tokens_remove_SOURCES) $(test_upgrade_SOURCES) \ $(test_upgrade_large_SOURCES) \ $(test_upgrade_large_tls_SOURCES) $(test_upgrade_tls_SOURCES) \ $(test_upgrade_vlarge_SOURCES) \ $(test_upgrade_vlarge_tls_SOURCES) DIST_SOURCES = $(am__libmicrohttpd_la_SOURCES_DIST) \ $(test_auth_parse_SOURCES) \ $(test_client_put_chunked_close_SOURCES) \ $(test_client_put_chunked_hard_close_SOURCES) \ $(test_client_put_chunked_shutdown_SOURCES) \ $(test_client_put_chunked_steps_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_chunked_steps_shutdown_SOURCES) \ $(test_client_put_close_SOURCES) \ $(test_client_put_hard_close_SOURCES) \ $(test_client_put_hard_close_stress_os_SOURCES) \ $(test_client_put_shutdown_SOURCES) \ $(test_client_put_steps_close_SOURCES) \ $(test_client_put_steps_hard_close_SOURCES) \ $(test_client_put_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_steps_shutdown_SOURCES) \ $(test_daemon_SOURCES) $(test_dauth_userdigest_SOURCES) \ $(test_dauth_userhash_SOURCES) $(test_http_reasons_SOURCES) \ $(am__test_md5_SOURCES_DIST) $(test_mhd_version_SOURCES) \ $(test_options_SOURCES) $(test_postprocessor_SOURCES) \ $(test_postprocessor_amp_SOURCES) \ $(test_postprocessor_large_SOURCES) \ $(test_postprocessor_md_SOURCES) \ $(test_response_entries_SOURCES) $(test_set_panic_SOURCES) \ $(test_sha1_SOURCES) $(am__test_sha256_SOURCES_DIST) \ $(test_sha512_256_SOURCES) $(test_shutdown_poll_SOURCES) \ $(test_shutdown_poll_ignore_SOURCES) \ $(test_shutdown_select_SOURCES) \ $(test_shutdown_select_ignore_SOURCES) \ $(test_start_stop_SOURCES) $(test_str_base64_SOURCES) \ $(test_str_bin_hex_SOURCES) $(test_str_compare_SOURCES) \ $(test_str_from_value_SOURCES) $(test_str_pct_SOURCES) \ $(test_str_quote_SOURCES) $(test_str_to_value_SOURCES) \ $(test_str_token_SOURCES) $(test_str_token_remove_SOURCES) \ $(test_str_tokens_remove_SOURCES) $(test_upgrade_SOURCES) \ $(test_upgrade_large_SOURCES) \ $(test_upgrade_large_tls_SOURCES) $(test_upgrade_tls_SOURCES) \ $(test_upgrade_vlarge_SOURCES) \ $(test_upgrade_vlarge_tls_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(noinst_DATA) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(srcdir)/microhttpd_dll_res.rc.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) $(HIDDEN_VISIBILITY_CFLAGS) $(am__append_9) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) lib_LTLIBRARIES = \ libmicrohttpd.la noinst_DATA = $(am__append_1) $(am__append_3) $(am__append_4) MOSTLYCLEANFILES = $(am__append_2) $(am__append_5) AM_V_LIB = $(am__v_LIB_@AM_V@) am__v_LIB_ = $(am__v_LIB_@AM_DEFAULT_V@) am__v_LIB_0 = @echo " LIB " $@; am__v_LIB_1 = @W32_SHARED_LIB_EXP_TRUE@AM_V_DLLTOOL = $(am__v_DLLTOOL_@AM_V@) @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_ = $(am__v_DLLTOOL_@AM_DEFAULT_V@) @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_0 = @echo " DLLTOOL " $@; @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_1 = @W32_SHARED_LIB_EXP_FALSE@W32_MHD_LIB_LDFLAGS = @W32_SHARED_LIB_EXP_TRUE@W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc libmicrohttpd_la_SOURCES = connection.c connection.h reason_phrase.c \ daemon.c internal.c internal.h memorypool.c memorypool.h \ mhd_mono_clock.c mhd_mono_clock.h mhd_limits.h sysfdsetsize.h \ mhd_str.c mhd_str.h mhd_str_types.h mhd_send.h mhd_send.c \ mhd_assert.h mhd_sockets.c mhd_sockets.h mhd_itc.c mhd_itc.h \ mhd_itc_types.h mhd_compat.c mhd_compat.h mhd_panic.c \ mhd_panic.h response.c response.h $(am__append_6) \ $(am__append_7) $(am__append_8) $(am__append_10) \ $(am__append_11) $(am__append_12) $(am__append_13) \ $(am__append_14) $(am__append_15) $(am__append_16) \ $(am__append_17) $(am__append_18) $(am__append_19) \ $(am__append_20) $(am__append_21) $(am__append_22) libmicrohttpd_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS) libmicrohttpd_la_LDFLAGS = \ $(AM_LDFLAGS) $(MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -export-dynamic -no-undefined \ -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@ libmicrohttpd_la_LIBADD = $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS) \ $(MHD_DLL_RES_LO) AM_V_RC = $(am__v_RC_@AM_V@) am__v_RC_ = $(am__v_RC_@AM_DEFAULT_V@) am__v_RC_0 = @echo " RC " $@; am__v_RC_1 = @HAVE_W32_FALSE@MHD_DLL_RES_LO = @HAVE_W32_TRUE@MHD_DLL_RES_LO = libmicrohttpd_la-microhttpd_dll_res.lo EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO) TESTS = $(check_PROGRAMS) test_start_stop_SOURCES = \ test_start_stop.c test_start_stop_LDADD = \ libmicrohttpd.la test_daemon_SOURCES = \ test_daemon.c test_daemon_LDADD = \ $(builddir)/libmicrohttpd.la test_response_entries_SOURCES = \ test_response_entries.c test_response_entries_LDADD = \ libmicrohttpd.la test_upgrade_SOURCES = \ test_upgrade.c test_helpers.h mhd_sockets.h test_upgrade_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_upgrade_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_upgrade_LDFLAGS = \ $(MHD_TLS_LIB_LDFLAGS) test_upgrade_LDADD = \ $(builddir)/libmicrohttpd.la \ $(MHD_TLS_LIBDEPS) \ $(PTHREAD_LIBS) test_upgrade_large_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_LDADD = \ $(test_upgrade_LDADD) test_upgrade_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_large_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_tls_LDADD = \ $(test_upgrade_LDADD) test_postprocessor_SOURCES = \ test_postprocessor.c test_postprocessor_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_amp_SOURCES = \ test_postprocessor_amp.c test_postprocessor_amp_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_amp_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_amp_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_large_SOURCES = \ test_postprocessor_large.c test_postprocessor_large_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_large_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_large_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_md_SOURCES = \ test_postprocessor_md.c postprocessor.h postprocessor.c \ internal.h internal.c mhd_str.h mhd_str.c \ mhd_panic.h mhd_panic.c test_postprocessor_md_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_shutdown_select_SOURCES = \ test_shutdown_select.c test_shutdown_select_CFLAGS = $(AM_CFLAGS) $(am__append_35) test_shutdown_select_LDADD = $(LDADD) $(am__append_36) test_shutdown_poll_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_CFLAGS = $(AM_CFLAGS) $(am__append_37) test_shutdown_poll_LDADD = $(LDADD) $(am__append_38) test_shutdown_select_ignore_SOURCES = \ test_shutdown_select.c test_shutdown_select_ignore_CFLAGS = $(AM_CFLAGS) $(am__append_39) test_shutdown_select_ignore_LDADD = $(LDADD) $(am__append_40) test_shutdown_poll_ignore_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_ignore_CFLAGS = $(AM_CFLAGS) $(am__append_41) test_shutdown_poll_ignore_LDADD = $(LDADD) $(am__append_42) test_str_compare_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_to_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_from_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_token_SOURCES = \ test_str_token.c mhd_str.c mhd_str.h test_str_token_remove_SOURCES = \ test_str_token_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_str_tokens_remove_SOURCES = \ test_str_tokens_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_http_reasons_SOURCES = \ test_http_reasons.c \ reason_phrase.c mhd_str.c mhd_str.h test_md5_SOURCES = test_md5.c test_helpers.h mhd_md5_wrap.h \ ../include/mhd_options.h $(am__append_43) $(am__append_44) @ENABLE_MD5_EXT_FALSE@test_md5_CPPFLAGS = $(AM_CPPFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_CFLAGS = $(AM_CFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_LDFLAGS = $(AM_LDFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_LDADD = $(LDADD) @ENABLE_MD5_EXT_TRUE@test_md5_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) test_sha256_SOURCES = test_sha256.c test_helpers.h mhd_sha256_wrap.h \ ../include/mhd_options.h $(am__append_45) $(am__append_46) @ENABLE_SHA256_EXT_FALSE@test_sha256_CPPFLAGS = $(AM_CPPFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_CFLAGS = $(AM_CFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_LDFLAGS = $(AM_LDFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_LDADD = $(LDADD) @ENABLE_SHA256_EXT_TRUE@test_sha256_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) test_sha512_256_SOURCES = \ test_sha512_256.c test_helpers.h \ sha512_256.c sha512_256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha1_SOURCES = \ test_sha1.c test_helpers.h \ sha1.c sha1.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_auth_parse_SOURCES = \ test_auth_parse.c gen_auth.c gen_auth.h mhd_str.h mhd_str.c mhd_assert.h test_auth_parse_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_str_quote_SOURCES = \ test_str_quote.c mhd_str.h mhd_str.c mhd_assert.h test_str_base64_SOURCES = \ test_str_base64.c mhd_str.h mhd_str.c mhd_assert.h test_str_pct_SOURCES = \ test_str_pct.c mhd_str.h mhd_str.c mhd_assert.h test_str_bin_hex_SOURCES = \ test_str_bin_hex.c mhd_str.h mhd_str.c mhd_assert.h test_options_SOURCES = \ test_options.c test_options_LDADD = \ $(builddir)/libmicrohttpd.la test_client_put_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_shutdown_LDADD = \ libmicrohttpd.la test_client_put_close_SOURCES = \ test_client_put_stop.c test_client_put_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_hard_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_stress_os_SOURCES = \ $(test_client_put_hard_close_SOURCES) test_client_put_hard_close_stress_os_LDADD = \ $(test_client_put_hard_close_LDADD) test_client_put_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_steps_hard_close_SOURCES) test_client_put_steps_hard_close_stress_os_LDADD = \ $(test_client_put_steps_hard_close_LDADD) test_client_put_chunked_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_chunked_steps_hard_close_SOURCES) test_client_put_chunked_steps_hard_close_stress_os_LDADD = \ $(test_client_put_chunked_steps_hard_close_LDADD) test_set_panic_SOURCES = \ test_set_panic.c test_set_panic_LDADD = \ libmicrohttpd.la test_dauth_userdigest_SOURCES = \ test_dauth_userdigest.c test_dauth_userdigest_LDADD = \ libmicrohttpd.la test_dauth_userhash_SOURCES = \ test_dauth_userhash.c test_dauth_userhash_LDADD = \ libmicrohttpd.la test_mhd_version_SOURCES = \ test_mhd_version.c test_mhd_version_LDADD = \ libmicrohttpd.la all: all-am .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .rc .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/microhttpd/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/microhttpd/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): microhttpd_dll_res.rc: $(top_builddir)/config.status $(srcdir)/microhttpd_dll_res.rc.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libmicrohttpd.la: $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_DEPENDENCIES) $(EXTRA_libmicrohttpd_la_DEPENDENCIES) $(AM_V_CCLD)$(libmicrohttpd_la_LINK) -rpath $(libdir) $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_LIBADD) $(LIBS) test_auth_parse$(EXEEXT): $(test_auth_parse_OBJECTS) $(test_auth_parse_DEPENDENCIES) $(EXTRA_test_auth_parse_DEPENDENCIES) @rm -f test_auth_parse$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_auth_parse_OBJECTS) $(test_auth_parse_LDADD) $(LIBS) test_client_put_chunked_close$(EXEEXT): $(test_client_put_chunked_close_OBJECTS) $(test_client_put_chunked_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_close_DEPENDENCIES) @rm -f test_client_put_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_close_OBJECTS) $(test_client_put_chunked_close_LDADD) $(LIBS) test_client_put_chunked_hard_close$(EXEEXT): $(test_client_put_chunked_hard_close_OBJECTS) $(test_client_put_chunked_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_hard_close_DEPENDENCIES) @rm -f test_client_put_chunked_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_hard_close_OBJECTS) $(test_client_put_chunked_hard_close_LDADD) $(LIBS) test_client_put_chunked_shutdown$(EXEEXT): $(test_client_put_chunked_shutdown_OBJECTS) $(test_client_put_chunked_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_chunked_shutdown_DEPENDENCIES) @rm -f test_client_put_chunked_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_shutdown_OBJECTS) $(test_client_put_chunked_shutdown_LDADD) $(LIBS) test_client_put_chunked_steps_close$(EXEEXT): $(test_client_put_chunked_steps_close_OBJECTS) $(test_client_put_chunked_steps_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_close_DEPENDENCIES) @rm -f test_client_put_chunked_steps_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_close_OBJECTS) $(test_client_put_chunked_steps_close_LDADD) $(LIBS) test_client_put_chunked_steps_hard_close$(EXEEXT): $(test_client_put_chunked_steps_hard_close_OBJECTS) $(test_client_put_chunked_steps_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_hard_close_DEPENDENCIES) @rm -f test_client_put_chunked_steps_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_hard_close_OBJECTS) $(test_client_put_chunked_steps_hard_close_LDADD) $(LIBS) test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT): $(test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) $(test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) $(test_client_put_chunked_steps_hard_close_stress_os_LDADD) $(LIBS) test_client_put_chunked_steps_shutdown$(EXEEXT): $(test_client_put_chunked_steps_shutdown_OBJECTS) $(test_client_put_chunked_steps_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_shutdown_DEPENDENCIES) @rm -f test_client_put_chunked_steps_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_shutdown_OBJECTS) $(test_client_put_chunked_steps_shutdown_LDADD) $(LIBS) test_client_put_close$(EXEEXT): $(test_client_put_close_OBJECTS) $(test_client_put_close_DEPENDENCIES) $(EXTRA_test_client_put_close_DEPENDENCIES) @rm -f test_client_put_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_close_OBJECTS) $(test_client_put_close_LDADD) $(LIBS) test_client_put_hard_close$(EXEEXT): $(test_client_put_hard_close_OBJECTS) $(test_client_put_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_hard_close_DEPENDENCIES) @rm -f test_client_put_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_hard_close_OBJECTS) $(test_client_put_hard_close_LDADD) $(LIBS) test_client_put_hard_close_stress_os$(EXEEXT): $(test_client_put_hard_close_stress_os_OBJECTS) $(test_client_put_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_hard_close_stress_os_OBJECTS) $(test_client_put_hard_close_stress_os_LDADD) $(LIBS) test_client_put_shutdown$(EXEEXT): $(test_client_put_shutdown_OBJECTS) $(test_client_put_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_shutdown_DEPENDENCIES) @rm -f test_client_put_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_shutdown_OBJECTS) $(test_client_put_shutdown_LDADD) $(LIBS) test_client_put_steps_close$(EXEEXT): $(test_client_put_steps_close_OBJECTS) $(test_client_put_steps_close_DEPENDENCIES) $(EXTRA_test_client_put_steps_close_DEPENDENCIES) @rm -f test_client_put_steps_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_close_OBJECTS) $(test_client_put_steps_close_LDADD) $(LIBS) test_client_put_steps_hard_close$(EXEEXT): $(test_client_put_steps_hard_close_OBJECTS) $(test_client_put_steps_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_steps_hard_close_DEPENDENCIES) @rm -f test_client_put_steps_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_hard_close_OBJECTS) $(test_client_put_steps_hard_close_LDADD) $(LIBS) test_client_put_steps_hard_close_stress_os$(EXEEXT): $(test_client_put_steps_hard_close_stress_os_OBJECTS) $(test_client_put_steps_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_steps_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_steps_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_hard_close_stress_os_OBJECTS) $(test_client_put_steps_hard_close_stress_os_LDADD) $(LIBS) test_client_put_steps_shutdown$(EXEEXT): $(test_client_put_steps_shutdown_OBJECTS) $(test_client_put_steps_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_steps_shutdown_DEPENDENCIES) @rm -f test_client_put_steps_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_shutdown_OBJECTS) $(test_client_put_steps_shutdown_LDADD) $(LIBS) test_daemon$(EXEEXT): $(test_daemon_OBJECTS) $(test_daemon_DEPENDENCIES) $(EXTRA_test_daemon_DEPENDENCIES) @rm -f test_daemon$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_daemon_OBJECTS) $(test_daemon_LDADD) $(LIBS) test_dauth_userdigest$(EXEEXT): $(test_dauth_userdigest_OBJECTS) $(test_dauth_userdigest_DEPENDENCIES) $(EXTRA_test_dauth_userdigest_DEPENDENCIES) @rm -f test_dauth_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dauth_userdigest_OBJECTS) $(test_dauth_userdigest_LDADD) $(LIBS) test_dauth_userhash$(EXEEXT): $(test_dauth_userhash_OBJECTS) $(test_dauth_userhash_DEPENDENCIES) $(EXTRA_test_dauth_userhash_DEPENDENCIES) @rm -f test_dauth_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dauth_userhash_OBJECTS) $(test_dauth_userhash_LDADD) $(LIBS) test_http_reasons$(EXEEXT): $(test_http_reasons_OBJECTS) $(test_http_reasons_DEPENDENCIES) $(EXTRA_test_http_reasons_DEPENDENCIES) @rm -f test_http_reasons$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_http_reasons_OBJECTS) $(test_http_reasons_LDADD) $(LIBS) test_md5$(EXEEXT): $(test_md5_OBJECTS) $(test_md5_DEPENDENCIES) $(EXTRA_test_md5_DEPENDENCIES) @rm -f test_md5$(EXEEXT) $(AM_V_CCLD)$(test_md5_LINK) $(test_md5_OBJECTS) $(test_md5_LDADD) $(LIBS) test_mhd_version$(EXEEXT): $(test_mhd_version_OBJECTS) $(test_mhd_version_DEPENDENCIES) $(EXTRA_test_mhd_version_DEPENDENCIES) @rm -f test_mhd_version$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_mhd_version_OBJECTS) $(test_mhd_version_LDADD) $(LIBS) test_options$(EXEEXT): $(test_options_OBJECTS) $(test_options_DEPENDENCIES) $(EXTRA_test_options_DEPENDENCIES) @rm -f test_options$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_options_OBJECTS) $(test_options_LDADD) $(LIBS) test_postprocessor$(EXEEXT): $(test_postprocessor_OBJECTS) $(test_postprocessor_DEPENDENCIES) $(EXTRA_test_postprocessor_DEPENDENCIES) @rm -f test_postprocessor$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_LINK) $(test_postprocessor_OBJECTS) $(test_postprocessor_LDADD) $(LIBS) test_postprocessor_amp$(EXEEXT): $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_DEPENDENCIES) $(EXTRA_test_postprocessor_amp_DEPENDENCIES) @rm -f test_postprocessor_amp$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_amp_LINK) $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_LDADD) $(LIBS) test_postprocessor_large$(EXEEXT): $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_DEPENDENCIES) $(EXTRA_test_postprocessor_large_DEPENDENCIES) @rm -f test_postprocessor_large$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_large_LINK) $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_LDADD) $(LIBS) test_postprocessor_md$(EXEEXT): $(test_postprocessor_md_OBJECTS) $(test_postprocessor_md_DEPENDENCIES) $(EXTRA_test_postprocessor_md_DEPENDENCIES) @rm -f test_postprocessor_md$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postprocessor_md_OBJECTS) $(test_postprocessor_md_LDADD) $(LIBS) test_response_entries$(EXEEXT): $(test_response_entries_OBJECTS) $(test_response_entries_DEPENDENCIES) $(EXTRA_test_response_entries_DEPENDENCIES) @rm -f test_response_entries$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_response_entries_OBJECTS) $(test_response_entries_LDADD) $(LIBS) test_set_panic$(EXEEXT): $(test_set_panic_OBJECTS) $(test_set_panic_DEPENDENCIES) $(EXTRA_test_set_panic_DEPENDENCIES) @rm -f test_set_panic$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_set_panic_OBJECTS) $(test_set_panic_LDADD) $(LIBS) test_sha1$(EXEEXT): $(test_sha1_OBJECTS) $(test_sha1_DEPENDENCIES) $(EXTRA_test_sha1_DEPENDENCIES) @rm -f test_sha1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_sha1_OBJECTS) $(test_sha1_LDADD) $(LIBS) test_sha256$(EXEEXT): $(test_sha256_OBJECTS) $(test_sha256_DEPENDENCIES) $(EXTRA_test_sha256_DEPENDENCIES) @rm -f test_sha256$(EXEEXT) $(AM_V_CCLD)$(test_sha256_LINK) $(test_sha256_OBJECTS) $(test_sha256_LDADD) $(LIBS) test_sha512_256$(EXEEXT): $(test_sha512_256_OBJECTS) $(test_sha512_256_DEPENDENCIES) $(EXTRA_test_sha512_256_DEPENDENCIES) @rm -f test_sha512_256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_sha512_256_OBJECTS) $(test_sha512_256_LDADD) $(LIBS) test_shutdown_poll$(EXEEXT): $(test_shutdown_poll_OBJECTS) $(test_shutdown_poll_DEPENDENCIES) $(EXTRA_test_shutdown_poll_DEPENDENCIES) @rm -f test_shutdown_poll$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_poll_LINK) $(test_shutdown_poll_OBJECTS) $(test_shutdown_poll_LDADD) $(LIBS) test_shutdown_poll_ignore$(EXEEXT): $(test_shutdown_poll_ignore_OBJECTS) $(test_shutdown_poll_ignore_DEPENDENCIES) $(EXTRA_test_shutdown_poll_ignore_DEPENDENCIES) @rm -f test_shutdown_poll_ignore$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_poll_ignore_LINK) $(test_shutdown_poll_ignore_OBJECTS) $(test_shutdown_poll_ignore_LDADD) $(LIBS) test_shutdown_select$(EXEEXT): $(test_shutdown_select_OBJECTS) $(test_shutdown_select_DEPENDENCIES) $(EXTRA_test_shutdown_select_DEPENDENCIES) @rm -f test_shutdown_select$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_select_LINK) $(test_shutdown_select_OBJECTS) $(test_shutdown_select_LDADD) $(LIBS) test_shutdown_select_ignore$(EXEEXT): $(test_shutdown_select_ignore_OBJECTS) $(test_shutdown_select_ignore_DEPENDENCIES) $(EXTRA_test_shutdown_select_ignore_DEPENDENCIES) @rm -f test_shutdown_select_ignore$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_select_ignore_LINK) $(test_shutdown_select_ignore_OBJECTS) $(test_shutdown_select_ignore_LDADD) $(LIBS) test_start_stop$(EXEEXT): $(test_start_stop_OBJECTS) $(test_start_stop_DEPENDENCIES) $(EXTRA_test_start_stop_DEPENDENCIES) @rm -f test_start_stop$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_start_stop_OBJECTS) $(test_start_stop_LDADD) $(LIBS) test_str_base64$(EXEEXT): $(test_str_base64_OBJECTS) $(test_str_base64_DEPENDENCIES) $(EXTRA_test_str_base64_DEPENDENCIES) @rm -f test_str_base64$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_base64_OBJECTS) $(test_str_base64_LDADD) $(LIBS) test_str_bin_hex$(EXEEXT): $(test_str_bin_hex_OBJECTS) $(test_str_bin_hex_DEPENDENCIES) $(EXTRA_test_str_bin_hex_DEPENDENCIES) @rm -f test_str_bin_hex$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_bin_hex_OBJECTS) $(test_str_bin_hex_LDADD) $(LIBS) test_str_compare$(EXEEXT): $(test_str_compare_OBJECTS) $(test_str_compare_DEPENDENCIES) $(EXTRA_test_str_compare_DEPENDENCIES) @rm -f test_str_compare$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_compare_OBJECTS) $(test_str_compare_LDADD) $(LIBS) test_str_from_value$(EXEEXT): $(test_str_from_value_OBJECTS) $(test_str_from_value_DEPENDENCIES) $(EXTRA_test_str_from_value_DEPENDENCIES) @rm -f test_str_from_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_from_value_OBJECTS) $(test_str_from_value_LDADD) $(LIBS) test_str_pct$(EXEEXT): $(test_str_pct_OBJECTS) $(test_str_pct_DEPENDENCIES) $(EXTRA_test_str_pct_DEPENDENCIES) @rm -f test_str_pct$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_pct_OBJECTS) $(test_str_pct_LDADD) $(LIBS) test_str_quote$(EXEEXT): $(test_str_quote_OBJECTS) $(test_str_quote_DEPENDENCIES) $(EXTRA_test_str_quote_DEPENDENCIES) @rm -f test_str_quote$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_quote_OBJECTS) $(test_str_quote_LDADD) $(LIBS) test_str_to_value$(EXEEXT): $(test_str_to_value_OBJECTS) $(test_str_to_value_DEPENDENCIES) $(EXTRA_test_str_to_value_DEPENDENCIES) @rm -f test_str_to_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_to_value_OBJECTS) $(test_str_to_value_LDADD) $(LIBS) test_str_token$(EXEEXT): $(test_str_token_OBJECTS) $(test_str_token_DEPENDENCIES) $(EXTRA_test_str_token_DEPENDENCIES) @rm -f test_str_token$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_token_OBJECTS) $(test_str_token_LDADD) $(LIBS) test_str_token_remove$(EXEEXT): $(test_str_token_remove_OBJECTS) $(test_str_token_remove_DEPENDENCIES) $(EXTRA_test_str_token_remove_DEPENDENCIES) @rm -f test_str_token_remove$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_token_remove_OBJECTS) $(test_str_token_remove_LDADD) $(LIBS) test_str_tokens_remove$(EXEEXT): $(test_str_tokens_remove_OBJECTS) $(test_str_tokens_remove_DEPENDENCIES) $(EXTRA_test_str_tokens_remove_DEPENDENCIES) @rm -f test_str_tokens_remove$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_tokens_remove_OBJECTS) $(test_str_tokens_remove_LDADD) $(LIBS) test_upgrade$(EXEEXT): $(test_upgrade_OBJECTS) $(test_upgrade_DEPENDENCIES) $(EXTRA_test_upgrade_DEPENDENCIES) @rm -f test_upgrade$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_LINK) $(test_upgrade_OBJECTS) $(test_upgrade_LDADD) $(LIBS) test_upgrade_large$(EXEEXT): $(test_upgrade_large_OBJECTS) $(test_upgrade_large_DEPENDENCIES) $(EXTRA_test_upgrade_large_DEPENDENCIES) @rm -f test_upgrade_large$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_large_LINK) $(test_upgrade_large_OBJECTS) $(test_upgrade_large_LDADD) $(LIBS) test_upgrade_large_tls$(EXEEXT): $(test_upgrade_large_tls_OBJECTS) $(test_upgrade_large_tls_DEPENDENCIES) $(EXTRA_test_upgrade_large_tls_DEPENDENCIES) @rm -f test_upgrade_large_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_large_tls_LINK) $(test_upgrade_large_tls_OBJECTS) $(test_upgrade_large_tls_LDADD) $(LIBS) test_upgrade_tls$(EXEEXT): $(test_upgrade_tls_OBJECTS) $(test_upgrade_tls_DEPENDENCIES) $(EXTRA_test_upgrade_tls_DEPENDENCIES) @rm -f test_upgrade_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_tls_LINK) $(test_upgrade_tls_OBJECTS) $(test_upgrade_tls_LDADD) $(LIBS) test_upgrade_vlarge$(EXEEXT): $(test_upgrade_vlarge_OBJECTS) $(test_upgrade_vlarge_DEPENDENCIES) $(EXTRA_test_upgrade_vlarge_DEPENDENCIES) @rm -f test_upgrade_vlarge$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_vlarge_LINK) $(test_upgrade_vlarge_OBJECTS) $(test_upgrade_vlarge_LDADD) $(LIBS) test_upgrade_vlarge_tls$(EXEEXT): $(test_upgrade_vlarge_tls_OBJECTS) $(test_upgrade_vlarge_tls_DEPENDENCIES) $(EXTRA_test_upgrade_vlarge_tls_DEPENDENCIES) @rm -f test_upgrade_vlarge_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_vlarge_tls_LINK) $(test_upgrade_vlarge_tls_OBJECTS) $(test_upgrade_vlarge_tls_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-daemon.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-internal.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-md5.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-response.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha256.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/reason_phrase.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha1.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha512_256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-gen_auth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-test_auth_parse.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_client_put_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_daemon.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dauth_userdigest.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dauth_userhash.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_http_reasons.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-md5.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-md5_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-test_md5.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mhd_version.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_options.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor-test_postprocessor.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-internal.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-postprocessor.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_response_entries.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_set_panic.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha1.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-sha256_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-test_sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha512_256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_start_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_base64.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_bin_hex.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_pct.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_quote.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_token.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_token_remove.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_tokens_remove.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_large-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< libmicrohttpd_la-connection.lo: connection.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection.Tpo -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection.Tpo $(DEPDIR)/libmicrohttpd_la-connection.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connection.c' object='libmicrohttpd_la-connection.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c libmicrohttpd_la-reason_phrase.lo: reason_phrase.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-reason_phrase.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo $(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='reason_phrase.c' object='libmicrohttpd_la-reason_phrase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c libmicrohttpd_la-daemon.lo: daemon.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-daemon.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-daemon.Tpo -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-daemon.Tpo $(DEPDIR)/libmicrohttpd_la-daemon.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='daemon.c' object='libmicrohttpd_la-daemon.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c libmicrohttpd_la-internal.lo: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-internal.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-internal.Tpo -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-internal.Tpo $(DEPDIR)/libmicrohttpd_la-internal.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='libmicrohttpd_la-internal.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c libmicrohttpd_la-memorypool.lo: memorypool.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-memorypool.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo $(DEPDIR)/libmicrohttpd_la-memorypool.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='memorypool.c' object='libmicrohttpd_la-memorypool.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c libmicrohttpd_la-mhd_mono_clock.lo: mhd_mono_clock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_mono_clock.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Tpo -c -o libmicrohttpd_la-mhd_mono_clock.lo `test -f 'mhd_mono_clock.c' || echo '$(srcdir)/'`mhd_mono_clock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_mono_clock.c' object='libmicrohttpd_la-mhd_mono_clock.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_mono_clock.lo `test -f 'mhd_mono_clock.c' || echo '$(srcdir)/'`mhd_mono_clock.c libmicrohttpd_la-mhd_str.lo: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_str.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_str.Tpo -c -o libmicrohttpd_la-mhd_str.lo `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_str.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_str.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='libmicrohttpd_la-mhd_str.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_str.lo `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c libmicrohttpd_la-mhd_send.lo: mhd_send.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_send.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_send.Tpo -c -o libmicrohttpd_la-mhd_send.lo `test -f 'mhd_send.c' || echo '$(srcdir)/'`mhd_send.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_send.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_send.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_send.c' object='libmicrohttpd_la-mhd_send.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_send.lo `test -f 'mhd_send.c' || echo '$(srcdir)/'`mhd_send.c libmicrohttpd_la-mhd_sockets.lo: mhd_sockets.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_sockets.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Tpo -c -o libmicrohttpd_la-mhd_sockets.lo `test -f 'mhd_sockets.c' || echo '$(srcdir)/'`mhd_sockets.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_sockets.c' object='libmicrohttpd_la-mhd_sockets.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_sockets.lo `test -f 'mhd_sockets.c' || echo '$(srcdir)/'`mhd_sockets.c libmicrohttpd_la-mhd_itc.lo: mhd_itc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_itc.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_itc.Tpo -c -o libmicrohttpd_la-mhd_itc.lo `test -f 'mhd_itc.c' || echo '$(srcdir)/'`mhd_itc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_itc.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_itc.c' object='libmicrohttpd_la-mhd_itc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_itc.lo `test -f 'mhd_itc.c' || echo '$(srcdir)/'`mhd_itc.c libmicrohttpd_la-mhd_compat.lo: mhd_compat.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_compat.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_compat.Tpo -c -o libmicrohttpd_la-mhd_compat.lo `test -f 'mhd_compat.c' || echo '$(srcdir)/'`mhd_compat.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_compat.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_compat.c' object='libmicrohttpd_la-mhd_compat.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_compat.lo `test -f 'mhd_compat.c' || echo '$(srcdir)/'`mhd_compat.c libmicrohttpd_la-mhd_panic.lo: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_panic.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_panic.Tpo -c -o libmicrohttpd_la-mhd_panic.lo `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_panic.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='libmicrohttpd_la-mhd_panic.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_panic.lo `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c libmicrohttpd_la-response.lo: response.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-response.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-response.Tpo -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-response.Tpo $(DEPDIR)/libmicrohttpd_la-response.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='response.c' object='libmicrohttpd_la-response.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c libmicrohttpd_la-mhd_threads.lo: mhd_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_threads.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_threads.Tpo -c -o libmicrohttpd_la-mhd_threads.lo `test -f 'mhd_threads.c' || echo '$(srcdir)/'`mhd_threads.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_threads.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_threads.c' object='libmicrohttpd_la-mhd_threads.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_threads.lo `test -f 'mhd_threads.c' || echo '$(srcdir)/'`mhd_threads.c libmicrohttpd_la-sysfdsetsize.lo: sysfdsetsize.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sysfdsetsize.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Tpo -c -o libmicrohttpd_la-sysfdsetsize.lo `test -f 'sysfdsetsize.c' || echo '$(srcdir)/'`sysfdsetsize.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Tpo $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sysfdsetsize.c' object='libmicrohttpd_la-sysfdsetsize.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sysfdsetsize.lo `test -f 'sysfdsetsize.c' || echo '$(srcdir)/'`sysfdsetsize.c libmicrohttpd_la-tsearch.lo: tsearch.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-tsearch.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo $(DEPDIR)/libmicrohttpd_la-tsearch.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tsearch.c' object='libmicrohttpd_la-tsearch.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c libmicrohttpd_la-postprocessor.lo: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-postprocessor.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo $(DEPDIR)/libmicrohttpd_la-postprocessor.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='libmicrohttpd_la-postprocessor.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c libmicrohttpd_la-gen_auth.lo: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-gen_auth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-gen_auth.Tpo -c -o libmicrohttpd_la-gen_auth.lo `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-gen_auth.Tpo $(DEPDIR)/libmicrohttpd_la-gen_auth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='libmicrohttpd_la-gen_auth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-gen_auth.lo `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c libmicrohttpd_la-digestauth.lo: digestauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-digestauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo $(DEPDIR)/libmicrohttpd_la-digestauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='digestauth.c' object='libmicrohttpd_la-digestauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c libmicrohttpd_la-md5.lo: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-md5.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-md5.Tpo -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-md5.Tpo $(DEPDIR)/libmicrohttpd_la-md5.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='libmicrohttpd_la-md5.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c libmicrohttpd_la-md5_ext.lo: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-md5_ext.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-md5_ext.Tpo -c -o libmicrohttpd_la-md5_ext.lo `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-md5_ext.Tpo $(DEPDIR)/libmicrohttpd_la-md5_ext.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='libmicrohttpd_la-md5_ext.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-md5_ext.lo `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c libmicrohttpd_la-sha256.lo: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha256.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha256.Tpo -c -o libmicrohttpd_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha256.Tpo $(DEPDIR)/libmicrohttpd_la-sha256.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='libmicrohttpd_la-sha256.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c libmicrohttpd_la-sha256_ext.lo: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha256_ext.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha256_ext.Tpo -c -o libmicrohttpd_la-sha256_ext.lo `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha256_ext.Tpo $(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='libmicrohttpd_la-sha256_ext.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha256_ext.lo `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c libmicrohttpd_la-sha512_256.lo: sha512_256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha512_256.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha512_256.Tpo -c -o libmicrohttpd_la-sha512_256.lo `test -f 'sha512_256.c' || echo '$(srcdir)/'`sha512_256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha512_256.Tpo $(DEPDIR)/libmicrohttpd_la-sha512_256.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha512_256.c' object='libmicrohttpd_la-sha512_256.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha512_256.lo `test -f 'sha512_256.c' || echo '$(srcdir)/'`sha512_256.c libmicrohttpd_la-basicauth.lo: basicauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-basicauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo $(DEPDIR)/libmicrohttpd_la-basicauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='basicauth.c' object='libmicrohttpd_la-basicauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c libmicrohttpd_la-connection_https.lo: connection_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection_https.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo $(DEPDIR)/libmicrohttpd_la-connection_https.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connection_https.c' object='libmicrohttpd_la-connection_https.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c test_auth_parse-test_auth_parse.o: test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-test_auth_parse.o -MD -MP -MF $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo -c -o test_auth_parse-test_auth_parse.o `test -f 'test_auth_parse.c' || echo '$(srcdir)/'`test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo $(DEPDIR)/test_auth_parse-test_auth_parse.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_auth_parse.c' object='test_auth_parse-test_auth_parse.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-test_auth_parse.o `test -f 'test_auth_parse.c' || echo '$(srcdir)/'`test_auth_parse.c test_auth_parse-test_auth_parse.obj: test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-test_auth_parse.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo -c -o test_auth_parse-test_auth_parse.obj `if test -f 'test_auth_parse.c'; then $(CYGPATH_W) 'test_auth_parse.c'; else $(CYGPATH_W) '$(srcdir)/test_auth_parse.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo $(DEPDIR)/test_auth_parse-test_auth_parse.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_auth_parse.c' object='test_auth_parse-test_auth_parse.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-test_auth_parse.obj `if test -f 'test_auth_parse.c'; then $(CYGPATH_W) 'test_auth_parse.c'; else $(CYGPATH_W) '$(srcdir)/test_auth_parse.c'; fi` test_auth_parse-gen_auth.o: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-gen_auth.o -MD -MP -MF $(DEPDIR)/test_auth_parse-gen_auth.Tpo -c -o test_auth_parse-gen_auth.o `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-gen_auth.Tpo $(DEPDIR)/test_auth_parse-gen_auth.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='test_auth_parse-gen_auth.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-gen_auth.o `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c test_auth_parse-gen_auth.obj: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-gen_auth.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-gen_auth.Tpo -c -o test_auth_parse-gen_auth.obj `if test -f 'gen_auth.c'; then $(CYGPATH_W) 'gen_auth.c'; else $(CYGPATH_W) '$(srcdir)/gen_auth.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-gen_auth.Tpo $(DEPDIR)/test_auth_parse-gen_auth.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='test_auth_parse-gen_auth.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-gen_auth.obj `if test -f 'gen_auth.c'; then $(CYGPATH_W) 'gen_auth.c'; else $(CYGPATH_W) '$(srcdir)/gen_auth.c'; fi` test_auth_parse-mhd_str.o: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-mhd_str.o -MD -MP -MF $(DEPDIR)/test_auth_parse-mhd_str.Tpo -c -o test_auth_parse-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-mhd_str.Tpo $(DEPDIR)/test_auth_parse-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_auth_parse-mhd_str.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c test_auth_parse-mhd_str.obj: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-mhd_str.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-mhd_str.Tpo -c -o test_auth_parse-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-mhd_str.Tpo $(DEPDIR)/test_auth_parse-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_auth_parse-mhd_str.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` test_md5-test_md5.o: test_md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-test_md5.o -MD -MP -MF $(DEPDIR)/test_md5-test_md5.Tpo -c -o test_md5-test_md5.o `test -f 'test_md5.c' || echo '$(srcdir)/'`test_md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-test_md5.Tpo $(DEPDIR)/test_md5-test_md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_md5.c' object='test_md5-test_md5.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-test_md5.o `test -f 'test_md5.c' || echo '$(srcdir)/'`test_md5.c test_md5-test_md5.obj: test_md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-test_md5.obj -MD -MP -MF $(DEPDIR)/test_md5-test_md5.Tpo -c -o test_md5-test_md5.obj `if test -f 'test_md5.c'; then $(CYGPATH_W) 'test_md5.c'; else $(CYGPATH_W) '$(srcdir)/test_md5.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-test_md5.Tpo $(DEPDIR)/test_md5-test_md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_md5.c' object='test_md5-test_md5.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-test_md5.obj `if test -f 'test_md5.c'; then $(CYGPATH_W) 'test_md5.c'; else $(CYGPATH_W) '$(srcdir)/test_md5.c'; fi` test_md5-md5.o: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5.o -MD -MP -MF $(DEPDIR)/test_md5-md5.Tpo -c -o test_md5-md5.o `test -f 'md5.c' || echo '$(srcdir)/'`md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5.Tpo $(DEPDIR)/test_md5-md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='test_md5-md5.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5.o `test -f 'md5.c' || echo '$(srcdir)/'`md5.c test_md5-md5.obj: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5.obj -MD -MP -MF $(DEPDIR)/test_md5-md5.Tpo -c -o test_md5-md5.obj `if test -f 'md5.c'; then $(CYGPATH_W) 'md5.c'; else $(CYGPATH_W) '$(srcdir)/md5.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5.Tpo $(DEPDIR)/test_md5-md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='test_md5-md5.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5.obj `if test -f 'md5.c'; then $(CYGPATH_W) 'md5.c'; else $(CYGPATH_W) '$(srcdir)/md5.c'; fi` test_md5-md5_ext.o: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5_ext.o -MD -MP -MF $(DEPDIR)/test_md5-md5_ext.Tpo -c -o test_md5-md5_ext.o `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5_ext.Tpo $(DEPDIR)/test_md5-md5_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='test_md5-md5_ext.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5_ext.o `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c test_md5-md5_ext.obj: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5_ext.obj -MD -MP -MF $(DEPDIR)/test_md5-md5_ext.Tpo -c -o test_md5-md5_ext.obj `if test -f 'md5_ext.c'; then $(CYGPATH_W) 'md5_ext.c'; else $(CYGPATH_W) '$(srcdir)/md5_ext.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5_ext.Tpo $(DEPDIR)/test_md5-md5_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='test_md5-md5_ext.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5_ext.obj `if test -f 'md5_ext.c'; then $(CYGPATH_W) 'md5_ext.c'; else $(CYGPATH_W) '$(srcdir)/md5_ext.c'; fi` test_postprocessor-test_postprocessor.o: test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.o -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c test_postprocessor-test_postprocessor.obj: test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.obj -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi` test_postprocessor_amp-test_postprocessor_amp.o: test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.o -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c test_postprocessor_amp-test_postprocessor_amp.obj: test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi` test_postprocessor_large-test_postprocessor_large.o: test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.o -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c test_postprocessor_large-test_postprocessor_large.obj: test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi` test_postprocessor_md-test_postprocessor_md.o: test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-test_postprocessor_md.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo -c -o test_postprocessor_md-test_postprocessor_md.o `test -f 'test_postprocessor_md.c' || echo '$(srcdir)/'`test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_md.c' object='test_postprocessor_md-test_postprocessor_md.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-test_postprocessor_md.o `test -f 'test_postprocessor_md.c' || echo '$(srcdir)/'`test_postprocessor_md.c test_postprocessor_md-test_postprocessor_md.obj: test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-test_postprocessor_md.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo -c -o test_postprocessor_md-test_postprocessor_md.obj `if test -f 'test_postprocessor_md.c'; then $(CYGPATH_W) 'test_postprocessor_md.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_md.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_md.c' object='test_postprocessor_md-test_postprocessor_md.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-test_postprocessor_md.obj `if test -f 'test_postprocessor_md.c'; then $(CYGPATH_W) 'test_postprocessor_md.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_md.c'; fi` test_postprocessor_md-postprocessor.o: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-postprocessor.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo -c -o test_postprocessor_md-postprocessor.o `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo $(DEPDIR)/test_postprocessor_md-postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='test_postprocessor_md-postprocessor.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-postprocessor.o `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c test_postprocessor_md-postprocessor.obj: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-postprocessor.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo -c -o test_postprocessor_md-postprocessor.obj `if test -f 'postprocessor.c'; then $(CYGPATH_W) 'postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/postprocessor.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo $(DEPDIR)/test_postprocessor_md-postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='test_postprocessor_md-postprocessor.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-postprocessor.obj `if test -f 'postprocessor.c'; then $(CYGPATH_W) 'postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/postprocessor.c'; fi` test_postprocessor_md-internal.o: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-internal.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-internal.Tpo -c -o test_postprocessor_md-internal.o `test -f 'internal.c' || echo '$(srcdir)/'`internal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-internal.Tpo $(DEPDIR)/test_postprocessor_md-internal.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='test_postprocessor_md-internal.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-internal.o `test -f 'internal.c' || echo '$(srcdir)/'`internal.c test_postprocessor_md-internal.obj: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-internal.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-internal.Tpo -c -o test_postprocessor_md-internal.obj `if test -f 'internal.c'; then $(CYGPATH_W) 'internal.c'; else $(CYGPATH_W) '$(srcdir)/internal.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-internal.Tpo $(DEPDIR)/test_postprocessor_md-internal.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='test_postprocessor_md-internal.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-internal.obj `if test -f 'internal.c'; then $(CYGPATH_W) 'internal.c'; else $(CYGPATH_W) '$(srcdir)/internal.c'; fi` test_postprocessor_md-mhd_str.o: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_str.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo -c -o test_postprocessor_md-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo $(DEPDIR)/test_postprocessor_md-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_postprocessor_md-mhd_str.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c test_postprocessor_md-mhd_str.obj: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_str.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo -c -o test_postprocessor_md-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo $(DEPDIR)/test_postprocessor_md-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_postprocessor_md-mhd_str.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` test_postprocessor_md-mhd_panic.o: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_panic.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo -c -o test_postprocessor_md-mhd_panic.o `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo $(DEPDIR)/test_postprocessor_md-mhd_panic.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='test_postprocessor_md-mhd_panic.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_panic.o `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c test_postprocessor_md-mhd_panic.obj: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_panic.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo -c -o test_postprocessor_md-mhd_panic.obj `if test -f 'mhd_panic.c'; then $(CYGPATH_W) 'mhd_panic.c'; else $(CYGPATH_W) '$(srcdir)/mhd_panic.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo $(DEPDIR)/test_postprocessor_md-mhd_panic.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='test_postprocessor_md-mhd_panic.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_panic.obj `if test -f 'mhd_panic.c'; then $(CYGPATH_W) 'mhd_panic.c'; else $(CYGPATH_W) '$(srcdir)/mhd_panic.c'; fi` test_sha256-test_sha256.o: test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-test_sha256.o -MD -MP -MF $(DEPDIR)/test_sha256-test_sha256.Tpo -c -o test_sha256-test_sha256.o `test -f 'test_sha256.c' || echo '$(srcdir)/'`test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-test_sha256.Tpo $(DEPDIR)/test_sha256-test_sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_sha256.c' object='test_sha256-test_sha256.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-test_sha256.o `test -f 'test_sha256.c' || echo '$(srcdir)/'`test_sha256.c test_sha256-test_sha256.obj: test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-test_sha256.obj -MD -MP -MF $(DEPDIR)/test_sha256-test_sha256.Tpo -c -o test_sha256-test_sha256.obj `if test -f 'test_sha256.c'; then $(CYGPATH_W) 'test_sha256.c'; else $(CYGPATH_W) '$(srcdir)/test_sha256.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-test_sha256.Tpo $(DEPDIR)/test_sha256-test_sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_sha256.c' object='test_sha256-test_sha256.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-test_sha256.obj `if test -f 'test_sha256.c'; then $(CYGPATH_W) 'test_sha256.c'; else $(CYGPATH_W) '$(srcdir)/test_sha256.c'; fi` test_sha256-sha256.o: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256.o -MD -MP -MF $(DEPDIR)/test_sha256-sha256.Tpo -c -o test_sha256-sha256.o `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256.Tpo $(DEPDIR)/test_sha256-sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='test_sha256-sha256.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256.o `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c test_sha256-sha256.obj: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256.obj -MD -MP -MF $(DEPDIR)/test_sha256-sha256.Tpo -c -o test_sha256-sha256.obj `if test -f 'sha256.c'; then $(CYGPATH_W) 'sha256.c'; else $(CYGPATH_W) '$(srcdir)/sha256.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256.Tpo $(DEPDIR)/test_sha256-sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='test_sha256-sha256.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256.obj `if test -f 'sha256.c'; then $(CYGPATH_W) 'sha256.c'; else $(CYGPATH_W) '$(srcdir)/sha256.c'; fi` test_sha256-sha256_ext.o: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256_ext.o -MD -MP -MF $(DEPDIR)/test_sha256-sha256_ext.Tpo -c -o test_sha256-sha256_ext.o `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256_ext.Tpo $(DEPDIR)/test_sha256-sha256_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='test_sha256-sha256_ext.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256_ext.o `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c test_sha256-sha256_ext.obj: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256_ext.obj -MD -MP -MF $(DEPDIR)/test_sha256-sha256_ext.Tpo -c -o test_sha256-sha256_ext.obj `if test -f 'sha256_ext.c'; then $(CYGPATH_W) 'sha256_ext.c'; else $(CYGPATH_W) '$(srcdir)/sha256_ext.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256_ext.Tpo $(DEPDIR)/test_sha256-sha256_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='test_sha256-sha256_ext.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256_ext.obj `if test -f 'sha256_ext.c'; then $(CYGPATH_W) 'sha256_ext.c'; else $(CYGPATH_W) '$(srcdir)/sha256_ext.c'; fi` test_shutdown_poll-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -MT test_shutdown_poll-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo -c -o test_shutdown_poll-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_poll-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -MT test_shutdown_poll-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo -c -o test_shutdown_poll-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_poll_ignore-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_poll_ignore-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo -c -o test_shutdown_poll_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll_ignore-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_poll_ignore-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_poll_ignore-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo -c -o test_shutdown_poll_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll_ignore-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_select-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -MT test_shutdown_select-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo -c -o test_shutdown_select-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -c -o test_shutdown_select-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_select-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -MT test_shutdown_select-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo -c -o test_shutdown_select-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -c -o test_shutdown_select-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_select_ignore-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_select_ignore-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo -c -o test_shutdown_select_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select_ignore-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_select_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_select_ignore-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_select_ignore-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo -c -o test_shutdown_select_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select_ignore-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_select_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_upgrade-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -MT test_upgrade-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade-test_upgrade.Tpo -c -o test_upgrade-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade-test_upgrade.Tpo $(DEPDIR)/test_upgrade-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -c -o test_upgrade-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -MT test_upgrade-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade-test_upgrade.Tpo -c -o test_upgrade-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade-test_upgrade.Tpo $(DEPDIR)/test_upgrade-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -c -o test_upgrade-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_large-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -MT test_upgrade_large-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo -c -o test_upgrade_large-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -c -o test_upgrade_large-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_large-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -MT test_upgrade_large-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo -c -o test_upgrade_large-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -c -o test_upgrade_large-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_large_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_large_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo -c -o test_upgrade_large_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_large_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_large_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_large_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo -c -o test_upgrade_large_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_large_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo -c -o test_upgrade_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo -c -o test_upgrade_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_vlarge-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo -c -o test_upgrade_vlarge-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_vlarge-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo -c -o test_upgrade_vlarge-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_vlarge_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo -c -o test_upgrade_vlarge_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_vlarge_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo -c -o test_upgrade_vlarge_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_str_compare.log: test_str_compare$(EXEEXT) @p='test_str_compare$(EXEEXT)'; \ b='test_str_compare'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_to_value.log: test_str_to_value$(EXEEXT) @p='test_str_to_value$(EXEEXT)'; \ b='test_str_to_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_from_value.log: test_str_from_value$(EXEEXT) @p='test_str_from_value$(EXEEXT)'; \ b='test_str_from_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_token.log: test_str_token$(EXEEXT) @p='test_str_token$(EXEEXT)'; \ b='test_str_token'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_token_remove.log: test_str_token_remove$(EXEEXT) @p='test_str_token_remove$(EXEEXT)'; \ b='test_str_token_remove'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_tokens_remove.log: test_str_tokens_remove$(EXEEXT) @p='test_str_tokens_remove$(EXEEXT)'; \ b='test_str_tokens_remove'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_pct.log: test_str_pct$(EXEEXT) @p='test_str_pct$(EXEEXT)'; \ b='test_str_pct'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_bin_hex.log: test_str_bin_hex$(EXEEXT) @p='test_str_bin_hex$(EXEEXT)'; \ b='test_str_bin_hex'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_http_reasons.log: test_http_reasons$(EXEEXT) @p='test_http_reasons$(EXEEXT)'; \ b='test_http_reasons'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha1.log: test_sha1$(EXEEXT) @p='test_sha1$(EXEEXT)'; \ b='test_sha1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_start_stop.log: test_start_stop$(EXEEXT) @p='test_start_stop$(EXEEXT)'; \ b='test_start_stop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_daemon.log: test_daemon$(EXEEXT) @p='test_daemon$(EXEEXT)'; \ b='test_daemon'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_response_entries.log: test_response_entries$(EXEEXT) @p='test_response_entries$(EXEEXT)'; \ b='test_response_entries'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_md.log: test_postprocessor_md$(EXEEXT) @p='test_postprocessor_md$(EXEEXT)'; \ b='test_postprocessor_md'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_shutdown.log: test_client_put_shutdown$(EXEEXT) @p='test_client_put_shutdown$(EXEEXT)'; \ b='test_client_put_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_close.log: test_client_put_close$(EXEEXT) @p='test_client_put_close$(EXEEXT)'; \ b='test_client_put_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_hard_close.log: test_client_put_hard_close$(EXEEXT) @p='test_client_put_hard_close$(EXEEXT)'; \ b='test_client_put_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_shutdown.log: test_client_put_steps_shutdown$(EXEEXT) @p='test_client_put_steps_shutdown$(EXEEXT)'; \ b='test_client_put_steps_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_close.log: test_client_put_steps_close$(EXEEXT) @p='test_client_put_steps_close$(EXEEXT)'; \ b='test_client_put_steps_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_hard_close.log: test_client_put_steps_hard_close$(EXEEXT) @p='test_client_put_steps_hard_close$(EXEEXT)'; \ b='test_client_put_steps_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_shutdown.log: test_client_put_chunked_shutdown$(EXEEXT) @p='test_client_put_chunked_shutdown$(EXEEXT)'; \ b='test_client_put_chunked_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_close.log: test_client_put_chunked_close$(EXEEXT) @p='test_client_put_chunked_close$(EXEEXT)'; \ b='test_client_put_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_hard_close.log: test_client_put_chunked_hard_close$(EXEEXT) @p='test_client_put_chunked_hard_close$(EXEEXT)'; \ b='test_client_put_chunked_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_shutdown.log: test_client_put_chunked_steps_shutdown$(EXEEXT) @p='test_client_put_chunked_steps_shutdown$(EXEEXT)'; \ b='test_client_put_chunked_steps_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_close.log: test_client_put_chunked_steps_close$(EXEEXT) @p='test_client_put_chunked_steps_close$(EXEEXT)'; \ b='test_client_put_chunked_steps_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_hard_close.log: test_client_put_chunked_steps_hard_close$(EXEEXT) @p='test_client_put_chunked_steps_hard_close$(EXEEXT)'; \ b='test_client_put_chunked_steps_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_options.log: test_options$(EXEEXT) @p='test_options$(EXEEXT)'; \ b='test_options'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_mhd_version.log: test_mhd_version$(EXEEXT) @p='test_mhd_version$(EXEEXT)'; \ b='test_mhd_version'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_set_panic.log: test_set_panic$(EXEEXT) @p='test_set_panic$(EXEEXT)'; \ b='test_set_panic'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_md5.log: test_md5$(EXEEXT) @p='test_md5$(EXEEXT)'; \ b='test_md5'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha256.log: test_sha256$(EXEEXT) @p='test_sha256$(EXEEXT)'; \ b='test_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha512_256.log: test_sha512_256$(EXEEXT) @p='test_sha512_256$(EXEEXT)'; \ b='test_sha512_256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade.log: test_upgrade$(EXEEXT) @p='test_upgrade$(EXEEXT)'; \ b='test_upgrade'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_large.log: test_upgrade_large$(EXEEXT) @p='test_upgrade_large$(EXEEXT)'; \ b='test_upgrade_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_vlarge.log: test_upgrade_vlarge$(EXEEXT) @p='test_upgrade_vlarge$(EXEEXT)'; \ b='test_upgrade_vlarge'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_tls.log: test_upgrade_tls$(EXEEXT) @p='test_upgrade_tls$(EXEEXT)'; \ b='test_upgrade_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_large_tls.log: test_upgrade_large_tls$(EXEEXT) @p='test_upgrade_large_tls$(EXEEXT)'; \ b='test_upgrade_large_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_vlarge_tls.log: test_upgrade_vlarge_tls$(EXEEXT) @p='test_upgrade_vlarge_tls$(EXEEXT)'; \ b='test_upgrade_vlarge_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor.log: test_postprocessor$(EXEEXT) @p='test_postprocessor$(EXEEXT)'; \ b='test_postprocessor'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_large.log: test_postprocessor_large$(EXEEXT) @p='test_postprocessor_large$(EXEEXT)'; \ b='test_postprocessor_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_amp.log: test_postprocessor_amp$(EXEEXT) @p='test_postprocessor_amp$(EXEEXT)'; \ b='test_postprocessor_amp'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_select.log: test_shutdown_select$(EXEEXT) @p='test_shutdown_select$(EXEEXT)'; \ b='test_shutdown_select'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_poll.log: test_shutdown_poll$(EXEEXT) @p='test_shutdown_poll$(EXEEXT)'; \ b='test_shutdown_poll'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_select_ignore.log: test_shutdown_select_ignore$(EXEEXT) @p='test_shutdown_select_ignore$(EXEEXT)'; \ b='test_shutdown_select_ignore'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_poll_ignore.log: test_shutdown_poll_ignore$(EXEEXT) @p='test_shutdown_poll_ignore$(EXEEXT)'; \ b='test_shutdown_poll_ignore'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_auth_parse.log: test_auth_parse$(EXEEXT) @p='test_auth_parse$(EXEEXT)'; \ b='test_auth_parse'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_quote.log: test_str_quote$(EXEEXT) @p='test_str_quote$(EXEEXT)'; \ b='test_str_quote'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_dauth_userdigest.log: test_dauth_userdigest$(EXEEXT) @p='test_dauth_userdigest$(EXEEXT)'; \ b='test_dauth_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_dauth_userhash.log: test_dauth_userhash$(EXEEXT) @p='test_dauth_userhash$(EXEEXT)'; \ b='test_dauth_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_base64.log: test_str_base64$(EXEEXT) @p='test_str_base64$(EXEEXT)'; \ b='test_str_base64'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_hard_close_stress_os.log: test_client_put_hard_close_stress_os$(EXEEXT) @p='test_client_put_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_hard_close_stress_os.log: test_client_put_steps_hard_close_stress_os$(EXEEXT) @p='test_client_put_steps_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_steps_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_hard_close_stress_os.log: test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) @p='test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_chunked_steps_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile $(LTLIBRARIES) $(DATA) install-checkPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES) -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-internal.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-response.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo -rm -f ./$(DEPDIR)/mhd_str.Po -rm -f ./$(DEPDIR)/reason_phrase.Po -rm -f ./$(DEPDIR)/sha1.Po -rm -f ./$(DEPDIR)/sha512_256.Po -rm -f ./$(DEPDIR)/test_auth_parse-gen_auth.Po -rm -f ./$(DEPDIR)/test_auth_parse-mhd_str.Po -rm -f ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po -rm -f ./$(DEPDIR)/test_client_put_stop.Po -rm -f ./$(DEPDIR)/test_daemon.Po -rm -f ./$(DEPDIR)/test_dauth_userdigest.Po -rm -f ./$(DEPDIR)/test_dauth_userhash.Po -rm -f ./$(DEPDIR)/test_http_reasons.Po -rm -f ./$(DEPDIR)/test_md5-md5.Po -rm -f ./$(DEPDIR)/test_md5-md5_ext.Po -rm -f ./$(DEPDIR)/test_md5-test_md5.Po -rm -f ./$(DEPDIR)/test_mhd_version.Po -rm -f ./$(DEPDIR)/test_options.Po -rm -f ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po -rm -f ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-internal.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po -rm -f ./$(DEPDIR)/test_response_entries.Po -rm -f ./$(DEPDIR)/test_set_panic.Po -rm -f ./$(DEPDIR)/test_sha1.Po -rm -f ./$(DEPDIR)/test_sha256-sha256.Po -rm -f ./$(DEPDIR)/test_sha256-sha256_ext.Po -rm -f ./$(DEPDIR)/test_sha256-test_sha256.Po -rm -f ./$(DEPDIR)/test_sha512_256.Po -rm -f ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_start_stop.Po -rm -f ./$(DEPDIR)/test_str.Po -rm -f ./$(DEPDIR)/test_str_base64.Po -rm -f ./$(DEPDIR)/test_str_bin_hex.Po -rm -f ./$(DEPDIR)/test_str_pct.Po -rm -f ./$(DEPDIR)/test_str_quote.Po -rm -f ./$(DEPDIR)/test_str_token.Po -rm -f ./$(DEPDIR)/test_str_token_remove.Po -rm -f ./$(DEPDIR)/test_str_tokens_remove.Po -rm -f ./$(DEPDIR)/test_upgrade-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-internal.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-response.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo -rm -f ./$(DEPDIR)/mhd_str.Po -rm -f ./$(DEPDIR)/reason_phrase.Po -rm -f ./$(DEPDIR)/sha1.Po -rm -f ./$(DEPDIR)/sha512_256.Po -rm -f ./$(DEPDIR)/test_auth_parse-gen_auth.Po -rm -f ./$(DEPDIR)/test_auth_parse-mhd_str.Po -rm -f ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po -rm -f ./$(DEPDIR)/test_client_put_stop.Po -rm -f ./$(DEPDIR)/test_daemon.Po -rm -f ./$(DEPDIR)/test_dauth_userdigest.Po -rm -f ./$(DEPDIR)/test_dauth_userhash.Po -rm -f ./$(DEPDIR)/test_http_reasons.Po -rm -f ./$(DEPDIR)/test_md5-md5.Po -rm -f ./$(DEPDIR)/test_md5-md5_ext.Po -rm -f ./$(DEPDIR)/test_md5-test_md5.Po -rm -f ./$(DEPDIR)/test_mhd_version.Po -rm -f ./$(DEPDIR)/test_options.Po -rm -f ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po -rm -f ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-internal.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po -rm -f ./$(DEPDIR)/test_response_entries.Po -rm -f ./$(DEPDIR)/test_set_panic.Po -rm -f ./$(DEPDIR)/test_sha1.Po -rm -f ./$(DEPDIR)/test_sha256-sha256.Po -rm -f ./$(DEPDIR)/test_sha256-sha256_ext.Po -rm -f ./$(DEPDIR)/test_sha256-test_sha256.Po -rm -f ./$(DEPDIR)/test_sha512_256.Po -rm -f ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_start_stop.Po -rm -f ./$(DEPDIR)/test_str.Po -rm -f ./$(DEPDIR)/test_str_base64.Po -rm -f ./$(DEPDIR)/test_str_bin_hex.Po -rm -f ./$(DEPDIR)/test_str_pct.Po -rm -f ./$(DEPDIR)/test_str_quote.Po -rm -f ./$(DEPDIR)/test_str_token.Po -rm -f ./$(DEPDIR)/test_str_token_remove.Po -rm -f ./$(DEPDIR)/test_str_tokens_remove.Po -rm -f ./$(DEPDIR)/test_upgrade-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-TESTS \ check-am clean clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile @W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la @W32_SHARED_LIB_EXP_TRUE@ $(AM_V_at)test -f $@ && touch $@ || \ @W32_SHARED_LIB_EXP_TRUE@ ( rm -f libmicrohttpd.la ; $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la && touch $@ ) @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_at)test -f $@ && touch $@ || \ @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@ ( rm -f $(lt_cv_objdir)/libmicrohttpd.lib ; $(MAKE) $(AM_MAKEFLAGS) $(lt_cv_objdir)/libmicrohttpd.lib && touch $@ ) @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_LIB) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(MS_LIB_TOOL) -nologo -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -ignore:4221 @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib @W32_STATIC_LIB_TRUE@$(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_MS_LIB_TOOL_TRUE@@W32_STATIC_LIB_TRUE@ $(AM_V_LIB) $(MS_LIB_TOOL) -nologo -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o) @USE_MS_LIB_TOOL_FALSE@@W32_STATIC_LIB_TRUE@ $(AM_V_at)cp $(lt_cv_objdir)/libmicrohttpd.a $@ # General rule is not required, but keep it just in case # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. .rc.lo: $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $< -o $@ # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. libmicrohttpd_la-microhttpd_dll_res.lo: $(builddir)/microhttpd_dll_res.rc $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $(builddir)/microhttpd_dll_res.rc -o $@ update-po-POTFILES.in: $(top_srcdir)/po/POTFILES.in $(top_srcdir)/po/POTFILES.in: $(srcdir)/Makefile.am @echo "Creating $@" @echo src/include/microhttpd.h > "$@" && \ for src in $(am__libmicrohttpd_la_SOURCES_DIST) ; do \ echo "$(subdir)/$$src" >> "$@" ; \ done .PHONY: update-po-POTFILES.in # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: libmicrohttpd-1.0.2/src/microhttpd/connection.c0000644000175000017500000104333015035214301016544 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2020 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection.c * @brief Methods for managing connections * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "mhd_limits.h" #include "connection.h" #include "memorypool.h" #include "response.h" #include "mhd_mono_clock.h" #include "mhd_str.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_locks.h" #endif #include "mhd_sockets.h" #include "mhd_compat.h" #include "mhd_itc.h" #ifdef MHD_LINUX_SOLARIS_SENDFILE #include #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE) #include #include #include #endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */ #ifdef HTTPS_SUPPORT #include "connection_https.h" #endif /* HTTPS_SUPPORT */ #ifdef HAVE_SYS_PARAM_H /* For FreeBSD version identification */ #include #endif /* HAVE_SYS_PARAM_H */ #include "mhd_send.h" #include "mhd_assert.h" /** * Get whether bare LF in HTTP header and other protocol elements * should be treated as the line termination depending on the configured * strictness level. * RFC 9112, section 2.2 */ #define MHD_ALLOW_BARE_LF_AS_CRLF_(discp_lvl) (0 >= discp_lvl) /** * The reasonable length of the upload chunk "header" (the size specifier * with optional chunk extension). * MHD tries to keep the space in the read buffer large enough to read * the chunk "header" in one step. * The real "header" could be much larger, it will be handled correctly * anyway, however it may require several rounds of buffer grow. */ #define MHD_CHUNK_HEADER_REASONABLE_LEN 24 /** * Message to transmit when http 1.1 request is received */ #define HTTP_100_CONTINUE "HTTP/1.1 100 Continue\r\n\r\n" /** * Response text used when the request (http header) is too big to * be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_TOO_BIG \ "" \ "Request too big" \ "Request HTTP header is too big for the memory constraints " \ "of this webserver." \ "" #else #define ERR_MSG_REQUEST_TOO_BIG "" #endif /** * Response text used when the request header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_HEADER_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target and the request field lines, exceeds the memory " \ "constraints of this web server.

    " \ "

    The request could be re-tried with shorter field lines, a shorter " \ "request target or a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_HEADER_TOO_BIG "" #endif /** * Response text used when the request cookie header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target and the request field lines, exceeds the memory " \ "constraints of this web server.

    " \ "

    The request could be re-tried with smaller " \ ""Cookie:" field value, shorter other field lines, " \ "a shorter request target or a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG "" #endif /** * Response text used when the request chunk size line with chunk extension * cannot fit the buffer. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request target, the request field lines " \ "and the chunk size line exceeds the memory constraints of this web " \ "server.

    " \ "

    The request could be re-tried without chunk extensions, with a smaller " \ "chunk size, shorter field lines, a shorter request target or a shorter " \ "request method token.

    " \ "" #else #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG "" #endif /** * Response text used when the request chunk size line without chunk extension * cannot fit the buffer. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request target, the request field lines " \ "and the chunk size line exceeds the memory constraints of this web " \ "server.

    " \ "

    The request could be re-tried with a smaller " \ "chunk size, shorter field lines, a shorter request target or a shorter " \ "request method token.

    " \ "" #else #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG "" #endif /** * Response text used when the request header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_FOOTER_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target, the request field lines and the chunked trailer " \ "section exceeds the memory constraints of this web server.

    " \ "

    The request could be re-tried with a shorter chunked trailer " \ "section, shorter field lines, a shorter request target or " \ "a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_FOOTER_TOO_BIG "" #endif /** * Response text used when the request line has more then two whitespaces. */ #ifdef HAVE_MESSAGES #define RQ_LINE_TOO_MANY_WSP \ "" \ "Request broken" \ "The request line has more then two whitespaces." \ "" #else #define RQ_LINE_TOO_MANY_WSP "" #endif /** * Response text used when the request HTTP header has bare CR character * without LF character (and CR is not allowed to be treated as whitespace). */ #ifdef HAVE_MESSAGES #define BARE_CR_IN_HEADER \ "" \ "Request broken" \ "Request HTTP header has bare CR character without " \ "following LF character." \ "" #else #define BARE_CR_IN_HEADER "" #endif /** * Response text used when the request HTTP footer has bare CR character * without LF character (and CR is not allowed to be treated as whitespace). */ #ifdef HAVE_MESSAGES #define BARE_CR_IN_FOOTER \ "" \ "Request broken" \ "Request HTTP footer has bare CR character without " \ "following LF character." \ "" #else #define BARE_CR_IN_FOOTER "" #endif /** * Response text used when the request HTTP header has bare LF character * without CR character. */ #ifdef HAVE_MESSAGES #define BARE_LF_IN_HEADER \ "" \ "Request broken" \ "Request HTTP header has bare LF character without " \ "preceding CR character." \ "" #else #define BARE_LF_IN_HEADER "" #endif /** * Response text used when the request HTTP footer has bare LF character * without CR character. */ #ifdef HAVE_MESSAGES #define BARE_LF_IN_FOOTER \ "" \ "Request broken" \ "Request HTTP footer has bare LF character without " \ "preceding CR character." \ "" #else #define BARE_LF_IN_FOOTER "" #endif /** * Response text used when the request line has invalid characters in URI. */ #ifdef HAVE_MESSAGES #define RQ_TARGET_INVALID_CHAR \ "" \ "Request broken" \ "HTTP request has invalid characters in " \ "the request-target." \ "" #else #define RQ_TARGET_INVALID_CHAR "" #endif /** * Response text used when line folding is used in request headers. */ #ifdef HAVE_MESSAGES #define ERR_RSP_OBS_FOLD \ "" \ "Request broken" \ "Obsolete line folding is used in HTTP request header." \ "" #else #define ERR_RSP_OBS_FOLD "" #endif /** * Response text used when line folding is used in request footers. */ #ifdef HAVE_MESSAGES #define ERR_RSP_OBS_FOLD_FOOTER \ "" \ "Request broken" \ "Obsolete line folding is used in HTTP request footer." \ "" #else #define ERR_RSP_OBS_FOLD_FOOTER "" #endif /** * Response text used when the request has whitespace at the start * of the first header line. */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_BEFORE_HEADER \ "" \ "Request broken" \ "HTTP request has whitespace between the request line and " \ "the first header." \ "" #else #define ERR_RSP_WSP_BEFORE_HEADER "" #endif /** * Response text used when the request has whitespace at the start * of the first footer line. */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_BEFORE_FOOTER \ "" \ "Request broken" \ "First HTTP footer line has whitespace at the first " \ "position." \ "" #else #define ERR_RSP_WSP_BEFORE_FOOTER "" #endif /** * Response text used when the whitespace found before colon (inside header * name or between header name and colon). */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_IN_HEADER_NAME \ "" \ "Request broken" \ "HTTP request has whitespace before the first colon " \ "in header line." \ "" #else #define ERR_RSP_WSP_IN_HEADER_NAME "" #endif /** * Response text used when the whitespace found before colon (inside header * name or between header name and colon). */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_IN_FOOTER_NAME \ "" \ "Request broken" \ "HTTP request has whitespace before the first colon " \ "in footer line." \ "" #else #define ERR_RSP_WSP_IN_FOOTER_NAME "" #endif /** * Response text used when request header has invalid character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_INVALID_CHR_IN_HEADER \ "" \ "Request broken" \ "HTTP request has invalid character in header." \ "" #else #define ERR_RSP_INVALID_CHR_IN_HEADER "" #endif /** * Response text used when request header has invalid character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_INVALID_CHR_IN_FOOTER \ "" \ "Request broken" \ "HTTP request has invalid character in footer." \ "" #else #define ERR_RSP_INVALID_CHR_IN_FOOTER "" #endif /** * Response text used when request header has no colon character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_HEADER_WITHOUT_COLON \ "" \ "Request broken" \ "HTTP request header line has no colon character." \ "" #else #define ERR_RSP_HEADER_WITHOUT_COLON "" #endif /** * Response text used when request footer has no colon character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_FOOTER_WITHOUT_COLON \ "" \ "Request broken" \ "HTTP request footer line has no colon character." \ "" #else #define ERR_RSP_FOOTER_WITHOUT_COLON "" #endif /** * Response text used when request header has zero-length header (filed) name. */ #ifdef HAVE_MESSAGES #define ERR_RSP_EMPTY_HEADER_NAME \ "" \ "Request broken" \ "HTTP request header has empty header name." \ "" #else #define ERR_RSP_EMPTY_HEADER_NAME "" #endif /** * Response text used when request header has zero-length header (filed) name. */ #ifdef HAVE_MESSAGES #define ERR_RSP_EMPTY_FOOTER_NAME \ "" \ "Request broken" \ "HTTP request footer has empty footer name." \ "" #else #define ERR_RSP_EMPTY_FOOTER_NAME "" #endif /** * Response text used when the request (http header) does not * contain a "Host:" header and still claims to be HTTP 1.1. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define REQUEST_LACKS_HOST \ "" \ ""Host:" header required" \ "HTTP/1.1 request without "Host:"." \ "" #else #define REQUEST_LACKS_HOST "" #endif /** * Response text used when the request has unsupported "Transfer-Encoding:". */ #ifdef HAVE_MESSAGES #define REQUEST_UNSUPPORTED_TR_ENCODING \ "" \ "Unsupported Transfer-Encoding" \ "The Transfer-Encoding used in request is not supported." \ "" #else #define REQUEST_UNSUPPORTED_TR_ENCODING "" #endif /** * Response text used when the request has unsupported both headers: * "Transfer-Encoding:" and "Content-Length:" */ #ifdef HAVE_MESSAGES #define REQUEST_LENGTH_WITH_TR_ENCODING \ "" \ "Malformed request" \ "Wrong combination of the request headers: both Transfer-Encoding " \ "and Content-Length headers are used at the same time." \ "" #else #define REQUEST_LENGTH_WITH_TR_ENCODING "" #endif /** * Response text used when the request (http header) is * malformed. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define REQUEST_MALFORMED \ "Request malformed" \ "HTTP request is syntactically incorrect." #else #define REQUEST_MALFORMED "" #endif /** * Response text used when the request HTTP chunked encoding is * malformed. */ #ifdef HAVE_MESSAGES #define REQUEST_CHUNKED_MALFORMED \ "Request malformed" \ "HTTP chunked encoding is syntactically incorrect." #else #define REQUEST_CHUNKED_MALFORMED "" #endif /** * Response text used when the request HTTP chunk is too large. */ #ifdef HAVE_MESSAGES #define REQUEST_CHUNK_TOO_LARGE \ "Request content too large" \ "The chunk size used in HTTP chunked encoded " \ "request is too large." #else #define REQUEST_CHUNK_TOO_LARGE "" #endif /** * Response text used when the request HTTP content is too large. */ #ifdef HAVE_MESSAGES #define REQUEST_CONTENTLENGTH_TOOLARGE \ "Request content too large" \ "HTTP request has too large value for " \ "Content-Length header." #else #define REQUEST_CONTENTLENGTH_TOOLARGE "" #endif /** * Response text used when the request HTTP chunked encoding is * malformed. */ #ifdef HAVE_MESSAGES #define REQUEST_CONTENTLENGTH_MALFORMED \ "Request malformed" \ "HTTP request has wrong value for " \ "Content-Length header." #else #define REQUEST_CONTENTLENGTH_MALFORMED "" #endif /** * Response text used when there is an internal server error. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP \ "Internal server error" \ "Please ask the developer of this Web server to carefully " \ "read the GNU libmicrohttpd documentation about connection " \ "management and blocking." #else #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP "" #endif /** * Response text used when the request HTTP version is too old. */ #ifdef HAVE_MESSAGES #define REQ_HTTP_VER_IS_TOO_OLD \ "Requested HTTP version is not supported" \ "Requested HTTP version is too old and not " \ "supported." #else #define REQ_HTTP_VER_IS_TOO_OLD "" #endif /** * Response text used when the request HTTP version is not supported. */ #ifdef HAVE_MESSAGES #define REQ_HTTP_VER_IS_NOT_SUPPORTED \ "Requested HTTP version is not supported" \ "Requested HTTP version is not supported." #else #define REQ_HTTP_VER_IS_NOT_SUPPORTED "" #endif /** * sendfile() chuck size */ #define MHD_SENFILE_CHUNK_ (0x20000) /** * sendfile() chuck size for thread-per-connection */ #define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000) #ifdef HAVE_MESSAGES /** * Return text description for MHD_ERR_*_ codes * @param mhd_err_code the error code * @return pointer to static string with error description */ static const char * str_conn_error_ (ssize_t mhd_err_code) { switch (mhd_err_code) { case MHD_ERR_AGAIN_: return _ ("The operation would block, retry later"); case MHD_ERR_CONNRESET_: return _ ("The connection was forcibly closed by remote peer"); case MHD_ERR_NOTCONN_: return _ ("The socket is not connected"); case MHD_ERR_NOMEM_: return _ ("Not enough system resources to serve the request"); case MHD_ERR_BADF_: return _ ("Bad FD value"); case MHD_ERR_INVAL_: return _ ("Argument value is invalid"); case MHD_ERR_OPNOTSUPP_: return _ ("Argument value is not supported"); case MHD_ERR_PIPE_: return _ ("The socket is no longer available for sending"); case MHD_ERR_TLS_: return _ ("TLS encryption or decryption error"); default: break; /* Mute compiler warning */ } if (0 <= mhd_err_code) return _ ("Not an error code"); mhd_assert (0); /* Should never be reachable */ return _ ("Wrong error code value"); } #endif /* HAVE_MESSAGES */ /** * Allocate memory from connection's memory pool. * If memory pool doesn't have enough free memory but read or write buffer * have some unused memory, the size of the buffer will be reduced as needed. * @param connection the connection to use * @param size the size of allocated memory area * @return pointer to allocated memory region in the pool or * NULL if no memory is available */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size) { struct MHD_Connection *const c = connection; /* a short alias */ struct MemoryPool *const pool = c->pool; /* a short alias */ size_t need_to_be_freed = 0; /**< The required amount of additional free memory */ void *res; res = MHD_pool_try_alloc (pool, size, &need_to_be_freed); if (NULL != res) return res; if (MHD_pool_is_resizable_inplace (pool, c->write_buffer, c->write_buffer_size)) { if (c->write_buffer_size - c->write_buffer_append_offset >= need_to_be_freed) { char *buf; const size_t new_buf_size = c->write_buffer_size - need_to_be_freed; buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, new_buf_size); mhd_assert (c->write_buffer == buf); mhd_assert (c->write_buffer_append_offset <= new_buf_size); mhd_assert (c->write_buffer_send_offset <= new_buf_size); c->write_buffer_size = new_buf_size; c->write_buffer = buf; } else return NULL; } else if (MHD_pool_is_resizable_inplace (pool, c->read_buffer, c->read_buffer_size)) { if (c->read_buffer_size - c->read_buffer_offset >= need_to_be_freed) { char *buf; const size_t new_buf_size = c->read_buffer_size - need_to_be_freed; buf = MHD_pool_reallocate (pool, c->read_buffer, c->read_buffer_size, new_buf_size); mhd_assert (c->read_buffer == buf); mhd_assert (c->read_buffer_offset <= new_buf_size); c->read_buffer_size = new_buf_size; c->read_buffer = buf; } else return NULL; } else return NULL; res = MHD_pool_allocate (pool, size, true); mhd_assert (NULL != res); /* It has been checked that pool has enough space */ return res; } /** * Callback for receiving data from the socket. * * @param connection the MHD connection structure * @param other where to write received data to * @param i maximum size of other (in bytes) * @return positive value for number of bytes actually received or * negative value for error number MHD_ERR_xxx_ */ static ssize_t recv_param_adapter (struct MHD_Connection *connection, void *other, size_t i) { ssize_t ret; if ( (MHD_INVALID_SOCKET == connection->socket_fd) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } if (i > MHD_SCKT_SEND_MAX_SIZE_) i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */ ret = MHD_recv_ (connection->socket_fd, other, i); if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* Got EAGAIN --- no longer read-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if (i > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* EPOLL_SUPPORT */ return ret; } /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) { int ret; struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return -1; ret = 0; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) if (0 != (pos->kind & kind)) { ret++; if ( (NULL != iterator) && (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->value)) ) return ret; } return ret; } /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIteratorN iterator, void *iterator_cls) { int ret; struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return -1; ret = 0; if (NULL == iterator) for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (0 != (kind & pos->kind)) ret++; } else for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) if (0 != (kind & pos->kind)) { ret++; if (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->header_size, pos->value, pos->value_size)) return ret; } return ret; } /** * This function can be used to add an arbitrary entry to connection. * Internal version of #MHD_set_connection_value_n() without checking * of arguments values. * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ static enum MHD_Result MHD_set_connection_value_n_nocheck_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct MHD_HTTP_Req_Header *pos; pos = MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_HTTP_Res_Header)); if (NULL == pos) return MHD_NO; pos->header = key; pos->header_size = key_size; pos->value = value; pos->value_size = value_size; pos->kind = kind; pos->next = NULL; /* append 'pos' to the linked list of headers */ if (NULL == connection->rq.headers_received_tail) { connection->rq.headers_received = pos; connection->rq.headers_received_tail = pos; } else { connection->rq.headers_received_tail->next = pos; connection->rq.headers_received_tail = pos; } return MHD_YES; } /** * This function can be used to add an arbitrary entry to connection. * This function could add entry with binary zero, which is allowed * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is * recommended to use #MHD_set_connection_value. * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { if ( (MHD_GET_ARGUMENT_KIND != kind) && ( ((key ? strlen (key) : 0) != key_size) || ((value ? strlen (value) : 0) != value_size) ) ) return MHD_NO; /* binary zero is allowed only in GET arguments */ return MHD_set_connection_value_n_nocheck_ (connection, kind, key, key_size, value, value_size); } /** * This function can be used to add an entry to the HTTP headers of a * connection (so that the #MHD_get_connection_values function will * return them -- and the `struct MHD_PostProcessor` will also see * them). This maybe required in certain situations (see Mantis * #1399) where (broken) HTTP implementations fail to supply values * needed by the post processor (or other parts of the application). * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value * @param value the value itself * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value) { return MHD_set_connection_value_n_nocheck_ (connection, kind, key, NULL != key ? strlen (key) : 0, value, NULL != value ? strlen (value) : 0); } /** * Get a particular header value. If multiple * values match the kind, return any one of them. * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @return NULL if no such item was found * @ingroup request */ _MHD_EXTERN const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key) { const char *value; value = NULL; (void) MHD_lookup_connection_value_n (connection, kind, key, (NULL == key) ? 0 : strlen (key), &value, NULL); return value; } /** * Get a particular header value. If multiple * values match the kind, return any one of them. * @note Since MHD_VERSION 0x00096304 * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @param key_size the length of @a key in bytes * @param[out] value_ptr the pointer to variable, which will be set to found value, * will not be updated if key not found, * could be NULL to just check for presence of @a key * @param[out] value_size_ptr the pointer variable, which will set to found value, * will not be updated if key not found, * could be NULL * @return #MHD_YES if key is found, * #MHD_NO otherwise. * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) { struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return MHD_NO; if (NULL == key) { for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ( (0 != (kind & pos->kind)) && (NULL == pos->header) ) break; } } else { for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ( (0 != (kind & pos->kind)) && (key_size == pos->header_size) && ( (key == pos->header) || (MHD_str_equal_caseless_bin_n_ (key, pos->header, key_size) ) ) ) break; } } if (NULL == pos) return MHD_NO; if (NULL != value_ptr) *value_ptr = pos->value; if (NULL != value_size_ptr) *value_size_ptr = pos->value_size; return MHD_YES; } /** * Check whether request header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param connection the connection to get values from * @param header the header name * @param header_len the length of header, not including optional * terminating null-character * @param token the token to find * @param token_len the length of token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ static bool MHD_lookup_header_token_ci (const struct MHD_Connection *connection, const char *header, size_t header_len, const char *token, size_t token_len) { struct MHD_HTTP_Req_Header *pos; if ((NULL == connection) || (NULL == header) || (0 == header[0]) || (NULL == token) || (0 == token[0])) return false; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ((0 != (pos->kind & MHD_HEADER_KIND)) && (header_len == pos->header_size) && ( (header == pos->header) || (MHD_str_equal_caseless_bin_n_ (header, pos->header, header_len)) ) && (MHD_str_has_token_caseless_ (pos->value, token, token_len))) return true; } return false; } /** * Check whether request header contains particular static @a tkn. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param c the connection to get values from * @param h the static string of header name * @param tkn the static string of token to find * @return true if token is found in specified header, * false otherwise */ #define MHD_lookup_header_s_token_ci(c,h,tkn) \ MHD_lookup_header_token_ci ((c),(h),MHD_STATICSTR_LEN_ (h), \ (tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Do we (still) need to send a 100 continue * message for this connection? * * @param connection connection to test * @return false if we don't need 100 CONTINUE, true if we do */ static bool need_100_continue (struct MHD_Connection *connection) { const char *expect; if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) return false; if (0 == connection->rq.remaining_upload_size) return false; if (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_EXPECT, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_EXPECT), &expect, NULL)) return false; if (MHD_str_equal_caseless_ (expect, "100-continue")) return true; return false; } /** * Mark connection as "closed". * @remark To be called from any thread. * * @param connection connection to close */ void MHD_connection_mark_closed_ (struct MHD_Connection *connection) { const struct MHD_Daemon *daemon = connection->daemon; if (0 == (daemon->options & MHD_USE_TURBO)) { #ifdef HTTPS_SUPPORT /* For TLS connection use shutdown of TLS layer * and do not shutdown TCP socket. This give more * chances to send TLS closure data to remote side. * Closure of TLS layer will be interpreted by * remote side as end of transmission. */ if (0 != (daemon->options & MHD_USE_TLS)) { if (! MHD_tls_connection_shutdown (connection)) shutdown (connection->socket_fd, SHUT_WR); } else /* Combined with next 'shutdown()'. */ #endif /* HTTPS_SUPPORT */ shutdown (connection->socket_fd, SHUT_WR); } connection->state = MHD_CONNECTION_CLOSED; connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; } /** * Close the given connection and give the * specified termination code to the user. * @remark To be called only from thread that * process connection's recv(), send() and response. * * @param connection connection to close * @param termination_code termination reason to give */ void MHD_connection_close_ (struct MHD_Connection *connection, enum MHD_RequestTerminationCode termination_code) { struct MHD_Daemon *daemon = connection->daemon; struct MHD_Response *resp = connection->rp.response; mhd_assert (! connection->suspended); #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ if ( (NULL != daemon->notify_completed) && (connection->rq.client_aware) ) daemon->notify_completed (daemon->notify_completed_cls, connection, &connection->rq.client_context, termination_code); connection->rq.client_aware = false; if (NULL != resp) { connection->rp.response = NULL; MHD_destroy_response (resp); } if (NULL != connection->pool) { MHD_pool_destroy (connection->pool); connection->pool = NULL; } MHD_connection_mark_closed_ (connection); } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Stop TLS forwarding on upgraded connection and * reflect remote disconnect state to socketpair. * @remark In thread-per-connection mode this function * can be called from any thread, in other modes this * function must be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the upgraded connection */ void MHD_connection_finish_forward_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; struct MHD_UpgradeResponseHandle *urh = connection->urh; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_USE_TLS)) return; /* Nothing to do with non-TLS connection. */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) DLL_remove (daemon->urh_head, daemon->urh_tail, urh); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, connection->socket_fd, NULL)) ) { MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); } if (urh->in_eready_list) { EDLL_remove (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = false; } #endif /* EPOLL_SUPPORT */ if (MHD_INVALID_SOCKET != urh->mhd.socket) { #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, urh->mhd.socket, NULL)) ) { MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); } #endif /* EPOLL_SUPPORT */ /* Reflect remote disconnect to application by breaking * socketpair connection. */ shutdown (urh->mhd.socket, SHUT_RDWR); } /* Socketpair sockets will remain open as they will be * used with MHD_UPGRADE_ACTION_CLOSE. They will be * closed by cleanup_upgraded_connection() during * connection's final cleanup. */ } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT*/ /** * A serious error occurred, close the * connection (and notify the application). * * @param connection connection to close with error * @param emsg error message (can be NULL) */ static void connection_close_error (struct MHD_Connection *connection, const char *emsg) { connection->stop_with_error = true; connection->discard_request = true; #ifdef HAVE_MESSAGES if (NULL != emsg) MHD_DLOG (connection->daemon, "%s\n", emsg); #else /* ! HAVE_MESSAGES */ (void) emsg; /* Mute compiler warning. */ #endif /* ! HAVE_MESSAGES */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); } /** * Macro to only include error message in call to * #connection_close_error() if we have HAVE_MESSAGES. */ #ifdef HAVE_MESSAGES #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, emsg) #else #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, NULL) #endif /** * Prepare the response buffer of this connection for * sending. Assumes that the response mutex is * already held. If the transmission is complete, * this function may close the socket (and return * #MHD_NO). * * @param connection the connection * @return #MHD_NO if readying the response failed (the * lock on the response will have been released already * in this case). */ static enum MHD_Result try_ready_normal_body (struct MHD_Connection *connection) { ssize_t ret; struct MHD_Response *response; response = connection->rp.response; mhd_assert (connection->rp.props.send_reply_body); if ( (0 == response->total_size) || /* TODO: replace the next check with assert */ (connection->rp.rsp_write_position == response->total_size) ) return MHD_YES; /* 0-byte response is always ready */ if (NULL != response->data_iov) { size_t copy_size; if (NULL != connection->rp.resp_iov.iov) return MHD_YES; copy_size = response->data_iovcnt * sizeof(MHD_iovec_); connection->rp.resp_iov.iov = MHD_connection_alloc_memory_ (connection, copy_size); if (NULL == connection->rp.resp_iov.iov) { MHD_mutex_unlock_chk_ (&response->mutex); /* not enough memory */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (out of memory).")); return MHD_NO; } memcpy (connection->rp.resp_iov.iov, response->data_iov, copy_size); connection->rp.resp_iov.cnt = response->data_iovcnt; connection->rp.resp_iov.sent = 0; return MHD_YES; } if (NULL == response->crc) return MHD_YES; if ( (response->data_start <= connection->rp.rsp_write_position) && (response->data_size + response->data_start > connection->rp.rsp_write_position) ) return MHD_YES; /* response already ready */ #if defined(_MHD_HAVE_SENDFILE) if (MHD_resp_sender_sendfile == connection->rp.resp_sender) { /* will use sendfile, no need to bother response crc */ return MHD_YES; } #endif /* _MHD_HAVE_SENDFILE */ ret = response->crc (response->crc_cls, connection->rp.rsp_write_position, (char *) response->data, (size_t) MHD_MIN ((uint64_t) response->data_buffer_size, response->total_size - connection->rp.rsp_write_position)); if (0 > ret) { /* either error or http 1.0 transfer, close socket! */ /* TODO: do not update total size, check whether response * was really with unknown size */ response->total_size = connection->rp.rsp_write_position; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif if (MHD_CONTENT_READER_END_OF_STREAM == ret) MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_COMPLETED_OK); else CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application reported " \ "error generating data).")); return MHD_NO; } response->data_start = connection->rp.rsp_write_position; response->data_size = (size_t) ret; if (0 == ret) { connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return MHD_NO; } return MHD_YES; } /** * Prepare the response buffer of this connection for sending. * Assumes that the response mutex is already held. If the * transmission is complete, this function may close the socket (and * return #MHD_NO). * * @param connection the connection * @param[out] p_finished the pointer to variable that will be set to "true" * when application returned indication of the end * of the stream * @return #MHD_NO if readying the response failed */ static enum MHD_Result try_ready_chunked_body (struct MHD_Connection *connection, bool *p_finished) { ssize_t ret; struct MHD_Response *response; static const size_t max_chunk = 0xFFFFFF; char chunk_hdr[6]; /* 6: max strlen of "FFFFFF" */ /* "FFFFFF" + "\r\n" */ static const size_t max_chunk_hdr_len = sizeof(chunk_hdr) + 2; /* "FFFFFF" + "\r\n" + "\r\n" (chunk termination) */ static const size_t max_chunk_overhead = sizeof(chunk_hdr) + 2 + 2; size_t chunk_hdr_len; uint64_t left_to_send; size_t size_to_fill; response = connection->rp.response; mhd_assert (NULL != response->crc || NULL != response->data); mhd_assert (0 == connection->write_buffer_append_offset); /* The buffer must be reasonably large enough */ if (128 > connection->write_buffer_size) { size_t size; size = connection->write_buffer_size + MHD_pool_get_free (connection->pool); if (128 > size) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif /* not enough memory */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (out of memory).")); return MHD_NO; } /* Limit the buffer size to the largest usable size for chunks */ if ( (max_chunk + max_chunk_overhead) < size) size = max_chunk + max_chunk_overhead; mhd_assert ((NULL == connection->write_buffer) || \ MHD_pool_is_resizable_inplace (connection->pool, \ connection->write_buffer, \ connection->write_buffer_size)); connection->write_buffer = MHD_pool_reallocate (connection->pool, connection->write_buffer, connection->write_buffer_size, size); mhd_assert (NULL != connection->write_buffer); connection->write_buffer_size = size; } mhd_assert (max_chunk_overhead < connection->write_buffer_size); if (MHD_SIZE_UNKNOWN == response->total_size) left_to_send = MHD_SIZE_UNKNOWN; else left_to_send = response->total_size - connection->rp.rsp_write_position; size_to_fill = connection->write_buffer_size - max_chunk_overhead; /* Limit size for the callback to the max usable size */ if (max_chunk < size_to_fill) size_to_fill = max_chunk; if (left_to_send < size_to_fill) size_to_fill = (size_t) left_to_send; if (0 == left_to_send) /* nothing to send, don't bother calling crc */ ret = MHD_CONTENT_READER_END_OF_STREAM; else if ( (response->data_start <= connection->rp.rsp_write_position) && (response->data_start + response->data_size > connection->rp.rsp_write_position) ) { /* difference between rsp_write_position and data_start is less than data_size which is size_t type, no need to check for overflow */ const size_t data_write_offset = (size_t) (connection->rp.rsp_write_position - response->data_start); /* buffer already ready, use what is there for the chunk */ mhd_assert (SSIZE_MAX >= (response->data_size - data_write_offset)); mhd_assert (response->data_size >= data_write_offset); ret = (ssize_t) (response->data_size - data_write_offset); if ( ((size_t) ret) > size_to_fill) ret = (ssize_t) size_to_fill; memcpy (&connection->write_buffer[max_chunk_hdr_len], &response->data[data_write_offset], (size_t) ret); } else { if (NULL == response->crc) { /* There is no way to reach this code */ #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("No callback for the chunked data.")); return MHD_NO; } ret = response->crc (response->crc_cls, connection->rp.rsp_write_position, &connection->write_buffer[max_chunk_hdr_len], size_to_fill); } if (MHD_CONTENT_READER_END_WITH_ERROR == ret) { /* error, close socket! */ /* TODO: remove update of the response size */ response->total_size = connection->rp.rsp_write_position; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application error " \ "generating response).")); return MHD_NO; } if (MHD_CONTENT_READER_END_OF_STREAM == ret) { *p_finished = true; /* TODO: remove update of the response size */ response->total_size = connection->rp.rsp_write_position; return MHD_YES; } if (0 == ret) { connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return MHD_NO; } if (size_to_fill < (size_t) ret) { #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application returned " \ "more data than requested).")); return MHD_NO; } chunk_hdr_len = MHD_uint32_to_strx ((uint32_t) ret, chunk_hdr, sizeof(chunk_hdr)); mhd_assert (chunk_hdr_len != 0); mhd_assert (chunk_hdr_len < sizeof(chunk_hdr)); *p_finished = false; connection->write_buffer_send_offset = (max_chunk_hdr_len - (chunk_hdr_len + 2)); memcpy (connection->write_buffer + connection->write_buffer_send_offset, chunk_hdr, chunk_hdr_len); connection->write_buffer[max_chunk_hdr_len - 2] = '\r'; connection->write_buffer[max_chunk_hdr_len - 1] = '\n'; connection->write_buffer[max_chunk_hdr_len + (size_t) ret] = '\r'; connection->write_buffer[max_chunk_hdr_len + (size_t) ret + 1] = '\n'; connection->rp.rsp_write_position += (size_t) ret; connection->write_buffer_append_offset = max_chunk_hdr_len + (size_t) ret + 2; return MHD_YES; } /** * Are we allowed to keep the given connection alive? * We can use the TCP stream for a second request if the connection * is HTTP 1.1 and the "Connection" header either does not exist or * is not set to "close", or if the connection is HTTP 1.0 and the * "Connection" header is explicitly set to "keep-alive". * If no HTTP version is specified (or if it is not 1.0 or 1.1), we * definitively close the connection. If the "Connection" header is * not exactly "close" or "keep-alive", we proceed to use the default * for the respective HTTP version. * If response has HTTP/1.0 flag or has "Connection: close" header * then connection must be closed. * If full request has not been read then connection must be closed * as well. * * @param connection the connection to check for keepalive * @return MHD_CONN_USE_KEEPALIVE if (based on the request and the response), * a keepalive is legal, * MHD_CONN_MUST_CLOSE if connection must be closed after sending * complete reply, * MHD_CONN_MUST_UPGRADE if connection must be upgraded. */ static enum MHD_ConnKeepAlive keepalive_possible (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ mhd_assert (NULL != r); if (MHD_CONN_MUST_CLOSE == c->keepalive) return MHD_CONN_MUST_CLOSE; #ifdef UPGRADE_SUPPORT /* TODO: Move below the next check when MHD stops closing connections * when response is queued in first callback */ if (NULL != r->upgrade_handler) { /* No "close" token is enforced by 'add_response_header_connection()' */ mhd_assert (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); /* Valid HTTP version is enforced by 'MHD_queue_response()' */ mhd_assert (MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver)); mhd_assert (! c->stop_with_error); return MHD_CONN_MUST_UPGRADE; } #endif /* UPGRADE_SUPPORT */ mhd_assert ( (! c->stop_with_error) || (c->discard_request)); if ((c->read_closed) || (c->discard_request)) return MHD_CONN_MUST_CLOSE; if (0 != (r->flags & MHD_RF_HTTP_1_0_COMPATIBLE_STRICT)) return MHD_CONN_MUST_CLOSE; if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)) return MHD_CONN_MUST_CLOSE; if (! MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver)) return MHD_CONN_MUST_CLOSE; if (MHD_lookup_header_s_token_ci (c, MHD_HTTP_HEADER_CONNECTION, "close")) return MHD_CONN_MUST_CLOSE; if ((MHD_HTTP_VER_1_0 == connection->rq.http_ver) || (0 != (connection->rp.response->flags & MHD_RF_HTTP_1_0_SERVER))) { if (MHD_lookup_header_s_token_ci (connection, MHD_HTTP_HEADER_CONNECTION, "Keep-Alive")) return MHD_CONN_USE_KEEPALIVE; return MHD_CONN_MUST_CLOSE; } if (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver)) return MHD_CONN_USE_KEEPALIVE; return MHD_CONN_MUST_CLOSE; } /** * Produce time stamp. * * Result is NOT null-terminated. * Result is always 29 bytes long. * * @param[out] date where to write the time stamp, with * at least 29 bytes available space. */ static bool get_date_str (char *date) { static const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char *const mons[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static const size_t buf_len = 29; struct tm now; time_t t; const char *src; #if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \ ! defined(HAVE_GMTIME_R) struct tm *pNow; #endif if ((time_t) -1 == time (&t)) return false; #if defined(HAVE_C11_GMTIME_S) if (NULL == gmtime_s (&t, &now)) return false; #elif defined(HAVE_W32_GMTIME_S) if (0 != gmtime_s (&now, &t)) return false; #elif defined(HAVE_GMTIME_R) if (NULL == gmtime_r (&t, &now)) return false; #else pNow = gmtime (&t); if (NULL == pNow) return false; now = *pNow; #endif /* Day of the week */ src = days[now.tm_wday % 7]; date[0] = src[0]; date[1] = src[1]; date[2] = src[2]; date[3] = ','; date[4] = ' '; /* Day of the month */ if (2 != MHD_uint8_to_str_pad ((uint8_t) now.tm_mday, 2, date + 5, buf_len - 5)) return false; date[7] = ' '; /* Month */ src = mons[now.tm_mon % 12]; date[8] = src[0]; date[9] = src[1]; date[10] = src[2]; date[11] = ' '; /* Year */ if (4 != MHD_uint16_to_str ((uint16_t) (1900 + now.tm_year), date + 12, buf_len - 12)) return false; date[16] = ' '; /* Time */ MHD_uint8_to_str_pad ((uint8_t) now.tm_hour, 2, date + 17, buf_len - 17); date[19] = ':'; MHD_uint8_to_str_pad ((uint8_t) now.tm_min, 2, date + 20, buf_len - 20); date[22] = ':'; MHD_uint8_to_str_pad ((uint8_t) now.tm_sec, 2, date + 23, buf_len - 23); date[25] = ' '; date[26] = 'G'; date[27] = 'M'; date[28] = 'T'; return true; } /** * Produce HTTP DATE header. * Result is always 37 bytes long (plus one terminating null). * * @param[out] header where to write the header, with * at least 38 bytes available space. */ static bool get_date_header (char *header) { if (! get_date_str (header + 6)) { header[0] = 0; return false; } header[0] = 'D'; header[1] = 'a'; header[2] = 't'; header[3] = 'e'; header[4] = ':'; header[5] = ' '; header[35] = '\r'; header[36] = '\n'; header[37] = 0; return true; } /** * Try growing the read buffer. We initially claim half the available * buffer space for the read buffer (the other half being left for * management data structures; the write buffer can in the end take * virtually everything as the read buffer can be reduced to the * minimum necessary at that point. * * @param connection the connection * @param required set to 'true' if grow is required, i.e. connection * will fail if no additional space is granted * @return 'true' on success, 'false' on failure */ static bool try_grow_read_buffer (struct MHD_Connection *connection, bool required) { size_t new_size; size_t avail_size; const size_t def_grow_size = connection->daemon->pool_increment; void *rb; avail_size = MHD_pool_get_free (connection->pool); if (0 == avail_size) return false; /* No more space available */ if (0 == connection->read_buffer_size) new_size = avail_size / 2; /* Use half of available buffer for reading */ else { size_t grow_size; grow_size = avail_size / 8; if (def_grow_size > grow_size) { /* Shortage of space */ const size_t left_free = connection->read_buffer_size - connection->read_buffer_offset; mhd_assert (connection->read_buffer_size >= \ connection->read_buffer_offset); if ((def_grow_size <= grow_size + left_free) && (left_free < def_grow_size)) grow_size = def_grow_size - left_free; /* Use precise 'def_grow_size' for new free space */ else if (! required) return false; /* Grow is not mandatory, leave some space in pool */ else { /* Shortage of space, but grow is mandatory */ const size_t small_inc = ((MHD_BUF_INC_SIZE > def_grow_size) ? def_grow_size : MHD_BUF_INC_SIZE) / 8; if (small_inc < avail_size) grow_size = small_inc; else grow_size = avail_size; } } new_size = connection->read_buffer_size + grow_size; } /* Make sure that read buffer will not be moved */ if ((NULL != connection->read_buffer) && ! MHD_pool_is_resizable_inplace (connection->pool, connection->read_buffer, connection->read_buffer_size)) { mhd_assert (0); return false; } /* we can actually grow the buffer, do it! */ rb = MHD_pool_reallocate (connection->pool, connection->read_buffer, connection->read_buffer_size, new_size); if (NULL == rb) { /* This should NOT be possible: we just computed 'new_size' so that it should fit. If it happens, somehow our read buffer is not in the right position in the pool, say because someone called MHD_pool_allocate() without 'from_end' set to 'true'? Anyway, should be investigated! (Ideally provide all data from *pool and connection->read_buffer and new_size for debugging). */ mhd_assert (0); return false; } mhd_assert (connection->read_buffer == rb); connection->read_buffer = rb; mhd_assert (NULL != connection->read_buffer); connection->read_buffer_size = new_size; return true; } /** * Shrink connection read buffer to the zero size of free space in the buffer * @param connection the connection whose read buffer is being manipulated */ static void connection_shrink_read_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ void *new_buf; if ((NULL == c->read_buffer) || (0 == c->read_buffer_size)) { mhd_assert (0 == c->read_buffer_size); mhd_assert (0 == c->read_buffer_offset); return; } mhd_assert (c->read_buffer_offset <= c->read_buffer_size); if (0 == c->read_buffer_offset) { MHD_pool_deallocate (c->pool, c->read_buffer, c->read_buffer_size); c->read_buffer = NULL; c->read_buffer_size = 0; } else { mhd_assert (MHD_pool_is_resizable_inplace (c->pool, c->read_buffer, \ c->read_buffer_size)); new_buf = MHD_pool_reallocate (c->pool, c->read_buffer, c->read_buffer_size, c->read_buffer_offset); mhd_assert (c->read_buffer == new_buf); c->read_buffer = new_buf; c->read_buffer_size = c->read_buffer_offset; } } /** * Allocate the maximum available amount of memory from MemoryPool * for write buffer. * @param connection the connection whose write buffer is being manipulated * @return the size of the free space in the write buffer */ static size_t connection_maximize_write_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MemoryPool *const pool = connection->pool; void *new_buf; size_t new_size; size_t free_size; mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size)); mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset); mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset); free_size = MHD_pool_get_free (pool); if (0 != free_size) { new_size = c->write_buffer_size + free_size; /* This function must not move the buffer position. * MHD_pool_reallocate () may return the new position only if buffer was * allocated 'from_end' or is not the last allocation, * which should not happen. */ mhd_assert ((NULL == c->write_buffer) || \ MHD_pool_is_resizable_inplace (pool, c->write_buffer, \ c->write_buffer_size)); new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, new_size); mhd_assert ((c->write_buffer == new_buf) || (NULL == c->write_buffer)); c->write_buffer = new_buf; c->write_buffer_size = new_size; if (c->write_buffer_send_offset == c->write_buffer_append_offset) { /* All data have been sent, reset offsets to zero. */ c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; } } return c->write_buffer_size - c->write_buffer_append_offset; } #if 0 /* disable unused function */ /** * Shrink connection write buffer to the size of unsent data. * * @note: The number of calls of this function should be limited to avoid extra * zeroing of the memory. * @param connection the connection whose write buffer is being manipulated * @param connection the connection to manipulate write buffer */ static void connection_shrink_write_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MemoryPool *const pool = connection->pool; void *new_buf; mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size)); mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset); mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset); if ( (NULL == c->write_buffer) || (0 == c->write_buffer_size)) { mhd_assert (0 == c->write_buffer_append_offset); mhd_assert (0 == c->write_buffer_send_offset); c->write_buffer = NULL; return; } if (c->write_buffer_append_offset == c->write_buffer_size) return; new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, c->write_buffer_append_offset); mhd_assert ((c->write_buffer == new_buf) || \ (0 == c->write_buffer_append_offset)); c->write_buffer_size = c->write_buffer_append_offset; if (0 == c->write_buffer_size) c->write_buffer = NULL; else c->write_buffer = new_buf; } #endif /* unused function */ /** * Switch connection from recv mode to send mode. * * Current request header or body will not be read anymore, * response must be assigned to connection. * @param connection the connection to prepare for sending. */ static void connection_switch_from_recv_to_send (struct MHD_Connection *connection) { /* Read buffer is not needed for this request, shrink it.*/ connection_shrink_read_buffer (connection); } /** * This enum type describes requirements for reply body and reply bode-specific * headers (namely Content-Length, Transfer-Encoding). */ enum replyBodyUse { /** * No reply body allowed. * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are * not allowed as well. */ RP_BODY_NONE = 0, /** * Do not send reply body. * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are * allowed, but optional. */ RP_BODY_HEADERS_ONLY = 1, /** * Send reply body and * reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked'. * Reply body headers are required. */ RP_BODY_SEND = 2 }; /** * Check whether reply body must be used. * * If reply body is needed, it could be zero-sized. * * @param connection the connection to check * @param rcode the response code * @return enum value indicating whether response body can be used and * whether response body length headers are allowed or required. * @sa is_reply_body_header_needed() */ static enum replyBodyUse is_reply_body_needed (struct MHD_Connection *connection, unsigned int rcode) { struct MHD_Connection *const c = connection; /**< a short alias */ mhd_assert (100 <= rcode); mhd_assert (999 >= rcode); if (199 >= rcode) return RP_BODY_NONE; if (MHD_HTTP_NO_CONTENT == rcode) return RP_BODY_NONE; #if 0 /* This check is not needed as upgrade handler is used only with code 101 */ #ifdef UPGRADE_SUPPORT if (NULL != rp.response->upgrade_handler) return RP_BODY_NONE; #endif /* UPGRADE_SUPPORT */ #endif #if 0 /* CONNECT is not supported by MHD */ /* Successful responses for connect requests are filtered by * MHD_queue_response() */ if ( (MHD_HTTP_MTHD_CONNECT == c->rq.http_mthd) && (2 == rcode / 100) ) return false; /* Actually pass-through CONNECT is not supported by MHD */ #endif /* Reply body headers could be used. * Check whether reply body itself must be used. */ if (MHD_HTTP_MTHD_HEAD == c->rq.http_mthd) return RP_BODY_HEADERS_ONLY; if (MHD_HTTP_NOT_MODIFIED == rcode) return RP_BODY_HEADERS_ONLY; /* Reply body must be sent. The body may have zero length, but body size * must be indicated by headers ('Content-Length:' or * 'Transfer-Encoding: chunked'). */ return RP_BODY_SEND; } /** * Setup connection reply properties. * * Reply properties include presence of reply body, transfer-encoding * type and other. * * @param connection to connection to process */ static void setup_reply_properties (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ enum replyBodyUse use_rp_body; bool use_chunked; mhd_assert (NULL != r); /* ** Adjust reply properties ** */ c->keepalive = keepalive_possible (c); use_rp_body = is_reply_body_needed (c, c->rp.responseCode); c->rp.props.send_reply_body = (use_rp_body > RP_BODY_HEADERS_ONLY); c->rp.props.use_reply_body_headers = (use_rp_body >= RP_BODY_HEADERS_ONLY); #ifdef UPGRADE_SUPPORT mhd_assert ( (NULL == r->upgrade_handler) || (RP_BODY_NONE == use_rp_body) ); #endif /* UPGRADE_SUPPORT */ if (c->rp.props.use_reply_body_headers) { if ((MHD_SIZE_UNKNOWN == r->total_size) || (0 != (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))) { /* Use chunked reply encoding if possible */ /* Check whether chunked encoding is supported by the client */ if (! MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver)) use_chunked = false; /* Check whether chunked encoding is allowed for the reply */ else if (0 != (r->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT | MHD_RF_HTTP_1_0_SERVER))) use_chunked = false; else /* If chunked encoding is supported and allowed, and response size * is unknown, use chunked even for non-Keep-Alive connections. * See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 * Also use chunked if it is enforced by application and supported by * the client. */ use_chunked = true; } else use_chunked = false; if ( (MHD_SIZE_UNKNOWN == r->total_size) && (! use_chunked) ) { /* End of the stream is indicated by closure */ c->keepalive = MHD_CONN_MUST_CLOSE; } } else use_chunked = false; /* chunked encoding cannot be used without body */ c->rp.props.chunked = use_chunked; #ifdef _DEBUG c->rp.props.set = true; #endif /* _DEBUG */ } /** * Check whether queued response is suitable for @a connection. * @param connection to connection to check */ static void check_connection_reply (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ mhd_assert (c->rp.props.set); #ifdef HAVE_MESSAGES if ( (! c->rp.props.use_reply_body_headers) && (0 != r->total_size) ) { MHD_DLOG (c->daemon, _ ("This reply with response code %u cannot use reply body. " "Non-empty response body is ignored and not used.\n"), (unsigned) (c->rp.responseCode)); } if ( (! c->rp.props.use_reply_body_headers) && (0 != (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) ) { MHD_DLOG (c->daemon, _ ("This reply with response code %u cannot use reply body. " "Application defined \"Content-Length\" header violates" "HTTP specification.\n"), (unsigned) (c->rp.responseCode)); } #else (void) c; /* Mute compiler warning */ (void) r; /* Mute compiler warning */ #endif } /** * Append data to the buffer if enough space is available, * update position. * @param[out] buf the buffer to append data to * @param[in,out] ppos the pointer to position in the @a buffer * @param buf_size the size of the @a buffer * @param append the data to append * @param append_size the size of the @a append * @return true if data has been added and position has been updated, * false if not enough space is available */ static bool buffer_append (char *buf, size_t *ppos, size_t buf_size, const char *append, size_t append_size) { mhd_assert (NULL != buf); /* Mute static analyzer */ if (buf_size < *ppos + append_size) return false; memcpy (buf + *ppos, append, append_size); *ppos += append_size; return true; } /** * Append static string to the buffer if enough space is available, * update position. * @param[out] buf the buffer to append data to * @param[in,out] ppos the pointer to position in the @a buffer * @param buf_size the size of the @a buffer * @param str the static string to append * @return true if data has been added and position has been updated, * false if not enough space is available */ #define buffer_append_s(buf,ppos,buf_size,str) \ buffer_append (buf,ppos,buf_size,str, MHD_STATICSTR_LEN_ (str)) /** * Add user-defined headers from response object to * the text buffer. * * @param buf the buffer to add headers to * @param ppos the pointer to the position in the @a buf * @param buf_size the size of the @a buf * @param response the response * @param filter_transf_enc skip "Transfer-Encoding" header if any * @param filter_content_len skip "Content-Length" header if any * @param add_close add "close" token to the * "Connection:" header (if any), ignored if no "Connection:" * header was added by user or if "close" token is already * present in "Connection:" header * @param add_keep_alive add "Keep-Alive" token to the * "Connection:" header (if any) * @return true if succeed, * false if buffer is too small */ static bool add_user_headers (char *buf, size_t *ppos, size_t buf_size, struct MHD_Response *response, bool filter_transf_enc, bool filter_content_len, bool add_close, bool add_keep_alive) { struct MHD_Response *const r = response; /**< a short alias */ struct MHD_HTTP_Res_Header *hdr; /**< Iterates through User-specified headers */ size_t el_size; /**< the size of current element to be added to the @a buf */ mhd_assert (! add_close || ! add_keep_alive); if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) filter_transf_enc = false; /* No such header */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) filter_content_len = false; /* No such header */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { add_close = false; /* No such header */ add_keep_alive = false; /* No such header */ } else if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)) add_close = false; /* "close" token was already set */ for (hdr = r->first_header; NULL != hdr; hdr = hdr->next) { size_t initial_pos = *ppos; if (MHD_HEADER_KIND != hdr->kind) continue; if (filter_transf_enc) { /* Need to filter-out "Transfer-Encoding" */ if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) == hdr->header_size) && (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_TRANSFER_ENCODING, hdr->header, hdr->header_size)) ) { filter_transf_enc = false; /* There is the only one such header */ continue; /* Skip "Transfer-Encoding" header */ } } if (filter_content_len) { /* Need to filter-out "Content-Length" */ if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) == hdr->header_size) && (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH, hdr->header, hdr->header_size)) ) { /* Reset filter flag if only one header is allowed */ filter_transf_enc = (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)); continue; /* Skip "Content-Length" header */ } } /* Add user header */ el_size = hdr->header_size + 2 + hdr->value_size + 2; if (buf_size < *ppos + el_size) return false; memcpy (buf + *ppos, hdr->header, hdr->header_size); (*ppos) += hdr->header_size; buf[(*ppos)++] = ':'; buf[(*ppos)++] = ' '; if (add_close || add_keep_alive) { /* "Connection:" header must be always the first one */ mhd_assert (MHD_str_equal_caseless_n_ (hdr->header, \ MHD_HTTP_HEADER_CONNECTION, \ hdr->header_size)); if (add_close) { el_size += MHD_STATICSTR_LEN_ ("close, "); if (buf_size < initial_pos + el_size) return false; memcpy (buf + *ppos, "close, ", MHD_STATICSTR_LEN_ ("close, ")); *ppos += MHD_STATICSTR_LEN_ ("close, "); } else { el_size += MHD_STATICSTR_LEN_ ("Keep-Alive, "); if (buf_size < initial_pos + el_size) return false; memcpy (buf + *ppos, "Keep-Alive, ", MHD_STATICSTR_LEN_ ("Keep-Alive, ")); *ppos += MHD_STATICSTR_LEN_ ("Keep-Alive, "); } add_close = false; add_keep_alive = false; } if (0 != hdr->value_size) memcpy (buf + *ppos, hdr->value, hdr->value_size); *ppos += hdr->value_size; buf[(*ppos)++] = '\r'; buf[(*ppos)++] = '\n'; mhd_assert (initial_pos + el_size == (*ppos)); } return true; } /** * Allocate the connection's write buffer and fill it with all of the * headers from the response. * Required headers are added here. * * @param connection the connection * @return #MHD_YES on success, #MHD_NO on failure (out of memory) */ static enum MHD_Result build_header_response (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ char *buf; /**< the output buffer */ size_t pos; /**< append offset in the @a buf */ size_t buf_size; /**< the size of the @a buf */ size_t el_size; /**< the size of current element to be added to the @a buf */ unsigned rcode; /**< the response code */ bool use_conn_close; /**< Use "Connection: close" header */ bool use_conn_k_alive; /**< Use "Connection: Keep-Alive" header */ mhd_assert (NULL != r); /* ** Adjust response properties ** */ setup_reply_properties (c); mhd_assert (c->rp.props.set); mhd_assert ((MHD_CONN_MUST_CLOSE == c->keepalive) || \ (MHD_CONN_USE_KEEPALIVE == c->keepalive) || \ (MHD_CONN_MUST_UPGRADE == c->keepalive)); #ifdef UPGRADE_SUPPORT mhd_assert ((NULL == r->upgrade_handler) || \ (MHD_CONN_MUST_UPGRADE == c->keepalive)); #else /* ! UPGRADE_SUPPORT */ mhd_assert (MHD_CONN_MUST_UPGRADE != c->keepalive); #endif /* ! UPGRADE_SUPPORT */ mhd_assert ((! c->rp.props.chunked) || c->rp.props.use_reply_body_headers); mhd_assert ((! c->rp.props.send_reply_body) || \ c->rp.props.use_reply_body_headers); #ifdef UPGRADE_SUPPORT mhd_assert (NULL == r->upgrade_handler || \ ! c->rp.props.use_reply_body_headers); #endif /* UPGRADE_SUPPORT */ check_connection_reply (c); rcode = (unsigned) c->rp.responseCode; if (MHD_CONN_MUST_CLOSE == c->keepalive) { /* The closure of connection must be always indicated by header * to avoid hung connections */ use_conn_close = true; use_conn_k_alive = false; } else if (MHD_CONN_USE_KEEPALIVE == c->keepalive) { use_conn_close = false; /* Add "Connection: keep-alive" if request is HTTP/1.0 or * if reply is HTTP/1.0 * For HTTP/1.1 add header only if explicitly requested by app * (by response flag), as "Keep-Alive" is default for HTTP/1.1. */ if ((0 != (r->flags & MHD_RF_SEND_KEEP_ALIVE_HEADER)) || (MHD_HTTP_VER_1_0 == c->rq.http_ver) || (0 != (r->flags & MHD_RF_HTTP_1_0_SERVER))) use_conn_k_alive = true; else use_conn_k_alive = false; } else { use_conn_close = false; use_conn_k_alive = false; } /* ** Actually build the response header ** */ /* Get all space available */ connection_maximize_write_buffer (c); buf = c->write_buffer; pos = c->write_buffer_append_offset; buf_size = c->write_buffer_size; if (0 == buf_size) return MHD_NO; mhd_assert (NULL != buf); /* * The status line * */ /* The HTTP version */ if (! c->rp.responseIcy) { /* HTTP reply */ if (0 == (r->flags & MHD_RF_HTTP_1_0_SERVER)) { /* HTTP/1.1 reply */ /* Use HTTP/1.1 responses for HTTP/1.0 clients. * See https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_1)) return MHD_NO; } else { /* HTTP/1.0 reply */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_0)) return MHD_NO; } } else { /* ICY reply */ if (! buffer_append_s (buf, &pos, buf_size, "ICY")) return MHD_NO; } /* The response code */ if (buf_size < pos + 5) /* space + code + space */ return MHD_NO; buf[pos++] = ' '; pos += MHD_uint16_to_str ((uint16_t) rcode, buf + pos, buf_size - pos); buf[pos++] = ' '; /* The reason phrase */ el_size = MHD_get_reason_phrase_len_for (rcode); if (0 == el_size) { if (! buffer_append_s (buf, &pos, buf_size, "Non-Standard Status")) return MHD_NO; } else if (! buffer_append (buf, &pos, buf_size, MHD_get_reason_phrase_for (rcode), el_size)) return MHD_NO; /* The linefeed */ if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; /* * The headers * */ /* Main automatic headers */ /* The "Date:" header */ if ( (0 == (r->flags_auto & MHD_RAF_HAS_DATE_HDR)) && (0 == (c->daemon->options & MHD_USE_SUPPRESS_DATE_NO_CLOCK)) ) { /* Additional byte for unused zero-termination */ if (buf_size < pos + 38) return MHD_NO; if (get_date_header (buf + pos)) pos += 37; } /* The "Connection:" header */ mhd_assert (! use_conn_close || ! use_conn_k_alive); mhd_assert (! use_conn_k_alive || ! use_conn_close); if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { if (use_conn_close) { if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONNECTION ": close\r\n")) return MHD_NO; } else if (use_conn_k_alive) { if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONNECTION ": Keep-Alive\r\n")) return MHD_NO; } } /* User-defined headers */ if (! add_user_headers (buf, &pos, buf_size, r, ! c->rp.props.chunked, (! c->rp.props.use_reply_body_headers) && (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)), use_conn_close, use_conn_k_alive)) return MHD_NO; /* Other automatic headers */ if ( (c->rp.props.use_reply_body_headers) && (0 == (r->flags & MHD_RF_HEAD_ONLY_RESPONSE)) ) { /* Body-specific headers */ if (c->rp.props.chunked) { /* Chunked encoding is used */ if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) { /* No chunked encoding header set by user */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": " \ "chunked\r\n")) return MHD_NO; } } else /* Chunked encoding is not used */ { if (MHD_SIZE_UNKNOWN != r->total_size) { /* The size is known */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) { /* The response does not have "Content-Length" header */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ")) return MHD_NO; el_size = MHD_uint64_to_str (r->total_size, buf + pos, buf_size - pos); if (0 == el_size) return MHD_NO; pos += el_size; if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; } } } } /* * Header termination * */ if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; c->write_buffer_append_offset = pos; return MHD_YES; } /** * Allocate the connection's write buffer (if necessary) and fill it * with response footers. * Works only for chunked responses as other responses do not need * and do not support any kind of footers. * * @param connection the connection * @return #MHD_YES on success, #MHD_NO on failure (out of memory) */ static enum MHD_Result build_connection_chunked_response_footer (struct MHD_Connection *connection) { char *buf; /**< the buffer to write footers to */ size_t buf_size; /**< the size of the @a buf */ size_t used_size; /**< the used size of the @a buf */ struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_HTTP_Res_Header *pos; mhd_assert (connection->rp.props.chunked); /* TODO: allow combining of the final footer with the last chunk, * modify the next assert. */ mhd_assert (MHD_CONNECTION_CHUNKED_BODY_SENT == connection->state); mhd_assert (NULL != c->rp.response); buf_size = connection_maximize_write_buffer (c); /* '5' is the minimal size of chunked footer ("0\r\n\r\n") */ if (buf_size < 5) return MHD_NO; mhd_assert (NULL != c->write_buffer); buf = c->write_buffer + c->write_buffer_append_offset; mhd_assert (NULL != buf); used_size = 0; buf[used_size++] = '0'; buf[used_size++] = '\r'; buf[used_size++] = '\n'; for (pos = c->rp.response->first_header; NULL != pos; pos = pos->next) { if (MHD_FOOTER_KIND == pos->kind) { size_t new_used_size; /* resulting size with this header */ /* '4' is colon, space, linefeeds */ new_used_size = used_size + pos->header_size + pos->value_size + 4; if (new_used_size > buf_size) return MHD_NO; memcpy (buf + used_size, pos->header, pos->header_size); used_size += pos->header_size; buf[used_size++] = ':'; buf[used_size++] = ' '; memcpy (buf + used_size, pos->value, pos->value_size); used_size += pos->value_size; buf[used_size++] = '\r'; buf[used_size++] = '\n'; mhd_assert (used_size == new_used_size); } } if (used_size + 2 > buf_size) return MHD_NO; buf[used_size++] = '\r'; buf[used_size++] = '\n'; c->write_buffer_append_offset += used_size; mhd_assert (c->write_buffer_append_offset <= c->write_buffer_size); return MHD_YES; } /** * We encountered an error processing the request. * Handle it properly by stopping to read data * and sending the indicated response code and message. * * @param connection the connection * @param status_code the response code to send (400, 413 or 414) * @param message the error message to send * @param message_len the length of the @a message * @param header_name the name of the header, malloc()ed by the caller, * free() by this function, optional, can be NULL * @param header_name_len the length of the @a header_name * @param header_value the value of the header, malloc()ed by the caller, * free() by this function, optional, can be NULL * @param header_value_len the length of the @a header_value */ static void transmit_error_response_len (struct MHD_Connection *connection, unsigned int status_code, const char *message, size_t message_len, char *header_name, size_t header_name_len, char *header_value, size_t header_value_len) { struct MHD_Response *response; enum MHD_Result iret; mhd_assert (! connection->stop_with_error); /* Do not send error twice */ if (connection->stop_with_error) { /* Should not happen */ if (MHD_CONNECTION_CLOSED > connection->state) connection->state = MHD_CONNECTION_CLOSED; free (header_name); free (header_value); return; } connection->stop_with_error = true; connection->discard_request = true; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Error processing request (HTTP response code is %u ('%s')). " \ "Closing connection.\n"), status_code, message); #endif if (MHD_CONNECTION_START_REPLY < connection->state) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Too late to send an error response, " \ "response is being sent already.\n"), status_code, message); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Too late for error response.")); free (header_name); free (header_value); return; } /* TODO: remove when special error queue function is implemented */ connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; if (0 != connection->read_buffer_size) { /* Read buffer is not needed anymore, discard it * to free some space for error response. */ MHD_pool_deallocate (connection->pool, connection->read_buffer, connection->read_buffer_size); connection->read_buffer = NULL; connection->read_buffer_size = 0; connection->read_buffer_offset = 0; } if (NULL != connection->rp.response) { MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; } response = MHD_create_response_from_buffer_static (message_len, message); if (NULL == response) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to create error response.\n"), status_code, message); #endif /* can't even send a reply, at least close the connection */ connection->state = MHD_CONNECTION_CLOSED; free (header_name); free (header_value); return; } mhd_assert ((0 == header_name_len) || (NULL != header_name)); mhd_assert ((NULL == header_name) || (0 != header_name_len)); mhd_assert ((0 == header_value_len) || (NULL != header_value)); mhd_assert ((NULL == header_value) || (0 != header_value_len)); mhd_assert ((NULL == header_name) || (NULL != header_value)); mhd_assert ((NULL != header_value) || (NULL == header_name)); if (NULL != header_name) { iret = MHD_add_response_entry_no_alloc_ (response, MHD_HEADER_KIND, header_name, header_name_len, header_value, header_value_len); if (MHD_NO == iret) { free (header_name); free (header_value); } } else iret = MHD_YES; if (MHD_NO != iret) { bool before = connection->in_access_handler; /* Fake the flag for the internal call */ connection->in_access_handler = true; iret = MHD_queue_response (connection, status_code, response); connection->in_access_handler = before; } MHD_destroy_response (response); if (MHD_NO == iret) { /* can't even send a reply, at least close the connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection " \ "(failed to queue error response).")); return; } mhd_assert (NULL != connection->rp.response); /* Do not reuse this connection. */ connection->keepalive = MHD_CONN_MUST_CLOSE; if (MHD_NO == build_header_response (connection)) { /* No memory. Release everything. */ connection->rq.version = NULL; connection->rq.method = NULL; connection->rq.url = NULL; connection->rq.url_len = 0; connection->rq.headers_received = NULL; connection->rq.headers_received_tail = NULL; connection->write_buffer = NULL; connection->write_buffer_size = 0; connection->write_buffer_send_offset = 0; connection->write_buffer_append_offset = 0; connection->read_buffer = MHD_pool_reset (connection->pool, NULL, 0, 0); connection->read_buffer_size = 0; /* Retry with empty buffer */ if (MHD_NO == build_header_response (connection)) { CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection " \ "(failed to create error response header).")); return; } } connection->state = MHD_CONNECTION_HEADERS_SENDING; } /** * Transmit static string as error response */ #define transmit_error_response_static(c, code, msg) \ transmit_error_response_len (c, code, \ msg, MHD_STATICSTR_LEN_ (msg), \ NULL, 0, NULL, 0) /** * Transmit static string as error response and add specified header */ #define transmit_error_response_header(c, code, m, hd_n, hd_n_l, hd_v, hd_v_l) \ transmit_error_response_len (c, code, \ m, MHD_STATICSTR_LEN_ (m), \ hd_n, hd_n_l, \ hd_v, hd_v_l) /** * Check whether the read buffer has any upload body data ready to * be processed. * Must be called only when connection is in MHD_CONNECTION_BODY_RECEIVING * state. * * @param c the connection to check * @return 'true' if upload body data is already in the read buffer, * 'false' if no upload data is received and not processed. */ static bool has_unprocessed_upload_body_data_in_buffer (struct MHD_Connection *c) { mhd_assert (MHD_CONNECTION_BODY_RECEIVING == c->state); if (! c->rq.have_chunked_upload) return 0 != c->read_buffer_offset; /* Chunked upload */ mhd_assert (0 != c->rq.remaining_upload_size); /* Must not be possible in MHD_CONNECTION_BODY_RECEIVING state */ if (c->rq.current_chunk_offset == c->rq.current_chunk_size) { /* 0 == c->rq.current_chunk_size: Waiting the chunk size (chunk header). 0 != c->rq.current_chunk_size: Waiting for chunk-closing CRLF. */ return false; } return 0 != c->read_buffer_offset; /* Chunk payload data in the read buffer */ } /** * The stage of input data processing. * Used for out-of-memory (in the pool) handling. */ enum MHD_ProcRecvDataStage { MHD_PROC_RECV_INIT, /**< No data HTTP request data have been processed yet */ MHD_PROC_RECV_METHOD, /**< Processing/receiving the request HTTP method */ MHD_PROC_RECV_URI, /**< Processing/receiving the request URI */ MHD_PROC_RECV_HTTPVER, /**< Processing/receiving the request HTTP version string */ MHD_PROC_RECV_HEADERS, /**< Processing/receiving the request HTTP headers */ MHD_PROC_RECV_COOKIE, /**< Processing the received request cookie header */ MHD_PROC_RECV_BODY_NORMAL, /**< Processing/receiving the request non-chunked body */ MHD_PROC_RECV_BODY_CHUNKED,/**< Processing/receiving the request chunked body */ MHD_PROC_RECV_FOOTERS /**< Processing/receiving the request footers */ }; #ifndef MHD_MAX_REASONABLE_HEADERS_SIZE_ /** * A reasonable headers size (excluding request line) that should be sufficient * for most requests. * If incoming data buffer free space is not enough to process the complete * header (the request line and all headers) and the headers size is larger than * this size then the status code 431 "Request Header Fields Too Large" is * returned to the client. * The larger headers are processed by MHD if enough space is available. */ # define MHD_MAX_REASONABLE_HEADERS_SIZE_ (6 * 1024) #endif /* ! MHD_MAX_REASONABLE_HEADERS_SIZE_ */ #ifndef MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ /** * A reasonable request target (the request URI) size that should be sufficient * for most requests. * If incoming data buffer free space is not enough to process the complete * header (the request line and all headers) and the request target size is * larger than this size then the status code 414 "URI Too Long" is * returned to the client. * The larger request targets are processed by MHD if enough space is available. * The value chosen according to RFC 9112 Section 3, paragraph 5 */ # define MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ 8000 #endif /* ! MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ */ #ifndef MHD_MIN_REASONABLE_HEADERS_SIZE_ /** * A reasonable headers size (excluding request line) that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 431 "Request Header Fields Too Large" if headers size * is smaller then this value. */ # define MHD_MIN_REASONABLE_HEADERS_SIZE_ 26 #endif /* ! MHD_MIN_REASONABLE_HEADERS_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ /** * A reasonable request target (the request URI) size that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 414 "URI Too Long" if the request target size is smaller then * this value. */ # define MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ 40 #endif /* ! MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ /** * A reasonable request method string size that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 501 "Not Implemented" if the request method size is * smaller then this value. */ # define MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ 16 #endif /* ! MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ /** * A reasonable minimal chunk line length. * When no space left in the receiving buffer reply with 413 "Content Too Large" * if the chunk line length is larger than this value. */ # define MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ 4 #endif /* ! MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ */ /** * Select the HTTP error status code for "out of receive buffer space" error. * @param c the connection to process * @param stage the current stage of request receiving * @param add_element the optional pointer to the element failed to be processed * or added, the meaning of the element depends on * the @a stage. Could be not zero-terminated and can * contain binary zeros. Can be NULL. * @param add_element_size the size of the @a add_element * @return the HTTP error code to use in the error reply */ static unsigned int get_no_space_err_status_code (struct MHD_Connection *c, enum MHD_ProcRecvDataStage stage, const char *add_element, size_t add_element_size) { size_t method_size; size_t uri_size; size_t opt_headers_size; size_t host_field_line_size; mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED < c->state); mhd_assert (MHD_PROC_RECV_HEADERS <= stage); mhd_assert ((0 == add_element_size) || (NULL != add_element)); if (MHD_CONNECTION_HEADERS_RECEIVED > c->state) { mhd_assert (NULL != c->rq.field_lines.start); opt_headers_size = (size_t) ((c->read_buffer + c->read_buffer_offset) - c->rq.field_lines.start); } else opt_headers_size = c->rq.field_lines.size; /* The read buffer is fully used by the request line, the field lines (headers) and internal information. The return status code works as a suggestion for the client to reduce one of the request elements. */ if ((MHD_PROC_RECV_BODY_CHUNKED == stage) && (MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ < add_element_size)) { /* Request could be re-tried easily with smaller chunk sizes */ return MHD_HTTP_CONTENT_TOO_LARGE; } host_field_line_size = 0; /* The "Host:" field line is mandatory. The total size of the field lines (headers) cannot be smaller than the size of the "Host:" field line. */ if ((MHD_PROC_RECV_HEADERS == stage) && (0 != add_element_size)) { static const size_t header_host_key_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); const bool is_host_header = (header_host_key_len + 1 <= add_element_size) && ( (0 == add_element[header_host_key_len]) || (':' == add_element[header_host_key_len]) ) && MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_HOST, add_element, header_host_key_len); if (is_host_header) { const bool is_parsed = ! ( (MHD_CONNECTION_HEADERS_RECEIVED > c->state) && (add_element_size == c->read_buffer_offset) && (c->read_buffer == add_element) ); size_t actual_element_size; mhd_assert (! is_parsed || (0 == add_element[header_host_key_len])); /* The actual size should be larger due to CRLF or LF chars, however the exact termination sequence is not known here and as perfect precision is not required, to simplify the code assume the minimal length. */ if (is_parsed) actual_element_size = add_element_size + 1; /* "1" for LF */ else actual_element_size = add_element_size; host_field_line_size = actual_element_size; mhd_assert (opt_headers_size >= actual_element_size); opt_headers_size -= actual_element_size; } } if (0 == host_field_line_size) { static const size_t host_field_name_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); size_t host_field_name_value_len; if (MHD_NO != MHD_lookup_connection_value_n (c, MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST, host_field_name_len, NULL, &host_field_name_value_len)) { /* Calculate the minimal size of the field line: no space between colon and the field value, line terminated by LR */ host_field_line_size = host_field_name_len + host_field_name_value_len + 2; /* "2" for ':' and LF */ /* The "Host:" field could be added by application */ if (opt_headers_size >= host_field_line_size) { opt_headers_size -= host_field_line_size; /* Take into account typical space after colon and CR at the end of the line */ if (opt_headers_size >= 2) opt_headers_size -= 2; } else host_field_line_size = 0; /* No "Host:" field line set by the client */ } } uri_size = c->rq.req_target_len; if (MHD_HTTP_MTHD_OTHER != c->rq.http_mthd) method_size = 0; /* Do not recommend shorter request method */ else { mhd_assert (NULL != c->rq.method); method_size = strlen (c->rq.method); } if ((size_t) MHD_MAX_REASONABLE_HEADERS_SIZE_ < opt_headers_size) { /* Typically the easiest way to reduce request header size is a removal of some optional headers. */ if (opt_headers_size > (uri_size / 8)) { if ((opt_headers_size / 2) > method_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } else { /* Request target is MUCH larger than headers */ if ((uri_size / 16) > method_size) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } } if ((size_t) MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ < uri_size) { /* If request target size if larger than maximum reasonable size recommend client to reduce the request target size (length). */ if ((uri_size / 16) > method_size) return MHD_HTTP_URI_TOO_LONG; /* Request target is MUCH larger than headers */ else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } /* The read buffer is too small to handle reasonably large requests */ if ((size_t) MHD_MIN_REASONABLE_HEADERS_SIZE_ < opt_headers_size) { /* Recommend application to retry with minimal headers */ if ((opt_headers_size * 4) > uri_size) { if (opt_headers_size > method_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } else { /* Request target is significantly larger than headers */ if (uri_size > method_size * 4) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } } if ((size_t) MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ < uri_size) { /* Recommend application to retry with a shorter request target */ if (uri_size > method_size * 4) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } if ((size_t) MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ < method_size) { /* The request target (URI) and headers are (reasonably) very small. Some non-standard long request method is used. */ /* The last resort response as it means "the method is not supported by the server for any URI". */ return MHD_HTTP_NOT_IMPLEMENTED; } /* The almost impossible situation: all elements are small, but cannot fit the buffer. The application set the buffer size to critically low value? */ if ((1 < opt_headers_size) || (1 < uri_size)) { if (opt_headers_size >= uri_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_URI_TOO_LONG; } /* Nothing to reduce in the request. Reply with some status. */ if (0 != host_field_line_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; return MHD_HTTP_URI_TOO_LONG; } /** * Send error reply when receive buffer space exhausted while receiving or * storing the request headers * @param c the connection to handle * @param add_header the optional pointer to the current header string being * processed or the header failed to be added. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_header_size the size of the @a add_header */ static void handle_req_headers_no_space (struct MHD_Connection *c, const char *add_header, size_t add_header_size) { unsigned int err_code; err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_HEADERS, add_header, add_header_size); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_HEADER_TOO_BIG); } #ifdef COOKIE_SUPPORT /** * Send error reply when the pool has no space to store 'cookie' header * parsing results. * @param c the connection to handle */ static void handle_req_cookie_no_space (struct MHD_Connection *c) { unsigned int err_code; err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_COOKIE, NULL, 0); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG); } #endif /* COOKIE_SUPPORT */ /** * Send error reply when receive buffer space exhausted while receiving * the chunk size line. * @param c the connection to handle * @param add_header the optional pointer to the partially received * the current chunk size line. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_header_size the size of the @a add_header */ static void handle_req_chunk_size_line_no_space (struct MHD_Connection *c, const char *chunk_size_line, size_t chunk_size_line_size) { unsigned int err_code; if (NULL != chunk_size_line) { const char *semicol; /* Check for chunk extension */ semicol = memchr (chunk_size_line, ';', chunk_size_line_size); if (NULL != semicol) { /* Chunk extension present. It could be removed without any loss of the details of the request. */ transmit_error_response_static (c, MHD_HTTP_CONTENT_TOO_LARGE, ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG); } } err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_BODY_CHUNKED, chunk_size_line, chunk_size_line_size); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG); } /** * Send error reply when receive buffer space exhausted while receiving or * storing the request footers (for chunked requests). * @param c the connection to handle * @param add_footer the optional pointer to the current footer string being * processed or the footer failed to be added. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_footer_size the size of the @a add_footer */ static void handle_req_footers_no_space (struct MHD_Connection *c, const char *add_footer, size_t add_footer_size) { (void) add_footer; (void) add_footer_size; /* Unused */ mhd_assert (c->rq.have_chunked_upload); /* Footers should be optional */ transmit_error_response_static (c, MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, ERR_MSG_REQUEST_FOOTER_TOO_BIG); } /** * Handle situation with read buffer exhaustion. * Must be called when no more space left in the read buffer, no more * space left in the memory pool to grow the read buffer, but more data * need to be received from the client. * Could be called when the result of received data processing cannot be * stored in the memory pool (like some header). * @param c the connection to process * @param stage the receive stage where the exhaustion happens. */ static void handle_recv_no_space (struct MHD_Connection *c, enum MHD_ProcRecvDataStage stage) { mhd_assert (MHD_PROC_RECV_INIT <= stage); mhd_assert (MHD_PROC_RECV_FOOTERS >= stage); mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED > c->state); mhd_assert ((MHD_PROC_RECV_INIT != stage) || \ (MHD_CONNECTION_INIT == c->state)); mhd_assert ((MHD_PROC_RECV_METHOD != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_URI != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_HTTPVER != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_HEADERS != stage) || \ (MHD_CONNECTION_REQ_HEADERS_RECEIVING == c->state)); mhd_assert (MHD_PROC_RECV_COOKIE != stage); /* handle_req_cookie_no_space() must be called directly */ mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \ (MHD_CONNECTION_BODY_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ (MHD_CONNECTION_BODY_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_FOOTERS != stage) || \ (MHD_CONNECTION_FOOTERS_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \ (! c->rq.have_chunked_upload)); mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ (c->rq.have_chunked_upload)); switch (stage) { case MHD_PROC_RECV_INIT: case MHD_PROC_RECV_METHOD: /* Some data has been received, but it is not clear yet whether * the received data is an valid HTTP request */ connection_close_error (c, _ ("No space left in the read buffer when " \ "receiving the initial part of " \ "the request line.")); return; case MHD_PROC_RECV_URI: case MHD_PROC_RECV_HTTPVER: /* Some data has been received, but the request line is incomplete */ mhd_assert (MHD_HTTP_MTHD_NO_METHOD != c->rq.http_mthd); mhd_assert (MHD_HTTP_VER_UNKNOWN == c->rq.http_ver); /* A quick simple check whether the incomplete line looks * like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_URI_TOO_LONG, ERR_MSG_REQUEST_TOO_BIG); return; } connection_close_error (c, _ ("No space left in the read buffer when " \ "receiving the URI in " \ "the request line. " \ "The request uses non-standard HTTP request " \ "method token.")); return; case MHD_PROC_RECV_HEADERS: handle_req_headers_no_space (c, c->read_buffer, c->read_buffer_offset); return; case MHD_PROC_RECV_BODY_NORMAL: case MHD_PROC_RECV_BODY_CHUNKED: mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ ! c->rq.some_payload_processed); if (has_unprocessed_upload_body_data_in_buffer (c)) { /* The connection must not be in MHD_EVENT_LOOP_INFO_READ state when external polling is used and some data left unprocessed. */ mhd_assert (MHD_D_IS_USING_THREADS_ (c->daemon)); /* failed to grow the read buffer, and the client which is supposed to handle the received data in a *blocking* fashion (in this mode) did not handle the data as it was supposed to! => we would either have to do busy-waiting (on the client, which would likely fail), or if we do nothing, we would just timeout on the connection (if a timeout is even set!). Solution: we kill the connection with an error */ transmit_error_response_static (c, MHD_HTTP_INTERNAL_SERVER_ERROR, ERROR_MSG_DATA_NOT_HANDLED_BY_APP); } else { if (MHD_PROC_RECV_BODY_NORMAL == stage) { /* A header probably has been added to a suspended connection and it took precisely all the space in the buffer. Very low probability. */ mhd_assert (! c->rq.have_chunked_upload); handle_req_headers_no_space (c, NULL, 0); } else { mhd_assert (c->rq.have_chunked_upload); if (c->rq.current_chunk_offset != c->rq.current_chunk_size) { /* Receiving content of the chunk */ /* A header probably has been added to a suspended connection and it took precisely all the space in the buffer. Very low probability. */ handle_req_headers_no_space (c, NULL, 0); } else { if (0 != c->rq.current_chunk_size) { /* Waiting for chunk-closing CRLF */ /* Not really possible as some payload should be processed and the space used by payload should be available. */ handle_req_headers_no_space (c, NULL, 0); } else { /* Reading the line with the chunk size */ handle_req_chunk_size_line_no_space (c, c->read_buffer, c->read_buffer_offset); } } } } return; case MHD_PROC_RECV_FOOTERS: handle_req_footers_no_space (c, c->read_buffer, c->read_buffer_offset); return; /* The next cases should not be possible */ case MHD_PROC_RECV_COOKIE: default: break; } mhd_assert (0); } /** * Check whether enough space is available in the read buffer for the next * operation. * Handles grow of the buffer if required and error conditions (when buffer * grow is required but not possible). * Must be called only when processing the event loop states and when * reading is required for the next phase. * @param c the connection to check * @return true if connection handled successfully and enough buffer * is available, * false if not enough buffer is available and the loop's states * must be processed again as connection is in the error state. */ static bool check_and_grow_read_buffer_space (struct MHD_Connection *c) { /** * The increase of read buffer size is desirable. */ bool rbuff_grow_desired; /** * The increase of read buffer size is a hard requirement. */ bool rbuff_grow_required; mhd_assert (0 != (MHD_EVENT_LOOP_INFO_READ & c->event_loop_info)); mhd_assert (! c->discard_request); rbuff_grow_required = (c->read_buffer_offset == c->read_buffer_size); if (rbuff_grow_required) rbuff_grow_desired = true; else { rbuff_grow_desired = (c->read_buffer_offset + c->daemon->pool_increment > c->read_buffer_size); if ((rbuff_grow_desired) && (MHD_CONNECTION_BODY_RECEIVING == c->state)) { if (! c->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN != c->rq.remaining_upload_size); /* Do not grow read buffer more than necessary to process the current request. */ rbuff_grow_desired = (c->rq.remaining_upload_size > c->read_buffer_size); } else { mhd_assert (MHD_SIZE_UNKNOWN == c->rq.remaining_upload_size); if (0 == c->rq.current_chunk_size) rbuff_grow_desired = /* Reading value of the next chunk size */ (MHD_CHUNK_HEADER_REASONABLE_LEN > c->read_buffer_size); else { const uint64_t cur_chunk_left = c->rq.current_chunk_size - c->rq.current_chunk_offset; /* Do not grow read buffer more than necessary to process the current chunk with terminating CRLF. */ mhd_assert (c->rq.current_chunk_offset <= c->rq.current_chunk_size); rbuff_grow_desired = ((cur_chunk_left + 2) > (uint64_t) (c->read_buffer_size)); } } } } if (! rbuff_grow_desired) return true; /* No need to increase the buffer */ if (try_grow_read_buffer (c, rbuff_grow_required)) return true; /* Buffer increase succeed */ if (! rbuff_grow_required) return true; /* Can continue without buffer increase */ /* Failed to increase the read buffer size, but need to read the data from the network. No more space left in the buffer, no more space to increase the buffer. */ /* 'PROCESS_READ' event state flag must be set only if the last application callback has processed some data. If any data is processed then some space in the read buffer must be available. */ mhd_assert (0 == (MHD_EVENT_LOOP_INFO_PROCESS & c->event_loop_info)); if ((! MHD_D_IS_USING_THREADS_ (c->daemon)) && (MHD_CONNECTION_BODY_RECEIVING == c->state) && has_unprocessed_upload_body_data_in_buffer (c)) { /* The application is handling processing cycles. The data could be processed later. */ c->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; return true; } else { enum MHD_ProcRecvDataStage stage; switch (c->state) { case MHD_CONNECTION_INIT: stage = MHD_PROC_RECV_INIT; break; case MHD_CONNECTION_REQ_LINE_RECEIVING: if (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd) stage = MHD_PROC_RECV_METHOD; else if (0 == c->rq.req_target_len) stage = MHD_PROC_RECV_URI; else stage = MHD_PROC_RECV_HTTPVER; break; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: stage = MHD_PROC_RECV_HEADERS; break; case MHD_CONNECTION_BODY_RECEIVING: stage = c->rq.have_chunked_upload ? MHD_PROC_RECV_BODY_CHUNKED : MHD_PROC_RECV_BODY_NORMAL; break; case MHD_CONNECTION_FOOTERS_RECEIVING: stage = MHD_PROC_RECV_FOOTERS; break; case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: case MHD_CONNECTION_CONTINUE_SENDING: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVED: case MHD_CONNECTION_FULL_REQ_RECEIVED: case MHD_CONNECTION_START_REPLY: case MHD_CONNECTION_HEADERS_SENDING: case MHD_CONNECTION_HEADERS_SENT: case MHD_CONNECTION_NORMAL_BODY_UNREADY: case MHD_CONNECTION_NORMAL_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_SENT: case MHD_CONNECTION_FOOTERS_SENDING: case MHD_CONNECTION_FULL_REPLY_SENT: case MHD_CONNECTION_CLOSED: #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: #endif default: stage = MHD_PROC_RECV_BODY_NORMAL; mhd_assert (0); } handle_recv_no_space (c, stage); } return false; } /** * Update the 'event_loop_info' field of this connection based on the state * that the connection is now in. May also close the connection or * perform other updates to the connection if needed to prepare for * the next round of the event loop. * * @param connection connection to get poll set for */ static void MHD_connection_update_event_loop_info (struct MHD_Connection *connection) { /* Do not update states of suspended connection */ if (connection->suspended) return; /* States will be updated after resume. */ #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ switch (connection->tls_state) { case MHD_TLS_CONN_INIT: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; return; case MHD_TLS_CONN_HANDSHAKING: case MHD_TLS_CONN_WR_CLOSING: if (0 == gnutls_record_get_direction (connection->tls_session)) connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; else connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; return; case MHD_TLS_CONN_CONNECTED: break; /* Do normal processing */ case MHD_TLS_CONN_WR_CLOSED: case MHD_TLS_CONN_TLS_FAILED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; return; case MHD_TLS_CONN_TLS_CLOSING: /* Not implemented yet */ case MHD_TLS_CONN_TLS_CLOSED: /* Not implemented yet */ case MHD_TLS_CONN_INVALID_STATE: case MHD_TLS_CONN_NO_TLS: /* Not possible */ default: MHD_PANIC (_ ("Invalid TLS state value.\n")); } } #endif /* HTTPS_SUPPORT */ while (1) { #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_REQ_LINE_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: mhd_assert (0); break; case MHD_CONNECTION_CONTINUE_SENDING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_BODY_RECEIVING: if ((connection->rq.some_payload_processed) && has_unprocessed_upload_body_data_in_buffer (connection)) { /* Some data was processed, the buffer must have some free space */ mhd_assert (connection->read_buffer_offset < \ connection->read_buffer_size); if (! connection->rq.have_chunked_upload) { /* Not a chunked upload. Do not read more than necessary to process the current request. */ if (connection->rq.remaining_upload_size >= connection->read_buffer_offset) connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; else connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ; } else { /* Chunked upload. The size of the current request is unknown. Continue reading as the space in the read buffer is available. */ connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ; } } else connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_BODY_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_FOOTERS_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_FOOTERS_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_FULL_REQ_RECEIVED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_START_REPLY: mhd_assert (0); break; case MHD_CONNECTION_HEADERS_SENDING: /* headers in buffer, keep writing */ connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_HEADERS_SENT: mhd_assert (0); break; case MHD_CONNECTION_NORMAL_BODY_UNREADY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_NORMAL_BODY_READY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_CHUNKED_BODY_READY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (0); break; case MHD_CONNECTION_FOOTERS_SENDING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_FULL_REPLY_SENT: mhd_assert (0); break; case MHD_CONNECTION_CLOSED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; return; /* do nothing, not even reading */ #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); break; #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); } if (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) { /* Check whether the space is available to receive data */ if (! check_and_grow_read_buffer_space (connection)) { mhd_assert (connection->discard_request); continue; } } break; /* Everything was processed. */ } } /** * Add an entry to the HTTP headers of a connection. If this fails, * transmit an error response (request too big). * * @param cls the context (connection) * @param kind kind of the value * @param key key for the value * @param key_size number of bytes in @a key * @param value the value itself * @param value_size number of bytes in @a value * @return #MHD_NO on failure (out of memory), #MHD_YES for success */ static enum MHD_Result connection_add_header (void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind) { struct MHD_Connection *connection = (struct MHD_Connection *) cls; if (MHD_NO == MHD_set_connection_value_n (connection, kind, key, key_size, value, value_size)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in pool to allocate header record!\n")); #endif transmit_error_response_static (connection, MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, ERR_MSG_REQUEST_TOO_BIG); return MHD_NO; } return MHD_YES; } #ifdef COOKIE_SUPPORT /** * Cookie parsing result */ enum _MHD_ParseCookie { MHD_PARSE_COOKIE_OK = MHD_YES, /**< Success or no cookies in headers */ MHD_PARSE_COOKIE_OK_LAX = 2, /**< Cookies parsed, but workarounds used */ MHD_PARSE_COOKIE_MALFORMED = -1, /**< Invalid cookie header */ MHD_PARSE_COOKIE_NO_MEMORY = MHD_NO /**< Not enough memory in the pool */ }; /** * Parse the cookies string (see RFC 6265). * * Try to parse the cookies string even if it is not strictly formed * as specified by RFC 6265. * * @param str the string to parse, without leading whitespaces * @param str_len the size of the @a str, not including mandatory * zero-termination * @param connection the connection to add parsed cookies * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise */ static enum _MHD_ParseCookie parse_cookies_string (char *str, const size_t str_len, struct MHD_Connection *connection) { size_t i; bool non_strict; /* Skip extra whitespaces and empty cookies */ const bool allow_wsp_empty = (0 >= connection->daemon->client_discipline); /* Allow whitespaces around '=' character */ const bool wsp_around_eq = (-3 >= connection->daemon->client_discipline); /* Allow whitespaces in quoted cookie value */ const bool wsp_in_quoted = (-2 >= connection->daemon->client_discipline); /* Allow tab as space after semicolon between cookies */ const bool tab_as_sp = (0 >= connection->daemon->client_discipline); /* Allow no space after semicolon between cookies */ const bool allow_no_space = (0 >= connection->daemon->client_discipline); non_strict = false; i = 0; while (i < str_len) { size_t name_start; size_t name_len; size_t value_start; size_t value_len; bool val_quoted; /* Skip any whitespaces and empty cookies */ while (' ' == str[i] || '\t' == str[i] || ';' == str[i]) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; if (i == str_len) return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK; } /* 'i' must point to the first char of cookie-name */ name_start = i; /* Find the end of the cookie-name */ do { const char l = str[i]; if (('=' == l) || (' ' == l) || ('\t' == l) || ('"' == l) || (',' == l) || (';' == l) || (0 == l)) break; } while (str_len > ++i); name_len = i - name_start; /* Skip any whitespaces */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) { if (! wsp_around_eq) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; } if ((str_len == i) || ('=' != str[i]) || (0 == name_len)) return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie name */ /* 'i' must point to the '=' char */ mhd_assert ('=' == str[i]); i++; /* Skip any whitespaces */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) { if (! wsp_around_eq) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; } /* 'i' must point to the first char of cookie-value */ if (str_len == i) { value_start = 0; value_len = 0; #ifdef _DEBUG val_quoted = false; /* This assignment used in assert */ #endif } else { bool valid_cookie; val_quoted = ('"' == str[i]); if (val_quoted) i++; value_start = i; /* Find the end of the cookie-value */ while (str_len > i) { const char l = str[i]; if ((';' == l) || ('"' == l) || (',' == l) || (';' == l) || ('\\' == l) || (0 == l)) break; if ((' ' == l) || ('\t' == l)) { if (! val_quoted) break; if (! wsp_in_quoted) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } i++; } value_len = i - value_start; if (val_quoted) { if ((str_len == i) || ('"' != str[i])) return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie value, no closing quote */ i++; } /* Skip any whitespaces */ if ((str_len > i) && ((' ' == str[i]) || ('\t' == str[i]))) { do { i++; } while (str_len > i && (' ' == str[i] || '\t' == str[i])); /* Whitespace at the end? */ if (str_len > i) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } } if (str_len == i) valid_cookie = true; else if (';' == str[i]) valid_cookie = true; else valid_cookie = false; if (! valid_cookie) return MHD_PARSE_COOKIE_MALFORMED; /* Garbage at the end of the cookie value */ } mhd_assert (0 != name_len); str[name_start + name_len] = 0; /* Zero-terminate the name */ if (0 != value_len) { mhd_assert (value_start + value_len <= str_len); str[value_start + value_len] = 0; /* Zero-terminate the value */ if (MHD_NO == MHD_set_connection_value_n_nocheck_ (connection, MHD_COOKIE_KIND, str + name_start, name_len, str + value_start, value_len)) return MHD_PARSE_COOKIE_NO_MEMORY; } else { if (MHD_NO == MHD_set_connection_value_n_nocheck_ (connection, MHD_COOKIE_KIND, str + name_start, name_len, "", 0)) return MHD_PARSE_COOKIE_NO_MEMORY; } if (str_len > i) { mhd_assert (0 == str[i] || ';' == str[i]); mhd_assert (! val_quoted || ';' == str[i]); mhd_assert (';' != str[i] || val_quoted || non_strict || 0 == value_len); i++; if (str_len == i) { /* No next cookie after semicolon */ if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } else if (' ' != str[i]) {/* No space after semicolon */ if (('\t' == str[i]) && tab_as_sp) i++; else if (! allow_no_space) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } else { i++; if (str_len == i) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } } } } return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK; } /** * Parse the cookie header (see RFC 6265). * * @param connection connection to parse header of * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise */ static enum _MHD_ParseCookie parse_cookie_header (struct MHD_Connection *connection) { const char *hdr; size_t hdr_len; char *cpy; size_t i; enum _MHD_ParseCookie parse_res; struct MHD_HTTP_Req_Header *const saved_tail = connection->rq.headers_received_tail; const bool allow_partially_correct_cookie = (1 >= connection->daemon->client_discipline); if (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_COOKIE, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_COOKIE), &hdr, &hdr_len)) return MHD_PARSE_COOKIE_OK; if (0 == hdr_len) return MHD_PARSE_COOKIE_OK; cpy = MHD_connection_alloc_memory_ (connection, hdr_len + 1); if (NULL == cpy) parse_res = MHD_PARSE_COOKIE_NO_MEMORY; else { memcpy (cpy, hdr, hdr_len); cpy[hdr_len] = '\0'; i = 0; /* Skip all initial whitespaces */ while (i < hdr_len && (' ' == cpy[i] || '\t' == cpy[i])) i++; parse_res = parse_cookies_string (cpy + i, hdr_len - i, connection); } switch (parse_res) { case MHD_PARSE_COOKIE_OK: break; case MHD_PARSE_COOKIE_OK_LAX: #ifdef HAVE_MESSAGES if (saved_tail != connection->rq.headers_received_tail) MHD_DLOG (connection->daemon, _ ("The Cookie header has been parsed, but it is not fully " "compliant with the standard.\n")); #endif /* HAVE_MESSAGES */ break; case MHD_PARSE_COOKIE_MALFORMED: if (saved_tail != connection->rq.headers_received_tail) { if (! allow_partially_correct_cookie) { /* Remove extracted values from partially broken cookie */ /* Memory remains allocated until the end of the request processing */ connection->rq.headers_received_tail = saved_tail; saved_tail->next = NULL; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Cookie header has been ignored as it contains " "malformed data.\n")); #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("The Cookie header has been only partially parsed as it " "contains malformed data.\n")); #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("The Cookie header has malformed data.\n")); #endif /* HAVE_MESSAGES */ break; case MHD_PARSE_COOKIE_NO_MEMORY: #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection pool to " "parse client cookies!\n")); #endif /* HAVE_MESSAGES */ break; default: mhd_assert (0); break; } #ifndef HAVE_MESSAGES (void) saved_tail; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ return parse_res; } #endif /* COOKIE_SUPPORT */ /** * The valid length of any HTTP version string */ #define HTTP_VER_LEN (MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)) /** * Detect HTTP version, send error response if version is not supported * * @param connection the connection * @param http_string the pointer to HTTP version string * @param len the length of @a http_string in bytes * @return true if HTTP version is correct and supported, * false if HTTP version is not correct or unsupported. */ static bool parse_http_version (struct MHD_Connection *connection, const char *http_string, size_t len) { const char *const h = http_string; /**< short alias */ mhd_assert (NULL != http_string); /* String must start with 'HTTP/d.d', case-sensetive match. * See https://www.rfc-editor.org/rfc/rfc9112#name-http-version */ if ((HTTP_VER_LEN != len) || ('H' != h[0]) || ('T' != h[1]) || ('T' != h[2]) || ('P' != h[3]) || ('/' != h[4]) || ('.' != h[6]) || (('0' > h[5]) || ('9' < h[5])) || (('0' > h[7]) || ('9' < h[7]))) { connection->rq.http_ver = MHD_HTTP_VER_INVALID; transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); return false; } if (1 == h[5] - '0') { /* HTTP/1.x */ if (1 == h[7] - '0') connection->rq.http_ver = MHD_HTTP_VER_1_1; else if (0 == h[7] - '0') connection->rq.http_ver = MHD_HTTP_VER_1_0; else connection->rq.http_ver = MHD_HTTP_VER_1_2__1_9; return true; } if (0 == h[5] - '0') { /* Too old major version */ connection->rq.http_ver = MHD_HTTP_VER_TOO_OLD; transmit_error_response_static (connection, MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, REQ_HTTP_VER_IS_TOO_OLD); return false; } connection->rq.http_ver = MHD_HTTP_VER_FUTURE; transmit_error_response_static (connection, MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, REQ_HTTP_VER_IS_NOT_SUPPORTED); return false; } /** * Detect standard HTTP request method * * @param connection the connection * @param method the pointer to HTTP request method string * @param len the length of @a method in bytes */ static void parse_http_std_method (struct MHD_Connection *connection, const char *method, size_t len) { const char *const m = method; /**< short alias */ mhd_assert (NULL != m); mhd_assert (0 != len); if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_GET, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_GET; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_HEAD) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_HEAD, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_HEAD; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_POST) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_POST, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_POST; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_PUT) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_PUT, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_PUT; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_DELETE) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_DELETE, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_DELETE; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_CONNECT) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_CONNECT, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_CONNECT; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_OPTIONS) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_OPTIONS, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_OPTIONS; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_TRACE) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_TRACE, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_TRACE; else connection->rq.http_mthd = MHD_HTTP_MTHD_OTHER; } /** * Call the handler of the application for this * connection. Handles chunking of the upload * as well as normal uploads. * * @param connection connection we're processing */ static void call_connection_handler (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; size_t processed; if (NULL != connection->rp.response) return; /* already queued a response */ processed = 0; connection->rq.client_aware = true; connection->in_access_handler = true; if (MHD_NO == daemon->default_handler (daemon->default_handler_cls, connection, connection->rq.url, connection->rq.method, connection->rq.version, NULL, &processed, &connection->rq.client_context)) { connection->in_access_handler = false; /* serious internal error, close connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Application reported internal error, " \ "closing connection.")); return; } connection->in_access_handler = false; } /** * Call the handler of the application for this * connection. Handles chunking of the upload * as well as normal uploads. * * @param connection connection we're processing */ static void process_request_body (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; size_t available; bool instant_retry; char *buffer_head; const int discp_lvl = daemon->client_discipline; /* Treat bare LF as the end of the line. RFC 9112, section 2.2-3 Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5). Bare LF is processed as end of the line or rejected as broken request. */ const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl); /* Allow "Bad WhiteSpace" in chunk extension. RFC 9112, Section 7.1.1, Paragraph 2 */ const bool allow_bws = (2 < discp_lvl); mhd_assert (NULL == connection->rp.response); buffer_head = connection->read_buffer; available = connection->read_buffer_offset; do { size_t to_be_processed; size_t left_unprocessed; size_t processed_size; instant_retry = false; if (connection->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size); if ( (connection->rq.current_chunk_offset == connection->rq.current_chunk_size) && (0 != connection->rq.current_chunk_size) ) { size_t i; mhd_assert (0 != available); /* skip new line at the *end* of a chunk */ i = 0; if ( (2 <= available) && ('\r' == buffer_head[0]) && ('\n' == buffer_head[1]) ) i += 2; /* skip CRLF */ else if (bare_lf_as_crlf && ('\n' == buffer_head[0])) i++; /* skip bare LF */ else if (2 > available) break; /* need more upload data */ if (0 == i) { /* malformed encoding */ transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_CHUNKED_MALFORMED); return; } available -= i; buffer_head += i; connection->rq.current_chunk_offset = 0; connection->rq.current_chunk_size = 0; if (0 == available) break; } if (0 != connection->rq.current_chunk_size) { uint64_t cur_chunk_left; mhd_assert (connection->rq.current_chunk_offset < \ connection->rq.current_chunk_size); /* we are in the middle of a chunk, give as much as possible to the client (without crossing chunk boundaries) */ cur_chunk_left = connection->rq.current_chunk_size - connection->rq.current_chunk_offset; if (cur_chunk_left > available) to_be_processed = available; else { /* cur_chunk_left <= (size_t)available */ to_be_processed = (size_t) cur_chunk_left; if (available > to_be_processed) instant_retry = true; } } else { /* Need the parse the chunk size line */ /** The number of found digits in the chunk size number */ size_t num_dig; uint64_t chunk_size; bool broken; bool overflow; mhd_assert (0 != available); overflow = false; chunk_size = 0; /* Mute possible compiler warning. The real value will be set later. */ num_dig = MHD_strx_to_uint64_n_ (buffer_head, available, &chunk_size); mhd_assert (num_dig <= available); if (num_dig == available) continue; /* Need line delimiter */ broken = (0 == num_dig); if (broken) /* Check whether result is invalid due to uint64_t overflow */ overflow = ((('0' <= buffer_head[0]) && ('9' >= buffer_head[0])) || (('A' <= buffer_head[0]) && ('F' >= buffer_head[0])) || (('a' <= buffer_head[0]) && ('f' >= buffer_head[0]))); else { /** * The length of the string with the number of the chunk size, * including chunk extension */ size_t chunk_size_line_len; chunk_size_line_len = 0; if ((';' == buffer_head[num_dig]) || (allow_bws && ((' ' == buffer_head[num_dig]) || ('\t' == buffer_head[num_dig])))) { /* Chunk extension */ size_t i; /* Skip bad whitespaces (if any) */ for (i = num_dig; i < available; ++i) { if ((' ' != buffer_head[i]) && ('\t' != buffer_head[i])) break; } if (i == available) break; /* need more data */ if (';' == buffer_head[i]) { for (++i; i < available; ++i) { if ('\n' == buffer_head[i]) break; } if (i == available) break; /* need more data */ mhd_assert (i > num_dig); mhd_assert (1 <= i); /* Found LF position */ if (bare_lf_as_crlf) chunk_size_line_len = i; /* Don't care about CR before LF */ else if ('\r' == buffer_head[i - 1]) chunk_size_line_len = i; } else { /* No ';' after "bad whitespace" */ mhd_assert (allow_bws); mhd_assert (0 == chunk_size_line_len); } } else { mhd_assert (available >= num_dig); if ((2 <= (available - num_dig)) && ('\r' == buffer_head[num_dig]) && ('\n' == buffer_head[num_dig + 1])) chunk_size_line_len = num_dig + 2; else if (bare_lf_as_crlf && ('\n' == buffer_head[num_dig])) chunk_size_line_len = num_dig + 1; else if (2 > (available - num_dig)) break; /* need more data */ } if (0 != chunk_size_line_len) { /* Valid termination of the chunk size line */ mhd_assert (chunk_size_line_len <= available); /* Start reading payload data of the chunk */ connection->rq.current_chunk_offset = 0; connection->rq.current_chunk_size = chunk_size; available -= chunk_size_line_len; buffer_head += chunk_size_line_len; if (0 == chunk_size) { /* The final (termination) chunk */ connection->rq.remaining_upload_size = 0; break; } if (available > 0) instant_retry = true; continue; } /* Invalid chunk size line */ } if (! overflow) transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_CHUNKED_MALFORMED); else transmit_error_response_static (connection, MHD_HTTP_CONTENT_TOO_LARGE, REQUEST_CHUNK_TOO_LARGE); return; } } else { /* no chunked encoding, give all to the client */ mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size); mhd_assert (0 != connection->rq.remaining_upload_size); if (connection->rq.remaining_upload_size < available) to_be_processed = (size_t) connection->rq.remaining_upload_size; else to_be_processed = available; } left_unprocessed = to_be_processed; connection->rq.client_aware = true; connection->in_access_handler = true; if (MHD_NO == daemon->default_handler (daemon->default_handler_cls, connection, connection->rq.url, connection->rq.method, connection->rq.version, buffer_head, &left_unprocessed, &connection->rq.client_context)) { connection->in_access_handler = false; /* serious internal error, close connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Application reported internal error, " \ "closing connection.")); return; } connection->in_access_handler = false; if (left_unprocessed > to_be_processed) MHD_PANIC (_ ("libmicrohttpd API violation.\n")); connection->rq.some_payload_processed = (left_unprocessed != to_be_processed); if (0 != left_unprocessed) { instant_retry = false; /* client did not process everything */ #ifdef HAVE_MESSAGES if ((! connection->rq.some_payload_processed) && (! connection->suspended)) { /* client did not process any upload data, complain if the setup was incorrect, which may prevent us from handling the rest of the request */ if (MHD_D_IS_USING_THREADS_ (daemon)) MHD_DLOG (daemon, _ ("WARNING: Access Handler Callback has not processed " \ "any upload data and connection is not suspended. " \ "This may result in hung connection.\n")); } #endif /* HAVE_MESSAGES */ } processed_size = to_be_processed - left_unprocessed; /* dh left "processed" bytes in buffer for next time... */ buffer_head += processed_size; available -= processed_size; if (! connection->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size); connection->rq.remaining_upload_size -= processed_size; } else { mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size); connection->rq.current_chunk_offset += processed_size; } } while (instant_retry); /* TODO: zero out reused memory region */ if ( (available > 0) && (buffer_head != connection->read_buffer) ) memmove (connection->read_buffer, buffer_head, available); else mhd_assert ((0 == available) || \ (connection->read_buffer_offset == available)); connection->read_buffer_offset = available; } /** * Check if we are done sending the write-buffer. * If so, transition into "next_state". * * @param connection connection to check write status for * @param next_state the next state to transition to * @return #MHD_NO if we are not done, #MHD_YES if we are */ static enum MHD_Result check_write_done (struct MHD_Connection *connection, enum MHD_CONNECTION_STATE next_state) { if ( (connection->write_buffer_append_offset != connection->write_buffer_send_offset) /* || data_in_tls_buffers == true */ ) return MHD_NO; connection->write_buffer_append_offset = 0; connection->write_buffer_send_offset = 0; connection->state = next_state; return MHD_YES; } /** * Parse the various headers; figure out the size * of the upload and make sure the headers follow * the protocol. Advance to the appropriate state. * * @param connection connection we're processing */ static void parse_connection_headers (struct MHD_Connection *connection) { const char *clen; const char *enc; size_t val_len; #ifdef COOKIE_SUPPORT if (MHD_PARSE_COOKIE_NO_MEMORY == parse_cookie_header (connection)) { handle_req_cookie_no_space (connection); return; } #endif /* COOKIE_SUPPORT */ if ( (-3 < connection->daemon->client_discipline) && (MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) && (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_HOST), NULL, NULL)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Received HTTP/1.1 request without `Host' header.\n")); #endif transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_LACKS_HOST); return; } /* The presence of the request body is indicated by "Content-Length:" or "Transfer-Encoding:" request headers. Unless one of these two headers is used, the request has no request body. See RFC9112, Section 6, paragraph 4. */ connection->rq.remaining_upload_size = 0; if (MHD_NO != MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_TRANSFER_ENCODING, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_TRANSFER_ENCODING), &enc, NULL)) { if (! MHD_str_equal_caseless_ (enc, "chunked")) { transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_UNSUPPORTED_TR_ENCODING); return; } else if (MHD_NO != MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_CONTENT_LENGTH), NULL, NULL)) { /* TODO: add individual settings */ if (1 <= connection->daemon->client_discipline) { transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_LENGTH_WITH_TR_ENCODING); return; } else { /* Must close connection after reply to prevent potential attack */ connection->keepalive = MHD_CONN_MUST_CLOSE; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'Content-Length' request header is ignored " "as chunked Transfer-Encoding is used " "for this request.\n")); #endif /* HAVE_MESSAGES */ } } connection->rq.have_chunked_upload = true; connection->rq.remaining_upload_size = MHD_SIZE_UNKNOWN; } else if (MHD_NO != MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_CONTENT_LENGTH), &clen, &val_len)) { size_t num_digits; num_digits = MHD_str_to_uint64_n_ (clen, val_len, &connection->rq.remaining_upload_size); if (((0 == num_digits) && (0 != val_len) && ('0' <= clen[0]) && ('9' >= clen[0])) || (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size)) { connection->rq.remaining_upload_size = 0; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Too large value of 'Content-Length' header. " \ "Closing connection.\n")); #endif transmit_error_response_static (connection, MHD_HTTP_CONTENT_TOO_LARGE, REQUEST_CONTENTLENGTH_TOOLARGE); } else if ((val_len != num_digits) || (0 == num_digits)) { connection->rq.remaining_upload_size = 0; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to parse 'Content-Length' header. " \ "Closing connection.\n")); #endif transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_CONTENTLENGTH_MALFORMED); } } } /** * Reset request header processing state. * * This function resets the processing state before processing the next header * (or footer) line. * @param c the connection to process */ _MHD_static_inline void reset_rq_header_processing_state (struct MHD_Connection *c) { memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); } /** * Switch to request headers (field lines) processing state. * @param c the connection to process */ _MHD_static_inline void switch_to_rq_headers_processing (struct MHD_Connection *c) { c->rq.field_lines.start = c->read_buffer; memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); c->state = MHD_CONNECTION_REQ_HEADERS_RECEIVING; } #ifndef MHD_MAX_EMPTY_LINES_SKIP /** * The maximum number of ignored empty line before the request line * at default "strictness" level. */ #define MHD_MAX_EMPTY_LINES_SKIP 1024 #endif /* ! MHD_MAX_EMPTY_LINES_SKIP */ /** * Find and parse the request line. * @param c the connection to process * @return true if request line completely processed (or unrecoverable error * found) and state is changed, * false if not enough data yet in the receive buffer */ static bool get_request_line_inner (struct MHD_Connection *c) { size_t p; /**< The current processing position */ const int discp_lvl = c->daemon->client_discipline; /* Allow to skip one or more empty lines before the request line. RFC 9112, section 2.2 */ const bool skip_empty_lines = (1 >= discp_lvl); /* Allow to skip more then one empty line before the request line. RFC 9112, section 2.2 */ const bool skip_several_empty_lines = (skip_empty_lines && (0 >= discp_lvl)); /* Allow to skip number of unlimited empty lines before the request line. RFC 9112, section 2.2 */ const bool skip_unlimited_empty_lines = (skip_empty_lines && (-3 >= discp_lvl)); /* Treat bare LF as the end of the line. RFC 9112, section 2.2 */ const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl); /* Treat tab as whitespace delimiter. RFC 9112, section 3 */ const bool tab_as_wsp = (0 >= discp_lvl); /* Treat VT (vertical tab) and FF (form feed) as whitespace delimiters. RFC 9112, section 3 */ const bool other_wsp_as_wsp = (-1 >= discp_lvl); /* Treat continuous whitespace block as a single space. RFC 9112, section 3 */ const bool wsp_blocks = (-1 >= discp_lvl); /* Parse whitespace in URI, special parsing of the request line. RFC 9112, section 3.2 */ const bool wsp_in_uri = (0 >= discp_lvl); /* Keep whitespace in URI, give app URI with whitespace instead of automatic redirect to fixed URI. Violates RFC 9112, section 3.2 */ const bool wsp_in_uri_keep = (-2 >= discp_lvl); /* Keep bare CR character as is. Violates RFC 9112, section 2.2 */ const bool bare_cr_keep = (wsp_in_uri_keep && (-3 >= discp_lvl)); /* Treat bare CR as space; replace it with space before processing. RFC 9112, section 2.2 */ const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl)); mhd_assert (MHD_CONNECTION_INIT == c->state || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.method || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \ 0 != c->rq.hdrs.rq_line.proc_pos); if (0 == c->read_buffer_offset) { mhd_assert (MHD_CONNECTION_INIT == c->state); return false; /* No data to process */ } p = c->rq.hdrs.rq_line.proc_pos; mhd_assert (p <= c->read_buffer_offset); /* Skip empty lines, if any (and if allowed) */ /* See RFC 9112, section 2.2 */ if ((0 == p) && (skip_empty_lines)) { /* Skip empty lines before the request line. See RFC 9112, section 2.2 */ bool is_empty_line; mhd_assert (MHD_CONNECTION_INIT == c->state); mhd_assert (NULL == c->rq.method); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt); mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); do { is_empty_line = false; if ('\r' == c->read_buffer[0]) { if (1 == c->read_buffer_offset) return false; /* Not enough data yet */ if ('\n' == c->read_buffer[1]) { is_empty_line = true; c->read_buffer += 2; c->read_buffer_size -= 2; c->read_buffer_offset -= 2; c->rq.hdrs.rq_line.skipped_empty_lines++; } } else if (('\n' == c->read_buffer[0]) && (bare_lf_as_crlf)) { is_empty_line = true; c->read_buffer += 1; c->read_buffer_size -= 1; c->read_buffer_offset -= 1; c->rq.hdrs.rq_line.skipped_empty_lines++; } if (is_empty_line) { if ((! skip_unlimited_empty_lines) && (((unsigned int) ((skip_several_empty_lines) ? MHD_MAX_EMPTY_LINES_SKIP : 1)) < c->rq.hdrs.rq_line.skipped_empty_lines)) { connection_close_error (c, _ ("Too many meaningless extra empty lines " \ "received before the request")); return true; /* Process connection closure */ } if (0 == c->read_buffer_offset) return false; /* No more data to process */ } } while (is_empty_line); } /* All empty lines are skipped */ c->state = MHD_CONNECTION_REQ_LINE_RECEIVING; /* Read and parse the request line */ mhd_assert (1 <= c->read_buffer_offset); while (p < c->read_buffer_offset) { const char chr = c->read_buffer[p]; bool end_of_line; /* The processing logic is different depending on the configured strictness: When whitespace BLOCKS are NOT ALLOWED, the end of the whitespace is processed BEFORE processing of the current character. When whitespace BLOCKS are ALLOWED, the end of the whitespace is processed AFTER processing of the current character. When space char in the URI is ALLOWED, the delimiter between the URI and the HTTP version string is processed only at the END of the line. When space in the URI is NOT ALLOWED, the delimiter between the URI and the HTTP version string is processed as soon as the FIRST whitespace is found after URI start. */ end_of_line = false; mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \ (c->rq.hdrs.rq_line.last_ws_end > \ c->rq.hdrs.rq_line.last_ws_start)); mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_start) || \ (0 != c->rq.hdrs.rq_line.last_ws_end)); /* Check for the end of the line */ if ('\r' == chr) { if (p + 1 == c->read_buffer_offset) { c->rq.hdrs.rq_line.proc_pos = p; return false; /* Not enough data yet */ } else if ('\n' == c->read_buffer[p + 1]) end_of_line = true; else { /* Bare CR alone */ /* Must be rejected or replaced with space char. See RFC 9112, section 2.2 */ if (bare_cr_as_sp) { c->read_buffer[p] = ' '; c->rq.num_cr_sp_replaced++; continue; /* Re-start processing of the current character */ } else if (! bare_cr_keep) { /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_HEADER); } else connection_close_error (c, _ ("Bare CR characters are not allowed " \ "in the request line.\n")); return true; /* Error in the request */ } } } else if ('\n' == chr) { /* Bare LF may be recognised as a line delimiter. See RFC 9112, section 2.2 */ if (bare_lf_as_crlf) end_of_line = true; else { /* While RFC does not enforce error for bare LF character, if this char is not treated as a line delimiter, it should be rejected to avoid any security weakness due to request smuggling. */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_HEADER); } else connection_close_error (c, _ ("Bare LF characters are not allowed " \ "in the request line.\n")); return true; /* Error in the request */ } } if (end_of_line) { /* Handle the end of the request line */ if (NULL != c->rq.method) { if (wsp_in_uri) { /* The end of the URI and the start of the HTTP version string should be determined now. */ mhd_assert (NULL == c->rq.version); mhd_assert (0 == c->rq.req_target_len); if (0 != c->rq.hdrs.rq_line.last_ws_end) { /* Determine the end and the length of the URI */ if (NULL != c->rq.hdrs.rq_line.rq_tgt) { c->read_buffer [c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */ c->rq.req_target_len = c->rq.hdrs.rq_line.last_ws_start - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer); } else if ((c->rq.hdrs.rq_line.last_ws_start + 1 < c->rq.hdrs.rq_line.last_ws_end) && (HTTP_VER_LEN == (p - c->rq.hdrs.rq_line.last_ws_end))) { /* Found only HTTP method and HTTP version and more than one whitespace between them. Assume zero-length URI. */ mhd_assert (wsp_blocks); c->rq.hdrs.rq_line.last_ws_start++; c->read_buffer[c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */ c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + c->rq.hdrs.rq_line.last_ws_start; c->rq.req_target_len = 0; c->rq.hdrs.rq_line.num_ws_in_uri = 0; c->rq.hdrs.rq_line.rq_tgt_qmark = NULL; } /* Determine the start of the HTTP version string */ if (NULL != c->rq.hdrs.rq_line.rq_tgt) { c->rq.version = c->read_buffer + c->rq.hdrs.rq_line.last_ws_end; } } } else { /* The end of the URI and the start of the HTTP version string should be already known. */ if ((NULL == c->rq.version) && (NULL != c->rq.hdrs.rq_line.rq_tgt) && (HTTP_VER_LEN == p - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer)) && (0 != c->read_buffer[(size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer) - 1])) { /* Found only HTTP method and HTTP version and more than one whitespace between them. Assume zero-length URI. */ size_t uri_pos; mhd_assert (wsp_blocks); mhd_assert (0 == c->rq.req_target_len); uri_pos = (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer) - 1; mhd_assert (uri_pos < p); c->rq.version = c->rq.hdrs.rq_line.rq_tgt; c->read_buffer[uri_pos] = 0; /* Zero terminate the URI */ c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + uri_pos; c->rq.req_target_len = 0; c->rq.hdrs.rq_line.num_ws_in_uri = 0; c->rq.hdrs.rq_line.rq_tgt_qmark = NULL; } } if (NULL != c->rq.version) { mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); if (! parse_http_version (c, c->rq.version, p - (size_t) (c->rq.version - c->read_buffer))) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state); return true; /* Unsupported / broken HTTP version */ } c->read_buffer[p] = 0; /* Zero terminate the HTTP version strings */ if ('\r' == chr) { p++; /* Consume CR */ mhd_assert (p < c->read_buffer_offset); /* The next character has been already checked */ } p++; /* Consume LF */ c->read_buffer += p; c->read_buffer_size -= p; c->read_buffer_offset -= p; mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \ c->rq.req_target_len); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (0 != c->rq.req_target_len)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ ((size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \ - c->rq.hdrs.rq_line.rq_tgt) < \ c->rq.req_target_len)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.hdrs.rq_line.rq_tgt_qmark >= \ c->rq.hdrs.rq_line.rq_tgt)); return true; /* The request line is successfully parsed */ } } /* Error in the request line */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); } else connection_close_error (c, _ ("The request line is malformed.\n")); return true; } /* Process possible end of the previously found whitespace delimiter */ if ((! wsp_blocks) && (p == c->rq.hdrs.rq_line.last_ws_end) && (0 != c->rq.hdrs.rq_line.last_ws_end)) { /* Previous character was a whitespace char and whitespace blocks are not allowed. */ /* The current position is the next character after a whitespace delimiter */ if (NULL == c->rq.hdrs.rq_line.rq_tgt) { /* The current position is the start of the URI */ mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } else { /* It was a whitespace after the start of the URI */ if (! wsp_in_uri) { mhd_assert ((0 != c->rq.req_target_len) || \ (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p)); mhd_assert (NULL == c->rq.version); /* Too many whitespaces? This error is handled at whitespace start */ c->rq.version = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } } } /* Process the current character. Is it not the end of the line. */ if ((' ' == chr) || (('\t' == chr) && (tab_as_wsp)) || ((other_wsp_as_wsp) && ((0xb == chr) || (0xc == chr)))) { /* A whitespace character */ if ((0 == c->rq.hdrs.rq_line.last_ws_end) || (p != c->rq.hdrs.rq_line.last_ws_end) || (! wsp_blocks)) { /* Found first whitespace char of the new whitespace block */ if (NULL == c->rq.method) { /* Found the end of the HTTP method string */ mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_start); mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_end); mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt); mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); if (0 == p) { connection_close_error (c, _ ("The request line starts with " "a whitespace.\n")); return true; /* Error in the request */ } c->read_buffer[p] = 0; /* Zero-terminate the request method string */ c->rq.method = c->read_buffer; parse_http_std_method (c, c->rq.method, p); } else { /* A whitespace after the start of the URI */ if (! wsp_in_uri) { /* Whitespace in URI is not allowed to be parsed */ if (NULL == c->rq.version) { mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); /* This is a delimiter between URI and HTTP version string */ c->read_buffer[p] = 0; /* Zero-terminate request URI string */ mhd_assert (((size_t) (c->rq.hdrs.rq_line.rq_tgt \ - c->read_buffer)) <= p); c->rq.req_target_len = p - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer); } else { /* This is a delimiter AFTER version string */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, RQ_LINE_TOO_MANY_WSP); } else connection_close_error (c, _ ("The request line has more than " "two whitespaces.\n")); return true; /* Error in the request */ } } else { /* Whitespace in URI is allowed to be parsed */ if (0 != c->rq.hdrs.rq_line.last_ws_end) { /* The whitespace after the start of the URI has been found already */ c->rq.hdrs.rq_line.num_ws_in_uri += c->rq.hdrs.rq_line.last_ws_end - c->rq.hdrs.rq_line.last_ws_start; } } } c->rq.hdrs.rq_line.last_ws_start = p; c->rq.hdrs.rq_line.last_ws_end = p + 1; /* Will be updated on the next char parsing */ } else { /* Continuation of the whitespace block */ mhd_assert (0 != c->rq.hdrs.rq_line.last_ws_end); mhd_assert (0 != p); c->rq.hdrs.rq_line.last_ws_end = p + 1; } } else { /* Non-whitespace char, not the end of the line */ mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \ (c->rq.hdrs.rq_line.last_ws_end == p) || \ wsp_in_uri); if ((p == c->rq.hdrs.rq_line.last_ws_end) && (0 != c->rq.hdrs.rq_line.last_ws_end) && (wsp_blocks)) { /* The end of the whitespace block */ if (NULL == c->rq.hdrs.rq_line.rq_tgt) { /* This is the first character of the URI */ mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } else { if (! wsp_in_uri) { /* This is the first character of the HTTP version */ mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); mhd_assert ((0 != c->rq.req_target_len) || \ (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p)); mhd_assert (NULL == c->rq.version); /* Handled at whitespace start */ c->rq.version = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } } } /* Handle other special characters */ if ('?' == chr) { if ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) && (NULL != c->rq.hdrs.rq_line.rq_tgt)) { c->rq.hdrs.rq_line.rq_tgt_qmark = c->read_buffer + p; } } else if ((0xb == chr) || (0xc == chr)) { /* VT or LF characters */ mhd_assert (! other_wsp_as_wsp); if ((NULL != c->rq.hdrs.rq_line.rq_tgt) && (NULL == c->rq.version) && (wsp_in_uri)) { c->rq.hdrs.rq_line.num_ws_in_uri++; } else { connection_close_error (c, _ ("Invalid character is in the " "request line.\n")); return true; /* Error in the request */ } } else if (0 == chr) { /* NUL character */ connection_close_error (c, _ ("The NUL character is in the " "request line.\n")); return true; /* Error in the request */ } } p++; } c->rq.hdrs.rq_line.proc_pos = p; return false; /* Not enough data yet */ } #ifndef MHD_MAX_FIXED_URI_LEN /** * The maximum size of the fixed URI for automatic redirection */ #define MHD_MAX_FIXED_URI_LEN (64 * 1024) #endif /* ! MHD_MAX_FIXED_URI_LEN */ /** * Send the automatic redirection to fixed URI when received URI with * whitespaces. * If URI is too large, close connection with error. * * @param c the connection to process */ static void send_redirect_fixed_rq_target (struct MHD_Connection *c) { char *b; size_t fixed_uri_len; size_t i; size_t o; char *hdr_name; size_t hdr_name_len; mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (0 != c->rq.hdrs.rq_line.num_ws_in_uri); mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \ c->rq.req_target_len); fixed_uri_len = c->rq.req_target_len + 2 * c->rq.hdrs.rq_line.num_ws_in_uri; if ( (fixed_uri_len + 200 > c->daemon->pool_size) || (fixed_uri_len > MHD_MAX_FIXED_URI_LEN) || (NULL == (b = malloc (fixed_uri_len + 1))) ) { connection_close_error (c, _ ("The request has whitespace character is " \ "in the URI and the URI is too large to " \ "send automatic redirect to fixed URI.\n")); return; } i = 0; o = 0; do { const char chr = c->rq.hdrs.rq_line.rq_tgt[i++]; mhd_assert ('\r' != chr); /* Replaced during request line parsing */ mhd_assert ('\n' != chr); /* Rejected during request line parsing */ mhd_assert (0 != chr); /* Rejected during request line parsing */ switch (chr) { case ' ': b[o++] = '%'; b[o++] = '2'; b[o++] = '0'; break; case '\t': b[o++] = '%'; b[o++] = '0'; b[o++] = '9'; break; case 0x0B: /* VT (vertical tab) */ b[o++] = '%'; b[o++] = '0'; b[o++] = 'B'; break; case 0x0C: /* FF (form feed) */ b[o++] = '%'; b[o++] = '0'; b[o++] = 'C'; break; default: b[o++] = chr; break; } } while (i < c->rq.req_target_len); mhd_assert (fixed_uri_len == o); b[o] = 0; /* Zero-terminate the result */ hdr_name_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_LOCATION); hdr_name = malloc (hdr_name_len + 1); if (NULL != hdr_name) { memcpy (hdr_name, MHD_HTTP_HEADER_LOCATION, hdr_name_len + 1); /* hdr_name and b are free()d within this call */ transmit_error_response_header (c, MHD_HTTP_MOVED_PERMANENTLY, RQ_TARGET_INVALID_CHAR, hdr_name, hdr_name_len, b, o); return; } free (b); connection_close_error (c, _ ("The request has whitespace character is in the " \ "URI.\n")); return; } /** * Process request-target string, form URI and URI parameters * @param c the connection to process * @return true if request-target successfully processed, * false if error encountered */ static bool process_request_target (struct MHD_Connection *c) { #ifdef _DEBUG size_t params_len; #endif /* _DEBUG */ mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.hdrs.rq_line.rq_tgt <= c->rq.hdrs.rq_line.rq_tgt_qmark)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.req_target_len > \ (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \ - c->rq.hdrs.rq_line.rq_tgt))); /* Log callback before the request-target is modified/decoded */ if (NULL != c->daemon->uri_log_callback) { c->rq.client_aware = true; c->rq.client_context = c->daemon->uri_log_callback (c->daemon->uri_log_callback_cls, c->rq.hdrs.rq_line.rq_tgt, c); } if (NULL != c->rq.hdrs.rq_line.rq_tgt_qmark) { #ifdef _DEBUG params_len = c->rq.req_target_len - (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark - c->rq.hdrs.rq_line.rq_tgt); #endif /* _DEBUG */ c->rq.hdrs.rq_line.rq_tgt_qmark[0] = 0; /* Replace '?' with zero termination */ if (MHD_NO == MHD_parse_arguments_ (c, MHD_GET_ARGUMENT_KIND, c->rq.hdrs.rq_line.rq_tgt_qmark + 1, &connection_add_header, c)) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING != c->state); return false; } } #ifdef _DEBUG else params_len = 0; #endif /* _DEBUG */ mhd_assert (strlen (c->rq.hdrs.rq_line.rq_tgt) == \ c->rq.req_target_len - params_len); /* Finally unescape URI itself */ c->rq.url_len = c->daemon->unescape_callback (c->daemon->unescape_callback_cls, c, c->rq.hdrs.rq_line.rq_tgt); c->rq.url = c->rq.hdrs.rq_line.rq_tgt; return true; } /** * Find and parse the request line. * Advance to the next state when done, handle errors. * @param c the connection to process * @return true if request line completely processed and state is changed, * false if not enough data yet in the receive buffer */ static bool get_request_line (struct MHD_Connection *c) { const int discp_lvl = c->daemon->client_discipline; /* Parse whitespace in URI, special parsing of the request line */ const bool wsp_in_uri = (0 >= discp_lvl); /* Keep whitespace in URI, give app URI with whitespace instead of automatic redirect to fixed URI */ const bool wsp_in_uri_keep = (-2 >= discp_lvl); if (! get_request_line_inner (c)) { /* End of the request line has not been found yet */ mhd_assert ((! wsp_in_uri) || NULL == c->rq.version); if ((NULL != c->rq.version) && (HTTP_VER_LEN < (c->rq.hdrs.rq_line.proc_pos - (size_t) (c->rq.version - c->read_buffer)))) { c->rq.http_ver = MHD_HTTP_VER_INVALID; transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); return true; /* Error in the request */ } return false; } if (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state) return true; /* Error in the request */ mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); if (0 != c->rq.hdrs.rq_line.num_ws_in_uri) { if (! wsp_in_uri) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, RQ_TARGET_INVALID_CHAR); return true; /* Error in the request */ } if (! wsp_in_uri_keep) { send_redirect_fixed_rq_target (c); return true; /* Error in the request */ } } if (! process_request_target (c)) return true; /* Error in processing */ c->state = MHD_CONNECTION_REQ_LINE_RECEIVED; return true; } /** * Results of header line reading */ enum MHD_HdrLineReadRes_ { /** * Not enough data yet */ MHD_HDR_LINE_READING_NEED_MORE_DATA = 0, /** * New header line has been read */ MHD_HDR_LINE_READING_GOT_HEADER, /** * Error in header data, error response has been queued */ MHD_HDR_LINE_READING_DATA_ERROR, /** * Found the end of the request header (end of field lines) */ MHD_HDR_LINE_READING_GOT_END_OF_HEADER } _MHD_FIXED_ENUM; /** * Find the end of the request header line and make basic header parsing. * Handle errors and header folding. * @param c the connection to process * @param process_footers if true then footers are processed, * if false then headers are processed * @param[out] hdr_name the name of the parsed header (field) * @param[out] hdr_name the value of the parsed header (field) * @return true if request header line completely processed, * false if not enough data yet in the receive buffer */ static enum MHD_HdrLineReadRes_ get_req_header (struct MHD_Connection *c, bool process_footers, struct _MHD_str_w_len *hdr_name, struct _MHD_str_w_len *hdr_value) { const int discp_lvl = c->daemon->client_discipline; /* Treat bare LF as the end of the line. RFC 9112, section 2.2-3 Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5). Bare LF is processed as end of the line or rejected as broken request. */ const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl); /* Keep bare CR character as is. Violates RFC 9112, section 2.2-4 */ const bool bare_cr_keep = (-3 >= discp_lvl); /* Treat bare CR as space; replace it with space before processing. RFC 9112, section 2.2-4 */ const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl)); /* Treat NUL as space; replace it with space before processing. RFC 9110, section 5.5-5 */ const bool nul_as_sp = (-1 >= discp_lvl); /* Allow folded header lines. RFC 9112, section 5.2-4 */ const bool allow_folded = (0 >= discp_lvl); /* Do not reject headers with the whitespace at the start of the first line. When allowed, the first line with whitespace character at the first position is ignored (as well as all possible line foldings of the first line). RFC 9112, section 2.2-8 */ const bool allow_wsp_at_start = allow_folded && (-1 >= discp_lvl); /* Allow whitespace in header (field) name. Violates RFC 9110, section 5.1-2 */ const bool allow_wsp_in_name = (-2 >= discp_lvl); /* Allow zero-length header (field) name. Violates RFC 9110, section 5.1-2 */ const bool allow_empty_name = (-2 >= discp_lvl); /* Allow whitespace before colon. Violates RFC 9112, section 5.1-2 */ const bool allow_wsp_before_colon = (-3 >= discp_lvl); /* Do not abort the request when header line has no colon, just skip such bad lines. RFC 9112, section 5-1 */ const bool allow_line_without_colon = (-2 >= discp_lvl); size_t p; /**< The position of the currently processed character */ #if ! defined (HAVE_MESSAGES) && ! defined(_DEBUG) (void) process_footers; /* Unused parameter */ #endif /* !HAVE_MESSAGES && !_DEBUG */ mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); p = c->rq.hdrs.hdr.proc_pos; mhd_assert (p <= c->read_buffer_offset); while (p < c->read_buffer_offset) { const char chr = c->read_buffer[p]; bool end_of_line; mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.name_len < p)); mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || (0 != p)); mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.name_end_found)); mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \ (c->rq.hdrs.hdr.name_len < c->rq.hdrs.hdr.value_start)); mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \ (0 != c->rq.hdrs.hdr.name_len)); mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \ (0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.name_len)); mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \ (0 == c->rq.hdrs.hdr.value_start) || \ (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start)); /* Check for the end of the line */ if ('\r' == chr) { if (0 != p) { /* Line is not empty, need to check for possible line folding */ if (p + 2 >= c->read_buffer_offset) break; /* Not enough data yet to check for folded line */ } else { /* Line is empty, no need to check for possible line folding */ if (p + 2 > c->read_buffer_offset) break; /* Not enough data yet to check for the end of the line */ } if ('\n' == c->read_buffer[p + 1]) end_of_line = true; else { /* Bare CR alone */ /* Must be rejected or replaced with space char. See RFC 9112, section 2.2-4 */ if (bare_cr_as_sp) { c->read_buffer[p] = ' '; c->rq.num_cr_sp_replaced++; continue; /* Re-start processing of the current character */ } else if (! bare_cr_keep) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } end_of_line = false; } } else if ('\n' == chr) { /* Bare LF may be recognised as a line delimiter. See RFC 9112, section 2.2-3 */ if (bare_lf_as_crlf) { if (0 != p) { /* Line is not empty, need to check for possible line folding */ if (p + 1 >= c->read_buffer_offset) break; /* Not enough data yet to check for folded line */ } end_of_line = true; } else { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } } else end_of_line = false; if (end_of_line) { /* Handle the end of the line */ /** * The full length of the line, including CRLF (or bare LF). */ const size_t line_len = p + (('\r' == chr) ? 2 : 1); char next_line_char; mhd_assert (line_len <= c->read_buffer_offset); if (0 == p) { /* Zero-length header line. This is the end of the request header section. RFC 9112, Section 2.1-1 */ mhd_assert (! c->rq.hdrs.hdr.starts_with_ws); mhd_assert (! c->rq.hdrs.hdr.name_end_found); mhd_assert (0 == c->rq.hdrs.hdr.name_len); mhd_assert (0 == c->rq.hdrs.hdr.ws_start); mhd_assert (0 == c->rq.hdrs.hdr.value_start); /* Consume the line with CRLF (or bare LF) */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; return MHD_HDR_LINE_READING_GOT_END_OF_HEADER; } mhd_assert (line_len < c->read_buffer_offset); mhd_assert (0 != line_len); mhd_assert ('\n' == c->read_buffer[line_len - 1]); next_line_char = c->read_buffer[line_len]; if ((' ' == next_line_char) || ('\t' == next_line_char)) { /* Folded line */ if (! allow_folded) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_OBS_FOLD); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_OBS_FOLD_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } /* Replace CRLF (or bare LF) character(s) with space characters. See RFC 9112, Section 5.2-4 */ c->read_buffer[p] = ' '; if ('\r' == chr) c->read_buffer[p + 1] = ' '; continue; /* Re-start processing of the current character */ } else { /* It is not a folded line, it's the real end of the non-empty line */ bool skip_line = false; mhd_assert (0 != p); if (c->rq.hdrs.hdr.starts_with_ws) { /* This is the first line and it starts with whitespace. This line must be discarded completely. See RFC 9112, Section 2.2-8 */ mhd_assert (allow_wsp_at_start); #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Whitespace-prefixed first header line " \ "has been skipped.\n")); #endif /* HAVE_MESSAGES */ skip_line = true; } else if (! c->rq.hdrs.hdr.name_end_found) { if (! allow_line_without_colon) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_HEADER_WITHOUT_COLON); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_FOOTER_WITHOUT_COLON); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } /* Skip broken line completely */ c->rq.skipped_broken_lines++; skip_line = true; } if (skip_line) { /* Skip the entire line */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; p = 0; /* Reset processing state */ memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); /* Start processing of the next line */ continue; } else { /* This line should be valid header line */ size_t value_len; mhd_assert ((0 != c->rq.hdrs.hdr.name_len) || allow_empty_name); hdr_name->str = c->read_buffer + 0; /* The name always starts at the first character */ hdr_name->len = c->rq.hdrs.hdr.name_len; mhd_assert (0 == hdr_name->str[hdr_name->len]); if (0 == c->rq.hdrs.hdr.value_start) { c->rq.hdrs.hdr.value_start = p; c->read_buffer[p] = 0; value_len = 0; } else if (0 != c->rq.hdrs.hdr.ws_start) { mhd_assert (p > c->rq.hdrs.hdr.ws_start); mhd_assert (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start); c->read_buffer[c->rq.hdrs.hdr.ws_start] = 0; value_len = c->rq.hdrs.hdr.ws_start - c->rq.hdrs.hdr.value_start; } else { mhd_assert (p > c->rq.hdrs.hdr.ws_start); c->read_buffer[p] = 0; value_len = p - c->rq.hdrs.hdr.value_start; } hdr_value->str = c->read_buffer + c->rq.hdrs.hdr.value_start; hdr_value->len = value_len; mhd_assert (0 == hdr_value->str[hdr_value->len]); /* Consume the entire line */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; return MHD_HDR_LINE_READING_GOT_HEADER; } } } else if ((' ' == chr) || ('\t' == chr)) { if (0 == p) { if (! allow_wsp_at_start) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_BEFORE_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_BEFORE_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.starts_with_ws = true; } else if ((! c->rq.hdrs.hdr.name_end_found) && (! c->rq.hdrs.hdr.starts_with_ws)) { /* Whitespace in header name / between header name and colon */ if (allow_wsp_in_name || allow_wsp_before_colon) { if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.ws_start = p; } else { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } } else { /* Whitespace before/inside/after header (field) value */ if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.ws_start = p; } } else if (0 == chr) { if (! nul_as_sp) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_INVALID_CHR_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_INVALID_CHR_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->read_buffer[p] = ' '; continue; /* Re-start processing of the current character */ } else { /* Not a whitespace, not the end of the header line */ mhd_assert ('\r' != chr); mhd_assert ('\n' != chr); mhd_assert ('\0' != chr); if ((! c->rq.hdrs.hdr.name_end_found) && (! c->rq.hdrs.hdr.starts_with_ws)) { /* Processing the header (field) name */ if (':' == chr) { if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.name_len = p; else { mhd_assert (allow_wsp_in_name || allow_wsp_before_colon); if (! allow_wsp_before_colon) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.name_len = c->rq.hdrs.hdr.ws_start; #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } if ((0 == c->rq.hdrs.hdr.name_len) && ! allow_empty_name) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_EMPTY_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_EMPTY_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.name_end_found = true; c->read_buffer[c->rq.hdrs.hdr.name_len] = 0; /* Zero-terminate the name */ } else { if (0 != c->rq.hdrs.hdr.ws_start) { /* End of the whitespace in header (field) name */ mhd_assert (allow_wsp_in_name || allow_wsp_before_colon); if (! allow_wsp_in_name) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } } } else { /* Processing the header (field) value */ if (0 == c->rq.hdrs.hdr.value_start) c->rq.hdrs.hdr.value_start = p; #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } #ifdef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* MHD_FAVOR_SMALL_CODE */ } p++; } c->rq.hdrs.hdr.proc_pos = p; return MHD_HDR_LINE_READING_NEED_MORE_DATA; /* Not enough data yet */ } /** * Find the end of the request headers and make basic header parsing. * Advance to the next state when done, handle errors. * @param c the connection to process * @param process_footers if true then footers are processed, * if false then headers are processed * @return true if request headers reading finished (either successfully * or with error), * false if not enough data yet in the receive buffer */ static bool get_req_headers (struct MHD_Connection *c, bool process_footers) { do { struct _MHD_str_w_len hdr_name; struct _MHD_str_w_len hdr_value; enum MHD_HdrLineReadRes_ res; mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); #ifdef _DEBUG hdr_name.str = NULL; hdr_value.str = NULL; #endif /* _DEBUG */ res = get_req_header (c, process_footers, &hdr_name, &hdr_value); if (MHD_HDR_LINE_READING_GOT_HEADER == res) { mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); mhd_assert (NULL != hdr_name.str); mhd_assert (NULL != hdr_value.str); /* Values must be zero-terminated and must not have binary zeros */ mhd_assert (strlen (hdr_name.str) == hdr_name.len); mhd_assert (strlen (hdr_value.str) == hdr_value.len); /* Values must not have whitespaces at the start or at the end */ mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != ' ')); mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != '\t')); mhd_assert ((hdr_name.len == 0) || \ (hdr_name.str[hdr_name.len - 1] != ' ')); mhd_assert ((hdr_name.len == 0) || \ (hdr_name.str[hdr_name.len - 1] != '\t')); mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != ' ')); mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != '\t')); mhd_assert ((hdr_value.len == 0) || \ (hdr_value.str[hdr_value.len - 1] != ' ')); mhd_assert ((hdr_value.len == 0) || \ (hdr_value.str[hdr_value.len - 1] != '\t')); if (MHD_NO == MHD_set_connection_value_n_nocheck_ (c, (! process_footers) ? MHD_HEADER_KIND : MHD_FOOTER_KIND, hdr_name.str, hdr_name.len, hdr_value.str, hdr_value.len)) { size_t add_element_size; mhd_assert (hdr_name.str < hdr_value.str); #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Failed to allocate memory in the connection memory " \ "pool to store %s.\n"), (! process_footers) ? _ ("header") : _ ("footer")); #endif /* HAVE_MESSAGES */ add_element_size = hdr_value.len + (size_t) (hdr_value.str - hdr_name.str); if (! process_footers) handle_req_headers_no_space (c, hdr_name.str, add_element_size); else handle_req_footers_no_space (c, hdr_name.str, add_element_size); mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED < c->state); return true; } /* Reset processing state */ reset_rq_header_processing_state (c); mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); /* Read the next header (field) line */ continue; } else if (MHD_HDR_LINE_READING_NEED_MORE_DATA == res) { mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); return false; } else if (MHD_HDR_LINE_READING_DATA_ERROR == res) { mhd_assert ((process_footers ? \ MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) < c->state); mhd_assert (c->stop_with_error); mhd_assert (c->discard_request); return true; } mhd_assert (MHD_HDR_LINE_READING_GOT_END_OF_HEADER == res); break; } while (1); #ifdef HAVE_MESSAGES if (1 == c->rq.num_cr_sp_replaced) { MHD_DLOG (c->daemon, _ ("One bare CR character has been replaced with space " \ "in %s.\n"), (! process_footers) ? _ ("the request line or in the request headers") : _ ("the request footers")); } else if (0 != c->rq.num_cr_sp_replaced) { MHD_DLOG (c->daemon, _ ("%" PRIu64 " bare CR characters have been replaced with " \ "spaces in the request line and/or in the request %s.\n"), (uint64_t) c->rq.num_cr_sp_replaced, (! process_footers) ? _ ("headers") : _ ("footers")); } if (1 == c->rq.skipped_broken_lines) { MHD_DLOG (c->daemon, _ ("One %s line without colon has been skipped.\n"), (! process_footers) ? _ ("header") : _ ("footer")); } else if (0 != c->rq.skipped_broken_lines) { MHD_DLOG (c->daemon, _ ("%" PRIu64 " %s lines without colons has been skipped.\n"), (uint64_t) c->rq.skipped_broken_lines, (! process_footers) ? _ ("header") : _ ("footer")); } #endif /* HAVE_MESSAGES */ mhd_assert (c->rq.method < c->read_buffer); if (! process_footers) { c->rq.header_size = (size_t) (c->read_buffer - c->rq.method); mhd_assert (NULL != c->rq.field_lines.start); c->rq.field_lines.size = (size_t) ((c->read_buffer - c->rq.field_lines.start) - 1); if ('\r' == *(c->read_buffer - 2)) c->rq.field_lines.size--; c->state = MHD_CONNECTION_HEADERS_RECEIVED; if (MHD_BUF_INC_SIZE > c->read_buffer_size) { /* Try to re-use some of the last bytes of the request header */ /* Do this only if space in the read buffer is limited AND amount of read ahead data is small. */ /** * The position of the terminating NUL after the last character of * the last header element. */ const char *last_elmnt_end; size_t shift_back_size; if (NULL != c->rq.headers_received_tail) last_elmnt_end = c->rq.headers_received_tail->value + c->rq.headers_received_tail->value_size; else last_elmnt_end = c->rq.version + HTTP_VER_LEN; mhd_assert ((last_elmnt_end + 1) < c->read_buffer); shift_back_size = (size_t) (c->read_buffer - (last_elmnt_end + 1)); if (0 != c->read_buffer_offset) memmove (c->read_buffer - shift_back_size, c->read_buffer, c->read_buffer_offset); c->read_buffer -= shift_back_size; c->read_buffer_size += shift_back_size; } } else c->state = MHD_CONNECTION_FOOTERS_RECEIVED; return true; } /** * Update the 'last_activity' field of the connection to the current time * and move the connection to the head of the 'normal_timeout' list if * the timeout for the connection uses the default value. * * @param connection the connection that saw some activity */ void MHD_update_last_activity_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (0 == connection->connection_timeout_ms) return; /* Skip update of activity for connections without timeout timer. */ if (connection->suspended) return; /* no activity on suspended connections */ connection->last_activity = MHD_monotonic_msec_counter (); if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) return; /* each connection has personal timeout */ if (connection->connection_timeout_ms != daemon->connection_timeout_ms) return; /* custom timeout, no need to move it in "normal" DLL */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif /* move connection to head of timeout list (by remove + add operation) */ XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * This function handles a particular connection when it has been * determined that there is data to be read off a socket. All * implementations (multithreaded, external polling, internal polling) * call this function to handle reads. * * @param connection connection to handle * @param socket_error set to true if socket error was detected */ void MHD_connection_handle_read (struct MHD_Connection *connection, bool socket_error) { ssize_t bytes_read; if ( (MHD_CONNECTION_CLOSED == connection->state) || (connection->suspended) ) return; #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if (MHD_TLS_CONN_CONNECTED > connection->tls_state) { if (! MHD_run_tls_handshake_ (connection)) return; } } #endif /* HTTPS_SUPPORT */ mhd_assert (NULL != connection->read_buffer); if (connection->read_buffer_size == connection->read_buffer_offset) return; /* No space for receiving data. */ bytes_read = connection->recv_cls (connection, &connection->read_buffer [connection->read_buffer_offset], connection->read_buffer_size - connection->read_buffer_offset); if ((bytes_read < 0) || socket_error) { if ((MHD_ERR_AGAIN_ == bytes_read) && ! socket_error) return; /* No new data to process. */ if ((bytes_read > 0) && connection->sk_nonblck) { /* Try to detect the socket error */ int dummy; bytes_read = connection->recv_cls (connection, &dummy, sizeof (dummy)); } if (MHD_ERR_CONNRESET_ == bytes_read) { if ( (MHD_CONNECTION_INIT < connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) ) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Socket has been disconnected when reading request.\n")); #endif connection->discard_request = true; } MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_READ_ERROR); return; } #ifdef HAVE_MESSAGES if (MHD_CONNECTION_INIT != connection->state) MHD_DLOG (connection->daemon, _ ("Connection socket is closed when reading " \ "request due to the error: %s\n"), (bytes_read < 0) ? str_conn_error_ (bytes_read) : "detected connection closure"); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } if (0 == bytes_read) { /* Remote side closed connection. */ connection->read_closed = true; if ( (MHD_CONNECTION_INIT < connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) ) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Connection was closed by remote side with incomplete " "request.\n")); #endif connection->discard_request = true; MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_CLIENT_ABORT); } else if (MHD_CONNECTION_INIT == connection->state) /* This termination code cannot be reported to the application * because application has not been informed yet about this request */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_COMPLETED_OK); else MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); return; } connection->read_buffer_offset += (size_t) bytes_read; MHD_update_last_activity_ (connection); #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif /* TODO: check whether the next 'switch()' really needed */ switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: case MHD_CONNECTION_REQ_HEADERS_RECEIVING: case MHD_CONNECTION_BODY_RECEIVING: case MHD_CONNECTION_FOOTERS_RECEIVING: case MHD_CONNECTION_FULL_REQ_RECEIVED: /* nothing to do but default action */ if (connection->read_closed) { /* TODO: check whether this really needed */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_READ_ERROR); } return; case MHD_CONNECTION_CLOSED: return; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); return; #endif /* UPGRADE_SUPPORT */ case MHD_CONNECTION_START_REPLY: /* shrink read buffer to how much is actually used */ /* TODO: remove shrink as it handled in special function */ if ((0 != connection->read_buffer_size) && (connection->read_buffer_size != connection->read_buffer_offset)) { mhd_assert (NULL != connection->read_buffer); connection->read_buffer = MHD_pool_reallocate (connection->pool, connection->read_buffer, connection->read_buffer_size, connection->read_buffer_offset); connection->read_buffer_size = connection->read_buffer_offset; } break; case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVED: /* Milestone state, no data should be read */ mhd_assert (0); /* Should not be possible */ break; case MHD_CONNECTION_CONTINUE_SENDING: case MHD_CONNECTION_HEADERS_SENDING: case MHD_CONNECTION_HEADERS_SENT: case MHD_CONNECTION_NORMAL_BODY_UNREADY: case MHD_CONNECTION_NORMAL_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_SENT: case MHD_CONNECTION_FOOTERS_SENDING: case MHD_CONNECTION_FULL_REPLY_SENT: default: mhd_assert (0); /* Should not be possible */ break; } return; } /** * This function was created to handle writes to sockets when it has * been determined that the socket can be written to. All * implementations (multithreaded, external select, internal select) * call this function * * @param connection connection to handle */ void MHD_connection_handle_write (struct MHD_Connection *connection) { struct MHD_Response *response; ssize_t ret; if (connection->suspended) return; #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if (MHD_TLS_CONN_CONNECTED > connection->tls_state) { if (! MHD_run_tls_handshake_ (connection)) return; } } #endif /* HTTPS_SUPPORT */ #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_REQ_HEADERS_RECEIVING: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: mhd_assert (0); return; case MHD_CONNECTION_CONTINUE_SENDING: ret = MHD_send_data_ (connection, &HTTP_100_CONTINUE [connection->continue_message_write_offset], MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE) - connection->continue_message_write_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send data in request for %s.\n"), connection->rq.url); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } #if _MHD_DEBUG_SEND_DATA fprintf (stderr, _ ("Sent 100 continue response: `%.*s'\n"), (int) ret, &HTTP_100_CONTINUE[connection->continue_message_write_offset]); #endif connection->continue_message_write_offset += (size_t) ret; MHD_update_last_activity_ (connection); return; case MHD_CONNECTION_BODY_RECEIVING: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVING: case MHD_CONNECTION_FOOTERS_RECEIVED: case MHD_CONNECTION_FULL_REQ_RECEIVED: mhd_assert (0); return; case MHD_CONNECTION_START_REPLY: mhd_assert (0); return; case MHD_CONNECTION_HEADERS_SENDING: { struct MHD_Response *const resp = connection->rp.response; const size_t wb_ready = connection->write_buffer_append_offset - connection->write_buffer_send_offset; mhd_assert (connection->write_buffer_append_offset >= \ connection->write_buffer_send_offset); mhd_assert (NULL != resp); mhd_assert ( (0 == resp->data_size) || \ (0 == resp->data_start) || \ (NULL != resp->crc) ); mhd_assert ( (0 == connection->rp.rsp_write_position) || \ (resp->total_size == connection->rp.rsp_write_position) ); mhd_assert ((MHD_CONN_MUST_UPGRADE != connection->keepalive) || \ (! connection->rp.props.send_reply_body)); if ( (connection->rp.props.send_reply_body) && (NULL == resp->crc) && (NULL == resp->data_iov) && /* TODO: remove the next check as 'send_reply_body' is used */ (0 == connection->rp.rsp_write_position) && (! connection->rp.props.chunked) ) { mhd_assert (resp->total_size >= resp->data_size); mhd_assert (0 == resp->data_start); /* Send response headers alongside the response body, if the body * data is available. */ ret = MHD_send_hdr_and_body_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], wb_ready, false, resp->data, resp->data_size, (resp->total_size == resp->data_size)); } else { /* This is response for HEAD request or reply body is not allowed * for any other reason or reply body is dynamically generated. */ /* Do not send the body data even if it's available. */ ret = MHD_send_hdr_and_body_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], wb_ready, false, NULL, 0, ((0 == resp->total_size) || (! connection->rp.props.send_reply_body) )); } if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the response headers for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } /* 'ret' is not negative, it's safe to cast it to 'size_t'. */ if (((size_t) ret) > wb_ready) { /* The complete header and some response data have been sent, * update both offsets. */ mhd_assert (0 == connection->rp.rsp_write_position); mhd_assert (! connection->rp.props.chunked); mhd_assert (connection->rp.props.send_reply_body); connection->write_buffer_send_offset += wb_ready; connection->rp.rsp_write_position = ((size_t) ret) - wb_ready; } else connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_HEADERS_SENDING != connection->state) return; check_write_done (connection, MHD_CONNECTION_HEADERS_SENT); return; } case MHD_CONNECTION_HEADERS_SENT: return; case MHD_CONNECTION_NORMAL_BODY_READY: response = connection->rp.response; if (connection->rp.rsp_write_position < connection->rp.response->total_size) { uint64_t data_write_offset; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != response->crc) MHD_mutex_lock_chk_ (&response->mutex); #endif if (MHD_NO == try_ready_normal_body (connection)) { /* mutex was already unlocked by try_ready_normal_body */ return; } #if defined(_MHD_HAVE_SENDFILE) if (MHD_resp_sender_sendfile == connection->rp.resp_sender) { mhd_assert (NULL == response->data_iov); ret = MHD_send_sendfile_ (connection); } else /* combined with the next 'if' */ #endif /* _MHD_HAVE_SENDFILE */ if (NULL != response->data_iov) { ret = MHD_send_iovec_ (connection, &connection->rp.resp_iov, true); } else { data_write_offset = connection->rp.rsp_write_position - response->data_start; if (data_write_offset > (uint64_t) SIZE_MAX) MHD_PANIC (_ ("Data offset exceeds limit.\n")); ret = MHD_send_data_ (connection, &response->data [(size_t) data_write_offset], response->data_size - (size_t) data_write_offset, true); #if _MHD_DEBUG_SEND_DATA if (ret > 0) fprintf (stderr, _ ("Sent %d-byte DATA response: `%.*s'\n"), (int) ret, (int) ret, &rp.response->data[connection->rp.rsp_write_position - rp.response->data_start]); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != response->crc) MHD_mutex_unlock_chk_ (&response->mutex); #endif if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the response body for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->rp.rsp_write_position += (size_t) ret; MHD_update_last_activity_ (connection); } if (connection->rp.rsp_write_position == connection->rp.response->total_size) connection->state = MHD_CONNECTION_FULL_REPLY_SENT; return; case MHD_CONNECTION_NORMAL_BODY_UNREADY: mhd_assert (0); return; case MHD_CONNECTION_CHUNKED_BODY_READY: ret = MHD_send_data_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], connection->write_buffer_append_offset - connection->write_buffer_send_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the chunked response body for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_CHUNKED_BODY_READY != connection->state) return; check_write_done (connection, (connection->rp.response->total_size == connection->rp.rsp_write_position) ? MHD_CONNECTION_CHUNKED_BODY_SENT : MHD_CONNECTION_CHUNKED_BODY_UNREADY); return; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (0); return; case MHD_CONNECTION_FOOTERS_SENDING: ret = MHD_send_data_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], connection->write_buffer_append_offset - connection->write_buffer_send_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the footers for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_FOOTERS_SENDING != connection->state) return; check_write_done (connection, MHD_CONNECTION_FULL_REPLY_SENT); return; case MHD_CONNECTION_FULL_REPLY_SENT: mhd_assert (0); return; case MHD_CONNECTION_CLOSED: return; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); return; #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); CONNECTION_CLOSE_ERROR (connection, _ ("Internal error.\n")); break; } return; } /** * Check whether connection has timed out. * @param c the connection to check * @return true if connection has timeout and needs to be closed, * false otherwise. */ static bool connection_check_timedout (struct MHD_Connection *c) { const uint64_t timeout = c->connection_timeout_ms; uint64_t now; uint64_t since_actv; if (c->suspended) return false; if (0 == timeout) return false; now = MHD_monotonic_msec_counter (); since_actv = now - c->last_activity; /* Keep the next lines in sync with #connection_get_wait() to avoid * undesired side-effects like busy-waiting. */ if (timeout < since_actv) { if (UINT64_MAX / 2 < since_actv) { const uint64_t jump_back = c->last_activity - now; /* Very unlikely that it is more than quarter-million years pause. * More likely that system clock jumps back. */ if (5000 >= jump_back) { #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Detected system clock %u milliseconds jump back.\n"), (unsigned int) jump_back); #endif return false; } #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Detected too large system clock %" PRIu64 " milliseconds " "jump back.\n"), jump_back); #endif } return true; } return false; } /** * Clean up the state of the given connection and move it into the * clean up queue for final disposal. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection handle for the connection to clean up */ static void cleanup_connection (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (connection->in_cleanup) return; /* Prevent double cleanup. */ connection->in_cleanup = true; if (NULL != connection->rp.response) { MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (connection->suspended) { DLL_remove (daemon->suspended_connections_head, daemon->suspended_connections_tail, connection); connection->suspended = false; } else { if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); } DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, connection); connection->resuming = false; connection->in_idle = false; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* if we were at the connection limit before and are in thread-per-connection mode, signal the main thread to resume accepting connections */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "c")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal end of connection via inter-thread " \ "communication channel.\n")); #endif } } } /** * Set initial internal states for the connection to start reading and * processing incoming data. * @param c the connection to process */ void MHD_connection_set_initial_state_ (struct MHD_Connection *c) { size_t read_buf_size; #ifdef HTTPS_SUPPORT mhd_assert ( (0 == (c->daemon->options & MHD_USE_TLS)) || \ (MHD_TLS_CONN_INIT == c->tls_state) ); mhd_assert ( (0 != (c->daemon->options & MHD_USE_TLS)) || \ (MHD_TLS_CONN_NO_TLS == c->tls_state) ); #endif /* HTTPS_SUPPORT */ mhd_assert (MHD_CONNECTION_INIT == c->state); c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN; c->event_loop_info = MHD_EVENT_LOOP_INFO_READ; memset (&c->rq, 0, sizeof(c->rq)); memset (&c->rp, 0, sizeof(c->rp)); c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; c->continue_message_write_offset = 0; c->read_buffer_offset = 0; read_buf_size = c->daemon->pool_size / 2; c->read_buffer = MHD_pool_allocate (c->pool, read_buf_size, false); c->read_buffer_size = read_buf_size; } /** * Reset connection after request-reply cycle. * @param connection the connection to process * @param reuse the flag to choose whether to close connection or * prepare connection for the next request processing */ static void connection_reset (struct MHD_Connection *connection, bool reuse) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Daemon *const d = connection->daemon; if (! reuse) { /* Next function will destroy response, notify client, * destroy memory pool, and set connection state to "CLOSED" */ MHD_connection_close_ (c, c->stop_with_error ? MHD_REQUEST_TERMINATED_WITH_ERROR : MHD_REQUEST_TERMINATED_COMPLETED_OK); c->read_buffer = NULL; c->read_buffer_size = 0; c->read_buffer_offset = 0; c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; } else { /* Reset connection to process the next request */ size_t new_read_buf_size; mhd_assert (! c->stop_with_error); mhd_assert (! c->discard_request); if ( (NULL != d->notify_completed) && (c->rq.client_aware) ) d->notify_completed (d->notify_completed_cls, c, &c->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); c->rq.client_aware = false; if (NULL != c->rp.response) MHD_destroy_response (c->rp.response); c->rp.response = NULL; c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN; c->state = MHD_CONNECTION_INIT; c->event_loop_info = (0 == c->read_buffer_offset) ? MHD_EVENT_LOOP_INFO_READ : MHD_EVENT_LOOP_INFO_PROCESS; memset (&c->rq, 0, sizeof(c->rq)); /* iov (if any) will be deallocated by MHD_pool_reset */ memset (&c->rp, 0, sizeof(c->rp)); c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; c->continue_message_write_offset = 0; /* Reset the read buffer to the starting size, preserving the bytes we have already read. */ new_read_buf_size = c->daemon->pool_size / 2; if (c->read_buffer_offset > new_read_buf_size) new_read_buf_size = c->read_buffer_offset; c->read_buffer = MHD_pool_reset (c->pool, c->read_buffer, c->read_buffer_offset, new_read_buf_size); c->read_buffer_size = new_read_buf_size; } c->rq.client_context = NULL; } /** * This function was created to handle per-connection processing that * has to happen even if the socket cannot be read or written to. * All implementations (multithreaded, external select, internal select) * call this function. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection connection to handle * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_handle_idle (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; enum MHD_Result ret; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ /* 'daemon' is not used if epoll is not available and asserts are disabled */ (void) daemon; /* Mute compiler warning */ connection->in_idle = true; while (! connection->suspended) { #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if ((MHD_TLS_CONN_INIT <= connection->tls_state) && (MHD_TLS_CONN_CONNECTED > connection->tls_state)) break; } #endif /* HTTPS_SUPPORT */ #if DEBUG_STATES MHD_DLOG (daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: if (get_request_line (connection)) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < connection->state); mhd_assert ((MHD_IS_HTTP_VER_SUPPORTED (connection->rq.http_ver)) \ || (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING >= connection->state); break; case MHD_CONNECTION_REQ_LINE_RECEIVED: switch_to_rq_headers_processing (connection); mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED != connection->state); continue; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: if (get_req_headers (connection, false)) { mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING < connection->state); mhd_assert ((MHD_CONNECTION_HEADERS_RECEIVED == connection->state) || \ (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING == connection->state); break; case MHD_CONNECTION_HEADERS_RECEIVED: parse_connection_headers (connection); if (MHD_CONNECTION_HEADERS_RECEIVED != connection->state) continue; connection->state = MHD_CONNECTION_HEADERS_PROCESSED; if (connection->suspended) break; continue; case MHD_CONNECTION_HEADERS_PROCESSED: call_connection_handler (connection); /* first call */ if (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) continue; if (connection->suspended) continue; if ( (NULL == connection->rp.response) && (need_100_continue (connection)) && /* If the client is already sending the payload (body) there is no need to send "100 Continue" */ (0 == connection->read_buffer_offset) ) { connection->state = MHD_CONNECTION_CONTINUE_SENDING; break; } if ( (NULL != connection->rp.response) && (0 != connection->rq.remaining_upload_size) ) { /* we refused (no upload allowed!) */ connection->rq.remaining_upload_size = 0; /* force close, in case client still tries to upload... */ connection->discard_request = true; } connection->state = (0 == connection->rq.remaining_upload_size) ? MHD_CONNECTION_FULL_REQ_RECEIVED : MHD_CONNECTION_BODY_RECEIVING; if (connection->suspended) break; continue; case MHD_CONNECTION_CONTINUE_SENDING: if (connection->continue_message_write_offset == MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)) { connection->state = MHD_CONNECTION_BODY_RECEIVING; continue; } break; case MHD_CONNECTION_BODY_RECEIVING: mhd_assert (0 != connection->rq.remaining_upload_size); mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 != connection->read_buffer_offset) { process_request_body (connection); /* loop call */ if (MHD_CONNECTION_BODY_RECEIVING != connection->state) continue; } /* Modify here when queueing of the response during data processing will be supported */ mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 == connection->rq.remaining_upload_size) { connection->state = MHD_CONNECTION_BODY_RECEIVED; continue; } break; case MHD_CONNECTION_BODY_RECEIVED: mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 == connection->rq.remaining_upload_size) { if (connection->rq.have_chunked_upload) { /* Reset counter variables reused for footers */ connection->rq.num_cr_sp_replaced = 0; connection->rq.skipped_broken_lines = 0; reset_rq_header_processing_state (connection); connection->state = MHD_CONNECTION_FOOTERS_RECEIVING; } else connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; continue; } break; case MHD_CONNECTION_FOOTERS_RECEIVING: if (get_req_headers (connection, true)) { mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING < connection->state); mhd_assert ((MHD_CONNECTION_FOOTERS_RECEIVED == connection->state) || \ (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING == connection->state); break; case MHD_CONNECTION_FOOTERS_RECEIVED: /* The header, the body, and the footers of the request has been received, * switch to the final processing of the request. */ connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; continue; case MHD_CONNECTION_FULL_REQ_RECEIVED: call_connection_handler (connection); /* "final" call */ if (connection->state != MHD_CONNECTION_FULL_REQ_RECEIVED) continue; if (NULL == connection->rp.response) break; /* try again next time */ /* Response is ready, start reply */ connection->state = MHD_CONNECTION_START_REPLY; continue; case MHD_CONNECTION_START_REPLY: mhd_assert (NULL != connection->rp.response); connection_switch_from_recv_to_send (connection); if (MHD_NO == build_header_response (connection)) { /* oops - close! */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (failed to create " "response header).\n")); continue; } connection->state = MHD_CONNECTION_HEADERS_SENDING; break; case MHD_CONNECTION_HEADERS_SENDING: /* no default action */ break; case MHD_CONNECTION_HEADERS_SENT: #ifdef UPGRADE_SUPPORT if (NULL != connection->rp.response->upgrade_handler) { connection->state = MHD_CONNECTION_UPGRADE; /* This connection is "upgraded". Pass socket to application. */ if (MHD_NO == MHD_response_execute_upgrade_ (connection->rp.response, connection)) { /* upgrade failed, fail hard */ CONNECTION_CLOSE_ERROR (connection, NULL); continue; } /* Response is not required anymore for this connection. */ if (1) { struct MHD_Response *const resp = connection->rp.response; connection->rp.response = NULL; MHD_destroy_response (resp); } continue; } #endif /* UPGRADE_SUPPORT */ if (connection->rp.props.send_reply_body) { if (connection->rp.props.chunked) connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY; else connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY; } else connection->state = MHD_CONNECTION_FULL_REPLY_SENT; continue; case MHD_CONNECTION_NORMAL_BODY_READY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (! connection->rp.props.chunked); /* nothing to do here */ break; case MHD_CONNECTION_NORMAL_BODY_UNREADY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (! connection->rp.props.chunked); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_lock_chk_ (&connection->rp.response->mutex); #endif if (0 == connection->rp.response->total_size) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif if (connection->rp.props.chunked) connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT; else connection->state = MHD_CONNECTION_FULL_REPLY_SENT; continue; } if (MHD_NO != try_ready_normal_body (connection)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = MHD_CONNECTION_NORMAL_BODY_READY; /* Buffering for flushable socket was already enabled*/ break; } /* mutex was already unlocked by "try_ready_normal_body */ /* not ready, no socket action */ break; case MHD_CONNECTION_CHUNKED_BODY_READY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); /* nothing to do here */ break; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_lock_chk_ (&connection->rp.response->mutex); #endif if ( (0 == connection->rp.response->total_size) || (connection->rp.rsp_write_position == connection->rp.response->total_size) ) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT; continue; } if (1) { /* pseudo-branch for local variables scope */ bool finished; if (MHD_NO != try_ready_chunked_body (connection, &finished)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = finished ? MHD_CONNECTION_CHUNKED_BODY_SENT : MHD_CONNECTION_CHUNKED_BODY_READY; continue; } /* mutex was already unlocked by try_ready_chunked_body */ } break; case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); mhd_assert (connection->write_buffer_send_offset <= \ connection->write_buffer_append_offset); if (MHD_NO == build_connection_chunked_response_footer (connection)) { /* oops - close! */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (failed to create " \ "response footer).")); continue; } mhd_assert (connection->write_buffer_send_offset < \ connection->write_buffer_append_offset); connection->state = MHD_CONNECTION_FOOTERS_SENDING; continue; case MHD_CONNECTION_FOOTERS_SENDING: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); /* no default action */ break; case MHD_CONNECTION_FULL_REPLY_SENT: if (MHD_HTTP_PROCESSING == connection->rp.responseCode) { /* After this type of response, we allow sending another! */ connection->state = MHD_CONNECTION_HEADERS_PROCESSED; MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; /* FIXME: maybe partially reset memory pool? */ continue; } /* Reset connection after complete reply */ connection_reset (connection, MHD_CONN_USE_KEEPALIVE == connection->keepalive && ! connection->read_closed && ! connection->discard_request); continue; case MHD_CONNECTION_CLOSED: cleanup_connection (connection); connection->in_idle = false; return MHD_NO; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: connection->in_idle = false; return MHD_YES; /* keep open */ #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); break; } break; } if (connection_check_timedout (connection)) { MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_TIMEOUT_REACHED); connection->in_idle = false; return MHD_YES; } MHD_connection_update_event_loop_info (connection); ret = MHD_YES; #ifdef EPOLL_SUPPORT if ( (! connection->suspended) && MHD_D_IS_USING_EPOLL_ (daemon) ) { ret = MHD_connection_epoll_update_ (connection); } #endif /* EPOLL_SUPPORT */ connection->in_idle = false; return ret; } #ifdef EPOLL_SUPPORT /** * Perform epoll() processing, possibly moving the connection back into * the epoll() set if needed. * * @param connection connection to process * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_epoll_update_ (struct MHD_Connection *connection) { struct MHD_Daemon *const daemon = connection->daemon; mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon)); if ((0 != (MHD_EVENT_LOOP_INFO_PROCESS & connection->event_loop_info)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))) { /* Make sure that connection waiting for processing will be processed */ EDLL_insert (daemon->eready_head, daemon->eready_tail, connection); connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } if ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) && ( ( (MHD_EVENT_LOOP_INFO_WRITE == connection->event_loop_info) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY))) || ( (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ) ) { /* add to epoll set */ struct epoll_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = connection; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { #ifdef HAVE_MESSAGES if (0 != (daemon->options & MHD_USE_ERROR_LOG)) MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif connection->state = MHD_CONNECTION_CLOSED; cleanup_connection (connection); return MHD_NO; } connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET; } return MHD_YES; } #endif /** * Set callbacks for this connection to those for HTTP. * * @param connection connection to initialize */ void MHD_set_http_callbacks_ (struct MHD_Connection *connection) { connection->recv_cls = &recv_param_adapter; } /** * Obtain information about the given connection. * The returned pointer is invalidated with the next call of this function or * when the connection is closed. * * @param connection what connection to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType info_type, ...) { switch (info_type) { #ifdef HTTPS_SUPPORT case MHD_CONNECTION_INFO_CIPHER_ALGO: if (NULL == connection->tls_session) return NULL; if (1) { /* Workaround to mute compiler warning */ gnutls_cipher_algorithm_t res; res = gnutls_cipher_get (connection->tls_session); connection->connection_info_dummy.cipher_algorithm = (int) res; } return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_PROTOCOL: if (NULL == connection->tls_session) return NULL; if (1) { /* Workaround to mute compiler warning */ gnutls_protocol_t res; res = gnutls_protocol_get_version (connection->tls_session); connection->connection_info_dummy.protocol = (int) res; } return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_GNUTLS_SESSION: if (NULL == connection->tls_session) return NULL; connection->connection_info_dummy.tls_session = connection->tls_session; return &connection->connection_info_dummy; #else /* ! HTTPS_SUPPORT */ case MHD_CONNECTION_INFO_CIPHER_ALGO: case MHD_CONNECTION_INFO_PROTOCOL: case MHD_CONNECTION_INFO_GNUTLS_SESSION: #endif /* ! HTTPS_SUPPORT */ case MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT: return NULL; /* Not implemented */ case MHD_CONNECTION_INFO_CLIENT_ADDRESS: if (0 < connection->addr_len) { mhd_assert (sizeof (connection->addr) == \ sizeof (connection->connection_info_dummy.client_addr)); memcpy (&connection->connection_info_dummy.client_addr, &connection->addr, sizeof(connection->addr)); return &connection->connection_info_dummy; } return NULL; case MHD_CONNECTION_INFO_DAEMON: connection->connection_info_dummy.daemon = MHD_get_master (connection->daemon); return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_FD: connection->connection_info_dummy.connect_fd = connection->socket_fd; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_SOCKET_CONTEXT: connection->connection_info_dummy.socket_context = connection->socket_context; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_SUSPENDED: connection->connection_info_dummy.suspended = connection->suspended ? MHD_YES : MHD_NO; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_TIMEOUT: #if SIZEOF_UNSIGNED_INT <= (SIZEOF_UINT64_T - 2) if (UINT_MAX < connection->connection_timeout_ms / 1000) connection->connection_info_dummy.connection_timeout = UINT_MAX; else #endif /* SIZEOF_UNSIGNED_INT <=(SIZEOF_UINT64_T - 2) */ connection->connection_info_dummy.connection_timeout = (unsigned int) (connection->connection_timeout_ms / 1000); return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE: if ( (MHD_CONNECTION_HEADERS_RECEIVED > connection->state) || (MHD_CONNECTION_CLOSED == connection->state) ) return NULL; /* invalid, too early! */ connection->connection_info_dummy.header_size = connection->rq.header_size; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_HTTP_STATUS: if (NULL == connection->rp.response) return NULL; connection->connection_info_dummy.http_status = connection->rp.responseCode; return &connection->connection_info_dummy; default: return NULL; } } /** * Set a custom option for the given connection, overriding defaults. * * @param connection connection to modify * @param option option to set * @param ... arguments to the option, depending on the option type * @return #MHD_YES on success, #MHD_NO if setting the option failed * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_set_connection_option (struct MHD_Connection *connection, enum MHD_CONNECTION_OPTION option, ...) { va_list ap; struct MHD_Daemon *daemon; unsigned int ui_val; daemon = connection->daemon; switch (option) { case MHD_CONNECTION_OPTION_TIMEOUT: if (0 == connection->connection_timeout_ms) connection->last_activity = MHD_monotonic_msec_counter (); va_start (ap, option); ui_val = va_arg (ap, unsigned int); va_end (ap); #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT if ((UINT64_MAX / 4000 - 1) < ui_val) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The specified connection timeout (%u) is too " \ "large. Maximum allowed value (%" PRIu64 ") will be used " \ "instead.\n"), ui_val, (UINT64_MAX / 4000 - 1)); #endif ui_val = UINT64_MAX / 4000 - 1; } #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #if defined(MHD_USE_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (! connection->suspended) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); connection->connection_timeout_ms = ((uint64_t) ui_val) * 1000; if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_insert (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } return MHD_YES; default: return MHD_NO; } } /** * Queue a response to be transmitted to the client (as soon as * possible but after #MHD_AccessHandlerCallback returns). * * For any active connection this function must be called * only by #MHD_AccessHandlerCallback callback. * * For suspended connection this function can be called at any moment (this * behaviour is deprecated and will be removed!). Response will be sent * as soon as connection is resumed. * * For single thread environment, when MHD is used in "external polling" mode * (without MHD_USE_SELECT_INTERNALLY) this function can be called any * time (this behaviour is deprecated and will be removed!). * * If HTTP specifications require use no body in reply, like @a status_code with * value 1xx, the response body is automatically not sent even if it is present * in the response. No "Content-Length" or "Transfer-Encoding" headers are * generated and added. * * When the response is used to respond HEAD request or used with @a status_code * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length" * header is added automatically based the size of the body in the response. * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead * of "Content-Length" header. For example, if response with zero-size body is * used for HEAD request, then "Content-Length: 0" is added automatically to * reply headers. * @sa #MHD_RF_HEAD_ONLY_RESPONSE * * In situations, where reply body is required, like answer for the GET request * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1) * are added automatically. * In practice, the same response object can be used to respond to both HEAD and * GET requests. * * @param connection the connection identifying the client * @param status_code HTTP status code (i.e. #MHD_HTTP_OK) * @param response response to transmit, the NULL is tolerated * @return #MHD_NO on error (reply already sent, response is NULL), * #MHD_YES on success or if message has been queued * @ingroup response * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response) { struct MHD_Daemon *daemon; bool reply_icy; if ((NULL == connection) || (NULL == response)) return MHD_NO; daemon = connection->daemon; if ((! connection->in_access_handler) && (! connection->suspended) && MHD_D_IS_USING_THREADS_ (daemon)) return MHD_NO; reply_icy = (0 != (status_code & MHD_ICY_FLAG)); status_code &= ~MHD_ICY_FLAG; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if ( (! connection->suspended) && MHD_D_IS_USING_THREADS_ (daemon) && (! MHD_thread_handle_ID_is_current_thread_ (connection->tid)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Attempted to queue response on wrong thread!\n")); #endif return MHD_NO; } #endif if (NULL != connection->rp.response) return MHD_NO; /* The response was already set */ if ( (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED != connection->state) ) return MHD_NO; /* Wrong connection state */ if (daemon->shutdown) return MHD_NO; #ifdef UPGRADE_SUPPORT if (NULL != response->upgrade_handler) { struct MHD_HTTP_Res_Header *conn_header; if (0 == (daemon->options & MHD_ALLOW_UPGRADE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Attempted 'upgrade' connection on daemon without" \ " MHD_ALLOW_UPGRADE option!\n")); #endif return MHD_NO; } if (MHD_HTTP_SWITCHING_PROTOCOLS != status_code) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid status code for" \ " 'upgrade' response!\n")); #endif return MHD_NO; } if (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid response" \ " without \"Connection\" header!\n")); #endif return MHD_NO; } conn_header = response->first_header; mhd_assert (NULL != conn_header); mhd_assert (MHD_str_equal_caseless_ (conn_header->header, MHD_HTTP_HEADER_CONNECTION)); if (! MHD_str_has_s_token_caseless_ (conn_header->value, "upgrade")) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid response" \ " without \"upgrade\" token in" \ " \"Connection\" header!\n")); #endif return MHD_NO; } if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Connection \"Upgrade\" can be used only " \ "with HTTP/1.1 connections!\n")); #endif return MHD_NO; } } #endif /* UPGRADE_SUPPORT */ if (MHD_HTTP_SWITCHING_PROTOCOLS == status_code) { #ifdef UPGRADE_SUPPORT if (NULL == response->upgrade_handler) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used status code 101 \"Switching Protocols\" " \ "with non-'upgrade' response!\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #else /* ! UPGRADE_SUPPORT */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used status code 101 \"Switching Protocols\", " \ "but this MHD was built without \"Upgrade\" support!\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! UPGRADE_SUPPORT */ } if ( (100 > status_code) || (999 < status_code) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Refused wrong status code (%u). " \ "HTTP requires three digits status code!\n"), status_code); #endif return MHD_NO; } if (200 > status_code) { if (MHD_HTTP_VER_1_0 == connection->rq.http_ver) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Wrong status code (%u) refused. " \ "HTTP/1.0 clients do not support 1xx status codes!\n"), (status_code)); #endif return MHD_NO; } if (0 != (response->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT | MHD_RF_HTTP_1_0_SERVER))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Wrong status code (%u) refused. " \ "HTTP/1.0 reply mode does not support 1xx status codes!\n"), (status_code)); #endif return MHD_NO; } } if ( (MHD_HTTP_MTHD_CONNECT == connection->rq.http_mthd) && (2 == status_code / 100) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Successful (%u) response code cannot be used to answer " \ "\"CONNECT\" request!\n"), (status_code)); #endif return MHD_NO; } if ( (0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) && (RP_BODY_HEADERS_ONLY < is_reply_body_needed (connection, status_code)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("HEAD-only response cannot be used when the request requires " "reply body to be sent!\n")); #endif return MHD_NO; } #ifdef HAVE_MESSAGES if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) && (0 != (MHD_RAF_HAS_CONTENT_LENGTH & response->flags_auto)) ) { MHD_DLOG (daemon, _ ("The response has application-defined \"Content-Length\" " \ "header. The reply to the request will be not " \ "HTTP-compliant and may result in hung connection or " \ "other problems!\n")); } #endif MHD_increment_response_rc (response); connection->rp.response = response; connection->rp.responseCode = status_code; connection->rp.responseIcy = reply_icy; #if defined(_MHD_HAVE_SENDFILE) if ( (response->fd == -1) || (response->is_pipe) || (0 != (connection->daemon->options & MHD_USE_TLS)) #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || (! daemon->sigpipe_blocked && ! connection->sk_spipe_suppress) #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE */ ) connection->rp.resp_sender = MHD_resp_sender_std; else connection->rp.resp_sender = MHD_resp_sender_sendfile; #endif /* _MHD_HAVE_SENDFILE */ /* FIXME: if 'is_pipe' is set, TLS is off, and we have *splice*, we could use splice() to avoid two user-space copies... */ if ( (MHD_HTTP_MTHD_HEAD == connection->rq.http_mthd) || (MHD_HTTP_OK > status_code) || (MHD_HTTP_NO_CONTENT == status_code) || (MHD_HTTP_NOT_MODIFIED == status_code) ) { /* if this is a "HEAD" request, or a status code for which a body is not allowed, pretend that we have already sent the full message body. */ /* TODO: remove the next assignment, use 'rp_props.send_reply_body' in * checks */ connection->rp.rsp_write_position = response->total_size; } if (MHD_CONNECTION_HEADERS_PROCESSED == connection->state) { /* response was queued "early", refuse to read body / footers or further requests! */ connection->discard_request = true; connection->state = MHD_CONNECTION_START_REPLY; connection->rq.remaining_upload_size = 0; } if (! connection->in_idle) (void) MHD_connection_handle_idle (connection); MHD_update_last_activity_ (connection); return MHD_YES; } /* end of connection.c */ libmicrohttpd-1.0.2/src/microhttpd/sha256_ext.h0000644000175000017500000000567015035214301016306 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/sha256_ext.h * @brief Wrapper declarations for SHA-256 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_EXT_H #define MHD_SHA256_EXT_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Size of SHA-256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA256_DIGEST_SIZE (32) /* Actual declaration is in GnuTLS lib header */ struct hash_hd_st; /** * Indicates that struct Sha256CtxExt has 'ext_error' */ #define MHD_SHA256_HAS_EXT_ERROR 1 /** * SHA-256 calculation context */ struct Sha256CtxExt { struct hash_hd_st *handle; /**< Hash calculation handle */ int ext_error; /**< Non-zero if external error occurs during init or hashing */ }; /** * Indicates that MHD_SHA256_init_one_time() function is present. */ #define MHD_SHA256_HAS_INIT_ONE_TIME 1 /** * Initialise structure for SHA-256 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx); /** * SHA-256 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256CtxExt *ctx, const uint8_t *data, size_t length); /** * Indicates that MHD_SHA256_finish_reset() function is available */ #define MHD_SHA256_HAS_FINISH_RESET 1 /** * Finalise SHA-256 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx, uint8_t digest[SHA256_DIGEST_SIZE]); /** * Indicates that MHD_SHA256_deinit() function is present */ #define MHD_SHA256_HAS_DEINIT 1 /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_SHA256_deinit (struct Sha256CtxExt *ctx); #endif /* MHD_SHA256_EXT_H */ libmicrohttpd-1.0.2/src/microhttpd/response.h0000644000175000017500000001066614760713577016304 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file response.h * @brief Methods for managing response objects * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef RESPONSE_H #define RESPONSE_H /** * Increments the reference counter for the @a response. * * @param response object to modify */ void MHD_increment_response_rc (struct MHD_Response *response); /** * We are done sending the header of a given response * to the client. Now it is time to perform the upgrade * and hand over the connection to the application. * @remark To be called only from thread that process connection's * recv(), send() and response. Must be called right after sending * response headers. * * @param response the response that was created for an upgrade * @param connection the specific connection we are upgrading * @return #MHD_YES on success, #MHD_NO on failure (will cause * connection to be closed) */ enum MHD_Result MHD_response_execute_upgrade_ (struct MHD_Response *response, struct MHD_Connection *connection); /** * Get a particular header (or footer) element from the response. * * Function returns the first found element. * @param response response to query * @param kind the kind of element: header or footer * @param key the key which header to get * @param key_len the length of the @a key * @return NULL if header element does not exist * @ingroup response */ struct MHD_HTTP_Res_Header * MHD_get_response_element_n_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *key, size_t key_len); /** * Add a header or footer line to the response without checking. * * It is assumed that parameters are correct. * * @param response response to add a header to * @param kind header or footer * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (like out-of-memory), * true if succeed */ bool MHD_add_response_entry_no_check_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len); /** * Add preallocated strings a header or footer line to the response without * checking. * * Header/footer strings are not checked and assumed to be correct. * * The string must not be statically allocated! * The strings must be malloc()'ed and zero terminated. The strings will * be free()'ed when the response is destroyed. * * @param response response to add a header to * @param kind header or footer * @param header the header string to add, must be malloc()'ed and * zero-terminated * @param header_len the length of the @a header * @param content the value string to add, must be malloc()'ed and * zero-terminated * @param content_len the length of the @a content */ bool MHD_add_response_entry_no_alloc_ (struct MHD_Response *response, enum MHD_ValueKind kind, char *header, size_t header_len, char *content, size_t content_len); #endif libmicrohttpd-1.0.2/src/microhttpd/mhd_itc.c0000644000175000017500000000356015035214301016014 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc.c * @brief Implementation of inter-thread communication functions * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_itc.h" #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #include #include "internal.h" #if defined(_MHD_ITC_PIPE) #if ! defined(_WIN32) || defined(__CYGWIN__) #ifndef HAVE_PIPE2_FUNC /** * Change itc FD options to be non-blocking. * * @param itc the inter-thread communication primitive to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_itc_nonblocking_ (struct MHD_itc_ itc) { unsigned int i; for (i = 0; i<2; i++) { int flags; flags = fcntl (itc.fd[i], F_GETFL); if (-1 == flags) return 0; if ( ((flags | O_NONBLOCK) != flags) && (0 != fcntl (itc.fd[i], F_SETFL, flags | O_NONBLOCK)) ) return 0; } return ! 0; } #endif /* ! HAVE_PIPE2_FUNC */ #endif /* !_WIN32 || __CYGWIN__ */ #endif /* _MHD_ITC_EVENTFD || _MHD_ITC_PIPE */ libmicrohttpd-1.0.2/src/microhttpd/test_sha256.c0000644000175000017500000004775314760713574016514 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha256.h * @brief Unit tests for SHA-256 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_sha256_wrap.h" #include "test_helpers.h" #include #include #if defined(MHD_SHA256_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_SHA256_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */ static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA256_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}}, {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}}, {D_STR_W_LEN (""), {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0x2f, 0xad, 0x7a, 0xff, 0x7d, 0xfe, 0xcd, 0x78, 0xe4, 0xa6, 0xf3, 0x85, 0x97, 0x9d, 0xdc, 0x39, 0x55, 0x24, 0x35, 0x4a, 0x00, 0x6f, 0x42, 0x72, 0x41, 0xc1, 0x52, 0xa7, 0x01, 0x0b, 0x2c, 0x41}}, {D_STR_W_LEN ("Simple string."), {0x01, 0x73, 0x17, 0xc4, 0x0a, 0x9a, 0x0e, 0x81, 0xb3, 0xa4, 0xb1, 0x8e, 0xe9, 0xd6, 0xc2, 0xdf, 0xfa, 0x7d, 0x53, 0x4e, 0xa1, 0xda, 0xb2, 0x5a, 0x75, 0xbb, 0x2c, 0x30, 0x2f, 0x5f, 0x7a, 0xf4}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44, 0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0xce, 0x7d, 0xde, 0xb6, 0x1f, 0x7c, 0x1d, 0x83, 0x7c, 0x60, 0xd8, 0x36, 0x73, 0x82, 0xac, 0x92, 0xca, 0x37, 0xfd, 0x72, 0x8b, 0x0c, 0xd1, 0x6c, 0x55, 0xd5, 0x88, 0x98, 0x24, 0xfa, 0x16, 0xf2}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0x27, 0xd1, 0xe8, 0xbc, 0x6a, 0x79, 0x16, 0x83, 0x61, 0x73, 0xa9, 0xa8, 0x9b, 0xaf, 0xaf, 0xcf, 0x47, 0x4d, 0x09, 0xef, 0x6d, 0x50, 0x35, 0x12, 0x25, 0x72, 0xd8, 0x68, 0xdc, 0x1f, 0xd2, 0xf4}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0x73, 0x85, 0xc5, 0xb9, 0x8f, 0xaf, 0x7d, 0x5e, 0xad, 0xd8, 0x0b, 0x8e, 0x12, 0xdb, 0x28, 0x60, 0xc7, 0xc7, 0x55, 0x05, 0x2f, 0x7c, 0x6f, 0xfa, 0xd1, 0xe3, 0xe1, 0x7b, 0x04, 0xd4, 0xb0, 0x21}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA256_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44, 0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */ {0x6a, 0x6d, 0x69, 0x1a, 0xc9, 0xba, 0x70, 0x95, 0x50, 0x46, 0x75, 0x7c, 0xd6, 0x85, 0xb6, 0x25, 0x77, 0x73, 0xff, 0x3a, 0xd9, 0x3f, 0x43, 0xd4, 0xd4, 0x81, 0x2c, 0x5b, 0x10, 0x6f, 0x4b, 0x5b}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0x06, 0xe4, 0xb3, 0x9e, 0xf1, 0xfb, 0x6c, 0xcf, 0xd7, 0x3f, 0x50, 0x9e, 0xf4, 0x16, 0x17, 0xd4, 0x63, 0x7c, 0x39, 0x1e, 0xa8, 0x0f, 0xa9, 0x88, 0x03, 0x44, 0x98, 0x0e, 0x95, 0x81, 0xf0, 0x2a}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x4a, 0xd3, 0xc6, 0x87, 0x1f, 0xd1, 0xc5, 0xe2, 0x3e, 0x52, 0xdc, 0x22, 0xd1, 0x10, 0xd2, 0x05, 0x15, 0x23, 0xcd, 0x15, 0xac, 0x24, 0x88, 0x26, 0x02, 0x00, 0x70, 0x78, 0x9f, 0x17, 0xf8, 0xd9}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0xe6, 0x03, 0x0f, 0xc9, 0x0d, 0xca, 0x0c, 0x26, 0x41, 0xcf, 0x43, 0x27, 0xec, 0xd6, 0x28, 0x2a, 0x98, 0x24, 0x55, 0xd3, 0x5a, 0xed, 0x8b, 0x32, 0x19, 0x78, 0xeb, 0x83, 0x1d, 0x19, 0x92, 0x79}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72},/* 1..72 sequence */ {0x87, 0xa2, 0xfa, 0x2e, 0xec, 0x53, 0x05, 0x3c, 0xb1, 0xee, 0x07, 0xd7, 0x59, 0x70, 0xf6, 0x50, 0xcd, 0x9d, 0xc5, 0x8b, 0xdc, 0xb8, 0x65, 0x30, 0x4f, 0x70, 0x82, 0x9e, 0xbd, 0xe2, 0x7d, 0xac}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x40, 0xaf, 0xf2, 0xe9, 0xd2, 0xd8, 0x92, 0x2e, 0x47, 0xaf, 0xd4, 0x64, 0x8e, 0x69, 0x67, 0x49, 0x71, 0x58, 0x78, 0x5f, 0xbd, 0x1d, 0xa8, 0x70, 0xe7, 0x11, 0x02, 0x66, 0xbf, 0x94, 0x48, 0x80}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0x85, 0xf8, 0xa2, 0x83, 0xd6, 0x3c, 0x76, 0x8e, 0xea, 0x8f, 0x1c, 0x57, 0x2d, 0x85, 0xb6, 0xff, 0xd8, 0x33, 0x57, 0x62, 0x1d, 0x37, 0xae, 0x0e, 0xfc, 0x22, 0xd3, 0xd5, 0x8f, 0x53, 0x21, 0xb7}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x61, 0x86, 0x96, 0xab, 0x3e, 0xaa, 0x0e, 0x64, 0xb2, 0xf7, 0x2d, 0x75, 0x47, 0x5a, 0x14, 0x97, 0xa3, 0x3d, 0x59, 0xa4, 0x08, 0xd9, 0x9e, 0x73, 0xf2, 0x78, 0x00, 0x5b, 0x4b, 0x55, 0xca, 0x43}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x08, 0x7f, 0x86, 0xac, 0xe2, 0x2e, 0x28, 0x56, 0x74, 0x53, 0x4f, 0xc0, 0xfb, 0xb8, 0x79, 0x57, 0xc5, 0xc8, 0xd1, 0xb7, 0x47, 0xb7, 0xd9, 0xea, 0x97, 0xa8, 0x67, 0xe9, 0x26, 0x93, 0xee, 0xa3}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA256_DIGEST_SIZE], const uint8_t expected[SHA256_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA256_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA256_DIGEST_STRING_SIZE]; char expc_str[SHA256_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str); bin2hex (expected, SHA256_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA256_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s " "matches expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } /* Calculated SHA-256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Sha256CtxWr ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; MHD_SHA256_init_one_time (&ctx); buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA256_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA256_DIGEST_SIZE); MHD_SHA256_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA256_finish_reset (&ctx, unaligned_digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); MHD_SHA256_deinit (&ctx); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.2/src/microhttpd/md5_ext.h0000644000175000017500000000552215035214301015757 00000000000000/* This file is part of GNU libmicrohttpd Copyright (C) 2022-2024 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/md5_ext.h * @brief Wrapper declarations for MD5 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_EXT_H #define MHD_MD5_EXT_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (16) /* Actual declaration is in GnuTLS lib header */ struct hash_hd_st; /** * Indicates that struct Md5CtxExt has 'ext_error' */ #define MHD_MD5_HAS_EXT_ERROR 1 /** * MD5 calculation context */ struct Md5CtxExt { struct hash_hd_st *handle; /**< Hash calculation handle */ int ext_error; /**< Non-zero if external error occurs during init or hashing */ }; /** * Indicates that MHD_MD5_init_one_time() function is present. */ #define MHD_MD5_HAS_INIT_ONE_TIME 1 /** * Initialise structure for MD5 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_MD5_init_one_time (struct Md5CtxExt *ctx); /** * MD5 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5CtxExt *ctx, const uint8_t *data, size_t length); /** * Indicates that MHD_MD5_finish_reset() function is available */ #define MHD_MD5_HAS_FINISH_RESET 1 /** * Finalise MD5 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish_reset (struct Md5CtxExt *ctx, uint8_t digest[MD5_DIGEST_SIZE]); /** * Indicates that MHD_MD5_deinit() function is present */ #define MHD_MD5_HAS_DEINIT 1 /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_MD5_deinit (struct Md5CtxExt *ctx); #endif /* MHD_MD5_EXT_H */ libmicrohttpd-1.0.2/src/microhttpd/internal.h0000644000175000017500000022363514760713577016264 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/internal.h * @brief MHD internal shared structures * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef INTERNAL_H #define INTERNAL_H #include "mhd_options.h" #include "platform.h" #include "microhttpd.h" #include "mhd_assert.h" #ifdef HTTPS_SUPPORT #include #if GNUTLS_VERSION_MAJOR >= 3 #include #endif #endif /* HTTPS_SUPPORT */ #ifdef HAVE_STDBOOL_H #include #endif #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ /* Must be included before other internal headers! */ #include "mhd_panic.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_threads.h" #endif #include "mhd_locks.h" #include "mhd_sockets.h" #include "mhd_itc_types.h" #include "mhd_str_types.h" #if defined(BAUTH_SUPPORT) || defined(DAUTH_SUPPORT) #include "gen_auth.h" #endif /* BAUTH_SUPPORT || DAUTH_SUPPORT*/ /** * Macro to drop 'const' qualifier from pointer without compiler warning. * To be used *only* to deal with broken external APIs, which require non-const * pointer to unmodifiable data. * Must not be used to transform pointers for MHD needs. */ #define _MHD_DROP_CONST(ptr) ((void *) ((uintptr_t) ((const void *) (ptr)))) /** * @def _MHD_MACRO_NO * "Negative answer"/"false" for use in macros, meaningful for precompiler */ #define _MHD_MACRO_NO 0 /** * @def _MHD_MACRO_YES * "Positive answer"/"true" for use in macros, meaningful for precompiler */ #define _MHD_MACRO_YES 1 /** * Close FD and abort execution if error is detected. * @param fd the FD to close */ #define MHD_fd_close_chk_(fd) do { \ if ( (0 != close ((fd)) && (EBADF == errno)) ) { \ MHD_PANIC (_ ("Failed to close FD.\n")); \ } \ } while (0) /* #define EXTRA_CHECKS _MHD_MACRO_NO * Not used. Behaviour is controlled by _DEBUG/NDEBUG macros. */ #ifndef _MHD_DEBUG_CONNECT /** * Print extra messages when establishing * connections? (only adds non-error messages). */ #define _MHD_DEBUG_CONNECT _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_CONNECT */ #ifndef _MHD_DEBUG_SEND_DATA /** * Should all data send be printed to stderr? */ #define _MHD_DEBUG_SEND_DATA _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_SEND_DATA */ #ifndef _MHD_DEBUG_CLOSE /** * Add extra debug messages with reasons for closing connections * (non-error reasons). */ #define _MHD_DEBUG_CLOSE _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_CLOSE */ #define MHD_MAX(a,b) (((a)<(b)) ? (b) : (a)) #define MHD_MIN(a,b) (((a)<(b)) ? (a) : (b)) /** * Minimum reasonable size by which MHD tries to increment read/write buffers. * We usually begin with half the available pool space for the * IO-buffer, but if absolutely needed we additively grow by the * number of bytes given here (up to -- theoretically -- the full pool * space). * * Currently set to reasonable maximum MSS size. */ #define MHD_BUF_INC_SIZE 1500 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Tri-state on/off/unknown */ enum MHD_tristate { _MHD_UNKNOWN = -1, /**< State is not yet checked nor set */ _MHD_OFF = false, /**< State is "off" / "disabled" */ _MHD_NO = false, /**< State is "off" / "disabled" */ _MHD_ON = true, /**< State is "on" / "enabled" */ _MHD_YES = true /**< State is "on" / "enabled" */ } _MHD_FIXED_ENUM; /** * State of the socket with respect to epoll (bitmask). */ enum MHD_EpollState { /** * The socket is not involved with a defined state in epoll() right * now. */ MHD_EPOLL_STATE_UNREADY = 0, /** * epoll() told us that data was ready for reading, and we did * not consume all of it yet. */ MHD_EPOLL_STATE_READ_READY = 1, /** * epoll() told us that space was available for writing, and we did * not consume all of it yet. */ MHD_EPOLL_STATE_WRITE_READY = 2, /** * Is this connection currently in the 'eready' EDLL? */ MHD_EPOLL_STATE_IN_EREADY_EDLL = 4, /** * Is this connection currently in the epoll() set? */ MHD_EPOLL_STATE_IN_EPOLL_SET = 8, /** * Is this connection currently suspended? */ MHD_EPOLL_STATE_SUSPENDED = 16, /** * Is this connection in some error state? */ MHD_EPOLL_STATE_ERROR = 128 } _MHD_FIXED_FLAGS_ENUM; /** * What is this connection waiting for? */ enum MHD_ConnectionEventLoopInfo { /** * We are waiting to be able to read. */ MHD_EVENT_LOOP_INFO_READ = 1 << 0, /** * We are waiting to be able to write. */ MHD_EVENT_LOOP_INFO_WRITE = 1 << 1, /** * We are waiting for the application to provide data. */ MHD_EVENT_LOOP_INFO_PROCESS = 1 << 2, /** * Some data is ready to be processed, but more data could * be read. */ MHD_EVENT_LOOP_INFO_PROCESS_READ = MHD_EVENT_LOOP_INFO_READ | MHD_EVENT_LOOP_INFO_PROCESS, /** * We are finished and are awaiting cleanup. */ MHD_EVENT_LOOP_INFO_CLEANUP = 1 << 3 } _MHD_FIXED_ENUM; /** * Additional test value for enum MHD_FLAG to check only for MHD_ALLOW_SUSPEND_RESUME and * NOT for MHD_USE_ITC. */ #define MHD_TEST_ALLOW_SUSPEND_RESUME 8192 /** * Maximum length of a nonce in digest authentication. 64(SHA-256 Hex) + * 12(Timestamp Hex) + 1(NULL); hence 77 should suffice, but Opera * (already) takes more (see Mantis #1633), so we've increased the * value to support something longer... */ #define MAX_CLIENT_NONCE_LENGTH 129 /** * The maximum size of MHD-generated nonce when printed with hexadecimal chars. * * This is equal to "(32 bytes for SHA-256 (or SHA-512/256) nonce plus 6 bytes * for timestamp) multiplied by two hex chars per byte". * Please keep it in sync with digestauth.c */ #if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT) #define MAX_DIGEST_NONCE_LENGTH ((32 + 6) * 2) #else /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */ #define MAX_DIGEST_NONCE_LENGTH ((16 + 6) * 2) #endif /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */ /** * A structure representing the internal holder of the * nonce-nc map. */ struct MHD_NonceNc { /** * Nonce counter, a value that increases for each subsequent * request for the same nonce. Matches the largest last received * 'nc' value. * This 'nc' value was already used by the client. */ uint32_t nc; /** * Bitmask over the previous 64 nonce counter values (down to to nc-64). * Used to allow out-of-order 'nc'. * If bit in the bitmask is set to one, then this 'nc' value was already used * by the client. */ uint64_t nmask; /** * Nonce value */ char nonce[MAX_DIGEST_NONCE_LENGTH + 1]; }; #ifdef HAVE_MESSAGES /** * fprintf()-like helper function for logging debug * messages. */ void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...); #endif /** * Header or footer for HTTP response. */ struct MHD_HTTP_Res_Header { /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Res_Header *next; /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Res_Header *prev; /** * The name of the header (key), without the colon. */ char *header; /** * The length of the @a header, not including the final zero termination. */ size_t header_size; /** * The value of the header. */ char *value; /** * The length of the @a value, not including the final zero termination. */ size_t value_size; /** * Type of the value. */ enum MHD_ValueKind kind; }; /** * Header, footer, or cookie for HTTP request. */ struct MHD_HTTP_Req_Header { /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Req_Header *next; /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Req_Header *prev; /** * The name of the header (key), without the colon. */ const char *header; /** * The length of the @a header, not including the final zero termination. */ size_t header_size; /** * The value of the header. */ const char *value; /** * The length of the @a value, not including the final zero termination. */ size_t value_size; /** * Type of the value. */ enum MHD_ValueKind kind; }; /** * Automatically assigned flags */ enum MHD_ResponseAutoFlags { MHD_RAF_NO_FLAGS = 0, /**< No auto flags */ MHD_RAF_HAS_CONNECTION_HDR = 1 << 0, /**< Has "Connection" header */ MHD_RAF_HAS_CONNECTION_CLOSE = 1 << 1, /**< Has "Connection: close" */ MHD_RAF_HAS_TRANS_ENC_CHUNKED = 1 << 2, /**< Has "Transfer-Encoding: chunked" */ MHD_RAF_HAS_CONTENT_LENGTH = 1 << 3, /**< Has "Content-Length" header */ MHD_RAF_HAS_DATE_HDR = 1 << 4 /**< Has "Date" header */ } _MHD_FIXED_FLAGS_ENUM; #if defined(MHD_WINSOCK_SOCKETS) /** * Internally used I/O vector type for use with winsock. * Binary matches system "WSABUF". */ typedef struct _MHD_W32_iovec { unsigned long iov_len; char *iov_base; } MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE ULONG_MAX typedef unsigned long MHD_iov_size_; #elif defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) /** * Internally used I/O vector type for use when writev or sendmsg * is available. Matches system "struct iovec". */ typedef struct iovec MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX typedef size_t MHD_iov_size_; #else /** * Internally used I/O vector type for use when writev or sendmsg * is not available. */ typedef struct MHD_IoVec MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX typedef size_t MHD_iov_size_; #endif struct MHD_iovec_track_ { /** * The copy of array of iovec elements. * The copy of elements are updated during sending. * The number of elements is not changed during lifetime. */ MHD_iovec_ *iov; /** * The number of elements in @a iov. * This value is not changed during lifetime. */ size_t cnt; /** * The number of sent elements. * At the same time, it is the index of the next (or current) element * to send. */ size_t sent; }; /** * Representation of a response. */ struct MHD_Response { /** * Head of double-linked list of headers to send for the response. */ struct MHD_HTTP_Res_Header *first_header; /** * Tail of double-linked list of headers to send for the response. */ struct MHD_HTTP_Res_Header *last_header; /** * Buffer pointing to data that we are supposed * to send as a response. */ const char *data; /** * Closure to give to the content reader @e crc * and content reader free callback @e crfc. */ void *crc_cls; /** * How do we get more data? NULL if we are * given all of the data up front. */ MHD_ContentReaderCallback crc; /** * NULL if data must not be freed, otherwise * either user-specified callback or "&free". */ MHD_ContentReaderFreeCallback crfc; #ifdef UPGRADE_SUPPORT /** * Application function to call once we are done sending the headers * of the response; NULL unless this is a response created with * #MHD_create_response_for_upgrade(). */ MHD_UpgradeHandler upgrade_handler; /** * Closure for @e uh. */ void *upgrade_handler_cls; #endif /* UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Mutex to synchronize access to @e data, @e size and * @e reference_count. */ MHD_mutex_ mutex; #endif /** * The size of the response body. * Set to #MHD_SIZE_UNKNOWN if size is not known. */ uint64_t total_size; /** * At what offset in the stream is the * beginning of @e data located? */ uint64_t data_start; /** * Offset to start reading from when using @e fd. */ uint64_t fd_off; /** * Number of bytes ready in @e data (buffer may be larger * than what is filled with payload). */ size_t data_size; /** * Size of the writable data buffer @e data. */ size_t data_buffer_size; /** * Reference count for this response. Free once the counter hits * zero. */ unsigned int reference_count; /** * File-descriptor if this response is FD-backed. */ int fd; /** * Flags set for the MHD response. */ enum MHD_ResponseFlags flags; /** * Automatic flags set for the MHD response. */ enum MHD_ResponseAutoFlags flags_auto; /** * If the @e fd is a pipe (no sendfile()). */ bool is_pipe; /** * I/O vector used with MHD_create_response_from_iovec. */ MHD_iovec_ *data_iov; /** * Number of elements in data_iov. */ unsigned int data_iovcnt; }; /** * States in a state machine for a connection. * * The main transitions are any-state to #MHD_CONNECTION_CLOSED, any * state to state+1, #MHD_CONNECTION_FOOTERS_SENT to * #MHD_CONNECTION_INIT. #MHD_CONNECTION_CLOSED is the terminal state * and #MHD_CONNECTION_INIT the initial state. * * Note that transitions for *reading* happen only after the input has * been processed; transitions for *writing* happen after the * respective data has been put into the write buffer (the write does * not have to be completed yet). A transition to * #MHD_CONNECTION_CLOSED or #MHD_CONNECTION_INIT requires the write * to be complete. */ enum MHD_CONNECTION_STATE { /** * Connection just started (no headers received). * Waiting for the line with the request type, URL and version. */ MHD_CONNECTION_INIT = 0, /** * Part of the request line was received. * Wait for complete line. */ MHD_CONNECTION_REQ_LINE_RECEIVING = MHD_CONNECTION_INIT + 1, /** * We got the URL (and request type and version). Wait for a header line. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_REQ_LINE_RECEIVED = MHD_CONNECTION_REQ_LINE_RECEIVING + 1, /** * Receiving request headers. Wait for the rest of the headers. */ MHD_CONNECTION_REQ_HEADERS_RECEIVING = MHD_CONNECTION_REQ_LINE_RECEIVED + 1, /** * We got the request headers. Process them. */ MHD_CONNECTION_HEADERS_RECEIVED = MHD_CONNECTION_REQ_HEADERS_RECEIVING + 1, /** * We have processed the request headers. Call application callback. */ MHD_CONNECTION_HEADERS_PROCESSED = MHD_CONNECTION_HEADERS_RECEIVED + 1, /** * We have processed the headers and need to send 100 CONTINUE. */ MHD_CONNECTION_CONTINUE_SENDING = MHD_CONNECTION_HEADERS_PROCESSED + 1, /** * We have sent 100 CONTINUE (or do not need to). Read the message body. */ MHD_CONNECTION_BODY_RECEIVING = MHD_CONNECTION_CONTINUE_SENDING + 1, /** * We got the request body. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_BODY_RECEIVED = MHD_CONNECTION_BODY_RECEIVING + 1, /** * We are reading the request footers. */ MHD_CONNECTION_FOOTERS_RECEIVING = MHD_CONNECTION_BODY_RECEIVED + 1, /** * We received the entire footer. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_FOOTERS_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVING + 1, /** * We received the entire request. * Wait for a response to be queued. */ MHD_CONNECTION_FULL_REQ_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVED + 1, /** * Finished reading of the request and the response is ready. * Switch internal logic from receiving to sending, prepare connection * sending the reply and build the reply header. */ MHD_CONNECTION_START_REPLY = MHD_CONNECTION_FULL_REQ_RECEIVED + 1, /** * We have prepared the response headers in the write buffer. * Send the response headers. */ MHD_CONNECTION_HEADERS_SENDING = MHD_CONNECTION_START_REPLY + 1, /** * We have sent the response headers. Get ready to send the body. */ MHD_CONNECTION_HEADERS_SENT = MHD_CONNECTION_HEADERS_SENDING + 1, /** * We are waiting for the client to provide more * data of a non-chunked body. */ MHD_CONNECTION_NORMAL_BODY_UNREADY = MHD_CONNECTION_HEADERS_SENT + 1, /** * We are ready to send a part of a non-chunked body. Send it. */ MHD_CONNECTION_NORMAL_BODY_READY = MHD_CONNECTION_NORMAL_BODY_UNREADY + 1, /** * We are waiting for the client to provide a chunk of the body. */ MHD_CONNECTION_CHUNKED_BODY_UNREADY = MHD_CONNECTION_NORMAL_BODY_READY + 1, /** * We are ready to send a chunk. */ MHD_CONNECTION_CHUNKED_BODY_READY = MHD_CONNECTION_CHUNKED_BODY_UNREADY + 1, /** * We have sent the chunked response body. Prepare the footers. */ MHD_CONNECTION_CHUNKED_BODY_SENT = MHD_CONNECTION_CHUNKED_BODY_READY + 1, /** * We have prepared the response footer. Send it. */ MHD_CONNECTION_FOOTERS_SENDING = MHD_CONNECTION_CHUNKED_BODY_SENT + 1, /** * We have sent the entire reply. * Shutdown connection or restart processing to get a new request. */ MHD_CONNECTION_FULL_REPLY_SENT = MHD_CONNECTION_FOOTERS_SENDING + 1, /** * This connection is to be closed. */ MHD_CONNECTION_CLOSED = MHD_CONNECTION_FULL_REPLY_SENT + 1 #ifdef UPGRADE_SUPPORT , /** * Connection was "upgraded" and socket is now under the * control of the application. */ MHD_CONNECTION_UPGRADE = MHD_CONNECTION_CLOSED + 1 #endif /* UPGRADE_SUPPORT */ } _MHD_FIXED_ENUM; /** * States of TLS transport layer. */ enum MHD_TLS_CONN_STATE { MHD_TLS_CONN_NO_TLS = 0, /**< Not a TLS connection (plain socket). */ MHD_TLS_CONN_INIT, /**< TLS connection is not established yet. */ MHD_TLS_CONN_HANDSHAKING, /**< TLS is in handshake process. */ MHD_TLS_CONN_CONNECTED, /**< TLS is established. */ MHD_TLS_CONN_WR_CLOSING, /**< Closing WR side of TLS layer. */ MHD_TLS_CONN_WR_CLOSED, /**< WR side of TLS layer is closed. */ MHD_TLS_CONN_TLS_CLOSING, /**< TLS session is terminating. */ MHD_TLS_CONN_TLS_CLOSED, /**< TLS session is terminated. */ MHD_TLS_CONN_TLS_FAILED, /**< TLS session failed. */ MHD_TLS_CONN_INVALID_STATE/**< Sentinel. Not a valid value. */ } _MHD_FIXED_ENUM; /** * Should all state transitions be printed to stderr? */ #define DEBUG_STATES _MHD_MACRO_NO #ifdef HAVE_MESSAGES #if DEBUG_STATES const char * MHD_state_to_string (enum MHD_CONNECTION_STATE state); #endif #endif /** * Function to receive plaintext data. * * @param conn the connection struct * @param write_to where to write received data * @param max_bytes maximum number of bytes to receive * @return number of bytes written to @a write_to */ typedef ssize_t (*ReceiveCallback) (struct MHD_Connection *conn, void *write_to, size_t max_bytes); /** * Function to transmit plaintext data. * * @param conn the connection struct * @param read_from where to read data to transmit * @param max_bytes maximum number of bytes to transmit * @return number of bytes transmitted */ typedef ssize_t (*TransmitCallback) (struct MHD_Connection *conn, const void *read_from, size_t max_bytes); /** * Ability to use same connection for next request */ enum MHD_ConnKeepAlive { /** * Connection must be closed after sending response. */ MHD_CONN_MUST_CLOSE = -1, /** * KeelAlive state is not yet determined */ MHD_CONN_KEEPALIVE_UNKOWN = 0, /** * Connection can be used for serving next request */ MHD_CONN_USE_KEEPALIVE = 1, /** * Connection will be upgraded */ MHD_CONN_MUST_UPGRADE = 2 } _MHD_FIXED_ENUM; enum MHD_HTTP_Version { /** * Not a HTTP protocol or HTTP version is invalid. */ MHD_HTTP_VER_INVALID = -1, /** * HTTP version is not yet received from the client. */ MHD_HTTP_VER_UNKNOWN = 0, /** * HTTP version before 1.0, unsupported. */ MHD_HTTP_VER_TOO_OLD = 1, /** * HTTP version 1.0 */ MHD_HTTP_VER_1_0 = 2, /** * HTTP version 1.1 */ MHD_HTTP_VER_1_1 = 3, /** * HTTP version 1.2-1.9, must be used as 1.1 */ MHD_HTTP_VER_1_2__1_9 = 4, /** * HTTP future version. Unsupported. */ MHD_HTTP_VER_FUTURE = 100 } _MHD_FIXED_ENUM; /** * Returns boolean 'true' if HTTP version is supported by MHD */ #define MHD_IS_HTTP_VER_SUPPORTED(ver) (MHD_HTTP_VER_1_0 <= (ver) && \ MHD_HTTP_VER_1_2__1_9 >= (ver)) /** * Protocol should be used as HTTP/1.1 protocol. * * See the last paragraph of * https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */ #define MHD_IS_HTTP_VER_1_1_COMPAT(ver) (MHD_HTTP_VER_1_1 == (ver) || \ MHD_HTTP_VER_1_2__1_9 == (ver)) /** * The HTTP method. * * Only primary methods (specified in RFC9110) are defined here. */ enum MHD_HTTP_Method { /** * No request string has been received yet */ MHD_HTTP_MTHD_NO_METHOD = 0, /** * HTTP method GET */ MHD_HTTP_MTHD_GET = 1, /** * HTTP method HEAD */ MHD_HTTP_MTHD_HEAD = 2, /** * HTTP method POST */ MHD_HTTP_MTHD_POST = 3, /** * HTTP method PUT */ MHD_HTTP_MTHD_PUT = 4, /** * HTTP method DELETE */ MHD_HTTP_MTHD_DELETE = 5, /** * HTTP method CONNECT */ MHD_HTTP_MTHD_CONNECT = 6, /** * HTTP method OPTIONS */ MHD_HTTP_MTHD_OPTIONS = 7, /** * HTTP method TRACE */ MHD_HTTP_MTHD_TRACE = 8, /** * Other HTTP method. Check the string value. */ MHD_HTTP_MTHD_OTHER = 1000 } _MHD_FIXED_ENUM; /** * The request line processing data */ struct MHD_RequestLineProcessing { /** * The position of the next character to be processed */ size_t proc_pos; /** * The number of empty lines skipped */ unsigned int skipped_empty_lines; /** * The position of the start of the current/last found whitespace block, * zero if not found yet. */ size_t last_ws_start; /** * The position of the next character after the last known whitespace * character in the current/last found whitespace block, * zero if not found yet. */ size_t last_ws_end; /** * The pointer to the request target. * The request URI will be formed based on it. */ char *rq_tgt; /** * The pointer to the first question mark in the @a rq_tgt. */ char *rq_tgt_qmark; /** * The number of whitespace characters in the request URI */ size_t num_ws_in_uri; }; /** * The request header processing data */ struct MHD_HeaderProcessing { /** * The position of the last processed character */ size_t proc_pos; /** * The position of the first whitespace character in current contiguous * whitespace block. * Zero when no whitespace found or found non-whitespace character after * whitespace. * Must be zero, if the current character is not whitespace. */ size_t ws_start; /** * Indicates that end of the header (field) name found. * Must be false until the first colon in line is found. */ bool name_end_found; /** * The length of the header name. * Must be zero until the first colon in line is found. * Name always starts at zero position. */ size_t name_len; /** * The position of the first character of the header value. * Zero when the first character has not been found yet. */ size_t value_start; /** * Line starts with whitespace. * It's meaningful only for the first line, as other lines should be handled * as "folded". */ bool starts_with_ws; }; /** * The union of request line and header processing data */ union MHD_HeadersProcessing { /** * The request line processing data */ struct MHD_RequestLineProcessing rq_line; /** * The request header processing data */ struct MHD_HeaderProcessing hdr; }; /** * The union of text staring point and the size of the text */ union MHD_StartOrSize { /** * The starting point of the text. * Valid when the text is being processed and the end of the text * is not yet determined. */ const char *start; /** * The size of the text. * Valid when the text has been processed and the end of the text * is known. */ size_t size; }; /** * Request-specific values. * * Meaningful for the current request only. */ struct MHD_Request { /** * HTTP version string (i.e. http/1.1). Allocated * in pool. */ const char *version; /** * HTTP protocol version as enum. */ enum MHD_HTTP_Version http_ver; /** * Request method. Should be GET/POST/etc. Allocated in pool. */ const char *method; /** * The request method as enum. */ enum MHD_HTTP_Method http_mthd; /** * Requested URL (everything after "GET" only). Allocated * in pool. */ const char *url; /** * The length of the @a url in characters, not including the terminating zero. */ size_t url_len; /** * The original length of the request target. */ size_t req_target_len; /** * Linked list of parsed headers. */ struct MHD_HTTP_Req_Header *headers_received; /** * Tail of linked list of parsed headers. */ struct MHD_HTTP_Req_Header *headers_received_tail; /** * Number of bytes we had in the HTTP header, set once we * pass #MHD_CONNECTION_HEADERS_RECEIVED. * This includes the request line, all request headers, the header section * terminating empty line, with all CRLF (or LF) characters. */ size_t header_size; /** * The union of the size of all request field lines (headers) and * the starting point of the first request field line (the first header). * Until #MHD_CONNECTION_HEADERS_RECEIVED the @a start member is valid, * staring with #MHD_CONNECTION_HEADERS_RECEIVED the @a size member is valid. * The size includes CRLF (or LR) characters, but does not include * the terminating empty line. */ union MHD_StartOrSize field_lines; /** * How many more bytes of the body do we expect * to read? #MHD_SIZE_UNKNOWN for unknown. */ uint64_t remaining_upload_size; /** * Are we receiving with chunked encoding? * This will be set to #MHD_YES after we parse the headers and * are processing the body with chunks. * After we are done with the body and we are processing the footers; * once the footers are also done, this will be set to #MHD_NO again * (before the final call to the handler). * It is used only for requests, chunked encoding for response is * indicated by @a rp_props. */ bool have_chunked_upload; /** * If we are receiving with chunked encoding, where are we right * now? * Set to 0 if we are waiting to receive the chunk size; * otherwise, this is the size of the current chunk. * A value of zero is also used when we're at the end of the chunks. */ uint64_t current_chunk_size; /** * If we are receiving with chunked encoding, where are we currently * with respect to the current chunk (at what offset / position)? */ uint64_t current_chunk_offset; /** * Indicate that some of the upload payload data (from the currently * processed chunk for chunked uploads) have been processed by the * last call of the connection handler. * If any data have been processed, but some data left in the buffer * for further processing, then MHD will use zero timeout before the * next data processing round. This allow the application handler * process the data by the fixed portions or other way suitable for * application developer. * If no data have been processed, than MHD will wait for more data * to come (as it makes no sense to call the same connection handler * under the same conditions). However this is dangerous as if buffer * is completely used then connection is aborted. Connection * suspension should be used in such case. */ bool some_payload_processed; /** * We allow the main application to associate some pointer with the * HTTP request, which is passed to each #MHD_AccessHandlerCallback * and some other API calls. Here is where we store it. (MHD does * not know or care what it is). */ void *client_context; /** * Did we ever call the "default_handler" on this request? * This flag determines if we have called the #MHD_OPTION_NOTIFY_COMPLETED * handler when the request finishes. */ bool client_aware; #ifdef BAUTH_SUPPORT /** * Basic Authorization parameters. * The result of Basic Authorization header parsing. * Allocated in the connection's pool. */ const struct MHD_RqBAuth *bauth; /** * Set to true if current request headers are checked for Basic Authorization */ bool bauth_tried; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Digest Authorization parameters. * The result of Digest Authorization header parsing. * Allocated in the connection's pool. */ const struct MHD_RqDAuth *dauth; /** * Set to true if current request headers are checked for Digest Authorization */ bool dauth_tried; #endif /* DAUTH_SUPPORT */ /** * Number of bare CR characters that were replaced with space characters * in the request line or in the headers (field lines). */ size_t num_cr_sp_replaced; /** * The number of header lines skipped because they have no colon */ size_t skipped_broken_lines; /** * The data of the request line / request headers processing */ union MHD_HeadersProcessing hdrs; }; /** * Reply-specific properties. */ struct MHD_Reply_Properties { #ifdef _DEBUG bool set; /**< Indicates that other members are set and valid */ #endif /* _DEBUG */ bool use_reply_body_headers; /**< Use reply body-specific headers */ bool send_reply_body; /**< Send reply body (can be zero-sized) */ bool chunked; /**< Use chunked encoding for reply */ }; #if defined(_MHD_HAVE_SENDFILE) enum MHD_resp_sender_ { MHD_resp_sender_std = 0, MHD_resp_sender_sendfile }; #endif /* _MHD_HAVE_SENDFILE */ /** * Reply-specific values. * * Meaningful for the current reply only. */ struct MHD_Reply { /** * Response to transmit (initially NULL). */ struct MHD_Response *response; /** * HTTP response code. Only valid if response object * is already set. */ unsigned int responseCode; /** * The "ICY" response. * Reply begins with the SHOUTcast "ICY" line instead of "HTTP". */ bool responseIcy; /** * Current write position in the actual response * (excluding headers, content only; should be 0 * while sending headers). */ uint64_t rsp_write_position; /** * The copy of iov response. * Valid if iovec response is used. * Updated during send. * Members are allocated in the pool. */ struct MHD_iovec_track_ resp_iov; #if defined(_MHD_HAVE_SENDFILE) enum MHD_resp_sender_ resp_sender; #endif /* _MHD_HAVE_SENDFILE */ /** * Reply-specific properties */ struct MHD_Reply_Properties props; }; /** * State kept for each HTTP request. */ struct MHD_Connection { #ifdef EPOLL_SUPPORT /** * Next pointer for the EDLL listing connections that are epoll-ready. */ struct MHD_Connection *nextE; /** * Previous pointer for the EDLL listing connections that are epoll-ready. */ struct MHD_Connection *prevE; #endif /** * Next pointer for the DLL describing our IO state. */ struct MHD_Connection *next; /** * Previous pointer for the DLL describing our IO state. */ struct MHD_Connection *prev; /** * Next pointer for the XDLL organizing connections by timeout. * This DLL can be either the * 'manual_timeout_head/manual_timeout_tail' or the * 'normal_timeout_head/normal_timeout_tail', depending on whether a * custom timeout is set for the connection. */ struct MHD_Connection *nextX; /** * Previous pointer for the XDLL organizing connections by timeout. */ struct MHD_Connection *prevX; /** * Reference to the MHD_Daemon struct. */ struct MHD_Daemon *daemon; /** * Request-specific data */ struct MHD_Request rq; /** * Reply-specific data */ struct MHD_Reply rp; /** * The memory pool is created whenever we first read from the TCP * stream and destroyed at the end of each request (and re-created * for the next request). In the meantime, this pointer is NULL. * The pool is used for all connection-related data except for the * response (which maybe shared between connections) and the IP * address (which persists across individual requests). */ struct MemoryPool *pool; /** * We allow the main application to associate some pointer with the * TCP connection (which may span multiple HTTP requests). Here is * where we store it. (MHD does not know or care what it is). * The location is given to the #MHD_NotifyConnectionCallback and * also accessible via #MHD_CONNECTION_INFO_SOCKET_CONTEXT. */ void *socket_context; /** * Close connection after sending response? * Functions may change value from "Unknown" or "KeepAlive" to "Must close", * but no functions reset value "Must Close" to any other value. */ enum MHD_ConnKeepAlive keepalive; /** * Buffer for reading requests. Allocated in pool. Actually one * byte larger than @e read_buffer_size (if non-NULL) to allow for * 0-termination. */ char *read_buffer; /** * Buffer for writing response (headers only). Allocated * in pool. */ char *write_buffer; /** * Foreign address (of length @e addr_len). MALLOCED (not * in pool!). */ struct sockaddr_storage *addr; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Thread handle for this connection (if we are using * one thread per connection). */ MHD_thread_handle_ID_ tid; #endif /** * Size of @e read_buffer (in bytes). * This value indicates how many bytes we're willing to read * into the buffer. */ size_t read_buffer_size; /** * Position where we currently append data in @e read_buffer (the * next char after the last valid position). */ size_t read_buffer_offset; /** * Size of @e write_buffer (in bytes). */ size_t write_buffer_size; /** * Offset where we are with sending from @e write_buffer. */ size_t write_buffer_send_offset; /** * Last valid location in write_buffer (where do we * append and up to where is it safe to send?) */ size_t write_buffer_append_offset; /** * Position in the 100 CONTINUE message that * we need to send when receiving http 1.1 requests. */ size_t continue_message_write_offset; /** * Length of the foreign address. */ socklen_t addr_len; /** * Last time this connection had any activity * (reading or writing). */ uint64_t last_activity; /** * After how many milliseconds of inactivity should * this connection time out? * Zero for no timeout. */ uint64_t connection_timeout_ms; /** * Socket for this connection. Set to #MHD_INVALID_SOCKET if * this connection has died (daemon should clean * up in that case). */ MHD_socket socket_fd; /** * true if @e socket_fd is not TCP/IP (a UNIX domain socket, a pipe), * false (TCP/IP) otherwise. */ enum MHD_tristate is_nonip; /** * true if #socket_fd is non-blocking, false otherwise. */ bool sk_nonblck; /** * true if connection socket has set SIGPIPE suppression */ bool sk_spipe_suppress; /** * Tracks TCP_CORK / TCP_NOPUSH of the connection socket. */ enum MHD_tristate sk_corked; /** * Tracks TCP_NODELAY state of the connection socket. */ enum MHD_tristate sk_nodelay; /** * Has this socket been closed for reading (i.e. other side closed * the connection)? If so, we must completely close the connection * once we are done sending our response (and stop trying to read * from this socket). */ bool read_closed; /** * Some error happens during processing the connection therefore this * connection must be closed. * The error may come from the client side (like wrong request format), * from the application side (like data callback returned error), or from * the OS side (like out-of-memory). */ bool stop_with_error; /** * Response queued early, before the request is fully processed, * the client upload is rejected. * The connection cannot be reused for additional requests as the current * request is incompletely read and it is unclear where is the initial * byte of the next request. */ bool discard_request; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Set to `true` if the thread has been joined. */ bool thread_joined; #endif /** * Are we currently inside the "idle" handler (to avoid recursively * invoking it). */ bool in_idle; /** * Connection is in the cleanup DL-linked list. */ bool in_cleanup; #ifdef EPOLL_SUPPORT /** * What is the state of this socket in relation to epoll? */ enum MHD_EpollState epoll_state; #endif /** * State in the FSM for this connection. */ enum MHD_CONNECTION_STATE state; /** * What is this connection waiting for? */ enum MHD_ConnectionEventLoopInfo event_loop_info; /** * Function used for reading HTTP request stream. */ ReceiveCallback recv_cls; #ifdef UPGRADE_SUPPORT /** * If this connection was upgraded, this points to * the upgrade response details such that the * #thread_main_connection_upgrade()-logic can perform the * bi-directional forwarding. */ struct MHD_UpgradeResponseHandle *urh; #endif /* UPGRADE_SUPPORT */ #ifdef HTTPS_SUPPORT /** * State required for HTTPS/SSL/TLS support. */ gnutls_session_t tls_session; /** * State of connection's TLS layer */ enum MHD_TLS_CONN_STATE tls_state; /** * Could it be that we are ready to read due to TLS buffers * even though the socket is not? */ bool tls_read_ready; #endif /* HTTPS_SUPPORT */ /** * Is the connection suspended? */ bool suspended; /** * Are we currently in the #MHD_AccessHandlerCallback * for this connection (and thus eligible to receive * calls to #MHD_queue_response()?). */ bool in_access_handler; /** * Is the connection wanting to resume? */ volatile bool resuming; /** * Special member to be returned by #MHD_get_connection_info() */ union MHD_ConnectionInfo connection_info_dummy; }; #ifdef UPGRADE_SUPPORT /** * Buffer we use for upgrade response handling in the unlikely * case where the memory pool was so small it had no buffer * capacity left. Note that we don't expect to _ever_ use this * buffer, so it's mostly wasted memory (except that it allows * us to handle a tricky error condition nicely). So no need to * make this one big. Applications that want to perform well * should just pick an adequate size for the memory pools. */ #define RESERVE_EBUF_SIZE 8 /** * Context we pass to epoll() for each of the two sockets * of a `struct MHD_UpgradeResponseHandle`. We need to do * this so we can distinguish the two sockets when epoll() * gives us event notifications. */ struct UpgradeEpollHandle { /** * Reference to the overall response handle this struct is * included within. */ struct MHD_UpgradeResponseHandle *urh; /** * The socket this event is kind-of about. Note that this is NOT * necessarily the socket we are polling on, as for when we read * from TLS, we epoll() on the connection's socket * (`urh->connection->socket_fd`), while this then the application's * socket (where the application will read from). Nevertheless, for * the application to read, we need to first read from TLS, hence * the two are related. * * Similarly, for writing to TLS, this epoll() will be on the * connection's `socket_fd`, and this will merely be the FD which * the application would write to. Hence this struct must always be * interpreted based on which field in `struct * MHD_UpgradeResponseHandle` it is (`app` or `mhd`). */ MHD_socket socket; /** * IO-state of the @e socket (or the connection's `socket_fd`). */ enum MHD_EpollState celi; }; /** * Handle given to the application to manage special * actions relating to MHD responses that "upgrade" * the HTTP protocol (i.e. to WebSockets). */ struct MHD_UpgradeResponseHandle { /** * The connection for which this is an upgrade handle. Note that * because a response may be shared over many connections, this may * not be the only upgrade handle for the response of this connection. */ struct MHD_Connection *connection; #ifdef HTTPS_SUPPORT /** * Kept in a DLL per daemon. */ struct MHD_UpgradeResponseHandle *next; /** * Kept in a DLL per daemon. */ struct MHD_UpgradeResponseHandle *prev; #ifdef EPOLL_SUPPORT /** * Next pointer for the EDLL listing urhs that are epoll-ready. */ struct MHD_UpgradeResponseHandle *nextE; /** * Previous pointer for the EDLL listing urhs that are epoll-ready. */ struct MHD_UpgradeResponseHandle *prevE; /** * Specifies whether urh already in EDLL list of ready connections. */ bool in_eready_list; #endif /** * The buffer for receiving data from TLS to * be passed to the application. Contains @e in_buffer_size * bytes (unless @e in_buffer_size is zero). Do not free! */ char *in_buffer; /** * The buffer for receiving data from the application to * be passed to TLS. Contains @e out_buffer_size * bytes (unless @e out_buffer_size is zero). Do not free! */ char *out_buffer; /** * Size of the @e in_buffer. * Set to 0 if the TLS connection went down for reading or socketpair * went down for writing. */ size_t in_buffer_size; /** * Size of the @e out_buffer. * Set to 0 if the TLS connection went down for writing or socketpair * went down for reading. */ size_t out_buffer_size; /** * Number of bytes actually in use in the @e in_buffer. Can be larger * than @e in_buffer_size if and only if @a in_buffer_size is zero and * we still have bytes that can be forwarded. * Reset to zero if all data was forwarded to socketpair or * if socketpair went down for writing. */ size_t in_buffer_used; /** * Number of bytes actually in use in the @e out_buffer. Can be larger * than @e out_buffer_size if and only if @a out_buffer_size is zero and * we still have bytes that can be forwarded. * Reset to zero if all data was forwarded to TLS connection or * if TLS connection went down for writing. */ size_t out_buffer_used; /** * The socket we gave to the application (r/w). */ struct UpgradeEpollHandle app; /** * If @a app_sock was a socketpair, our end of it, otherwise * #MHD_INVALID_SOCKET; (r/w). */ struct UpgradeEpollHandle mhd; /** * Emergency IO buffer we use in case the memory pool has literally * nothing left. */ char e_buf[RESERVE_EBUF_SIZE]; #endif /* HTTPS_SUPPORT */ /** * Set to true after the application finished with the socket * by #MHD_UPGRADE_ACTION_CLOSE. * * When BOTH @e was_closed (changed by command from application) * AND @e clean_ready (changed internally by MHD) are set to * #MHD_YES, function #MHD_resume_connection() will move this * connection to cleanup list. * @remark This flag could be changed from any thread. */ volatile bool was_closed; /** * Set to true if connection is ready for cleanup. * * In TLS mode functions #MHD_connection_finish_forward_() must * be called before setting this flag to true. * * In thread-per-connection mode, true in this flag means * that connection's thread exited or about to exit and will * not use MHD_Connection::urh data anymore. * * In any mode true in this flag also means that * MHD_Connection::urh data will not be used for socketpair * forwarding and forwarding itself is finished. * * When BOTH @e was_closed (changed by command from application) * AND @e clean_ready (changed internally by MHD) are set to * true, function #MHD_resume_connection() will move this * connection to cleanup list. * @remark This flag could be changed from thread that process * connection's recv(), send() and response. */ volatile bool clean_ready; }; #endif /* UPGRADE_SUPPORT */ /** * Signature of function called to log URI accesses. * * @param cls closure * @param uri uri being accessed * @param con connection handle * @return new closure */ typedef void * (*LogCallback)(void *cls, const char *uri, struct MHD_Connection *con); /** * Signature of function called to unescape URIs. See also * #MHD_http_unescape(). * * @param cls closure * @param conn connection handle * @param uri 0-terminated string to unescape (should be updated) * @return length of the resulting string */ typedef size_t (*UnescapeCallback)(void *cls, struct MHD_Connection *conn, char *uri); /** * State kept for each MHD daemon. All connections are kept in two * doubly-linked lists. The first one reflects the state of the * connection in terms of what operations we are waiting for (read, * write, locally blocked, cleanup) whereas the second is about its * timeout state (default or custom). */ struct MHD_Daemon { /** * Callback function for all requests. */ MHD_AccessHandlerCallback default_handler; /** * Closure argument to default_handler. */ void *default_handler_cls; /** * Daemon's flags (bitfield). * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ enum MHD_FLAG options; /** * Head of doubly-linked list of new, externally added connections. */ struct MHD_Connection *new_connections_head; /** * Tail of doubly-linked list of new, externally added connections. */ struct MHD_Connection *new_connections_tail; /** * Head of doubly-linked list of our current, active connections. */ struct MHD_Connection *connections_head; /** * Tail of doubly-linked list of our current, active connections. */ struct MHD_Connection *connections_tail; /** * Head of doubly-linked list of our current but suspended connections. */ struct MHD_Connection *suspended_connections_head; /** * Tail of doubly-linked list of our current but suspended connections. */ struct MHD_Connection *suspended_connections_tail; /** * Head of doubly-linked list of connections to clean up. */ struct MHD_Connection *cleanup_head; /** * Tail of doubly-linked list of connections to clean up. */ struct MHD_Connection *cleanup_tail; /** * _MHD_YES if the @e listen_fd socket is a UNIX domain socket. */ enum MHD_tristate listen_is_unix; #ifdef EPOLL_SUPPORT /** * Head of EDLL of connections ready for processing (in epoll mode). */ struct MHD_Connection *eready_head; /** * Tail of EDLL of connections ready for processing (in epoll mode) */ struct MHD_Connection *eready_tail; /** * File descriptor associated with our epoll loop. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ int epoll_fd; /** * true if the @e listen_fd socket is in the 'epoll' set, * false if not. */ bool listen_socket_in_epoll; #ifdef UPGRADE_SUPPORT #ifdef HTTPS_SUPPORT /** * File descriptor associated with the #run_epoll_for_upgrade() loop. * Only available if #MHD_USE_HTTPS_EPOLL_UPGRADE is set. */ int epoll_upgrade_fd; /** * true if @e epoll_upgrade_fd is in the 'epoll' set, * false if not. */ bool upgrade_fd_in_epoll; #endif /* HTTPS_SUPPORT */ /** * Head of EDLL of upgraded connections ready for processing (in epoll mode). */ struct MHD_UpgradeResponseHandle *eready_urh_head; /** * Tail of EDLL of upgraded connections ready for processing (in epoll mode) */ struct MHD_UpgradeResponseHandle *eready_urh_tail; #endif /* UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ /** * Head of the XDLL of ALL connections with a default ('normal') * timeout, sorted by timeout (earliest at the tail, most recently * used connection at the head). MHD can just look at the tail of * this list to determine the timeout for all of its elements; * whenever there is an event of a connection, the connection is * moved back to the tail of the list. * * All connections by default start in this list; if a custom * timeout that does not match @e connection_timeout_ms is set, they * are moved to the @e manual_timeout_head-XDLL. * Not used in MHD_USE_THREAD_PER_CONNECTION mode as each thread * needs only one connection-specific timeout. */ struct MHD_Connection *normal_timeout_head; /** * Tail of the XDLL of ALL connections with a default timeout, * sorted by timeout (earliest timeout at the tail). * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *normal_timeout_tail; /** * Head of the XDLL of ALL connections with a non-default/custom * timeout, unsorted. MHD will do a O(n) scan over this list to * determine the current timeout. * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *manual_timeout_head; /** * Tail of the XDLL of ALL connections with a non-default/custom * timeout, unsorted. * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *manual_timeout_tail; /** * Function to call to check if we should accept or reject an * incoming request. May be NULL. */ MHD_AcceptPolicyCallback apc; /** * Closure argument to apc. */ void *apc_cls; /** * Function to call when we are done processing * a particular request. May be NULL. */ MHD_RequestCompletedCallback notify_completed; /** * Closure argument to @e notify_completed. */ void *notify_completed_cls; /** * Function to call when we are starting/stopping * a connection. May be NULL. */ MHD_NotifyConnectionCallback notify_connection; /** * Closure argument to @e notify_connection. */ void *notify_connection_cls; /** * Function to call with the full URI at the * beginning of request processing. May be NULL. *

    * Returns the initial pointer to internal state * kept by the client for the request. */ LogCallback uri_log_callback; /** * Closure argument to @e uri_log_callback. */ void *uri_log_callback_cls; /** * Function to call when we unescape escape sequences. */ UnescapeCallback unescape_callback; /** * Closure for @e unescape_callback. */ void *unescape_callback_cls; /** * Listen port. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ uint16_t port; #ifdef HAVE_MESSAGES /** * Function for logging error messages (if we * support error reporting). */ MHD_LogCallback custom_error_log; /** * Closure argument to @e custom_error_log. */ void *custom_error_log_cls; #endif /** * Pointer to master daemon (NULL if this is the master) */ struct MHD_Daemon *master; /** * Listen socket. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ MHD_socket listen_fd; /** * Listen socket is non-blocking. */ bool listen_nonblk; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Worker daemons (one per thread) */ struct MHD_Daemon *worker_pool; #endif /** * Table storing number of connections per IP */ void *per_ip_connection_count; /** * Number of active parallel connections. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ unsigned int connections; /** * Size of the per-connection memory pools. */ size_t pool_size; /** * Increment for growth of the per-connection memory pools. */ size_t pool_increment; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Size of threads created by MHD. */ size_t thread_stack_size; /** * Number of worker daemons */ unsigned int worker_pool_size; /** * The select thread handle (if we have internal select) */ MHD_thread_handle_ID_ tid; /** * Mutex for per-IP connection counts. */ MHD_mutex_ per_ip_connection_mutex; /** * Mutex for (modifying) access to the "cleanup", "normal_timeout" and * "manual_timeout" DLLs. */ MHD_mutex_ cleanup_connection_mutex; /** * Mutex for any access to the "new connections" DL-list. */ MHD_mutex_ new_connections_mutex; #endif /** * Our #MHD_OPTION_SERVER_INSANITY level, bits indicating * which sanity checks are off. */ enum MHD_DisableSanityCheck insanity_level; /** * Whether to allow/disallow/ignore reuse of listening address. * The semantics is the following: * 0: ignore (user did not ask for neither allow/disallow, use SO_REUSEADDR * except W32) * >0: allow (use SO_REUSEPORT on most platforms, SO_REUSEADDR on Windows) * <0: disallow (mostly no action, SO_EXCLUSIVEADDRUSE on Windows or SO_EXCLBIND * on Solaris) */ int listening_address_reuse; /** * Inter-thread communication channel (also used to unblock * select() in non-threaded code). */ struct MHD_itc_ itc; /** * Are we shutting down? */ volatile bool shutdown; /** * Has this daemon been quiesced via #MHD_quiesce_daemon()? * If so, we should no longer use the @e listen_fd (including * removing it from the @e epoll_fd when possible). */ volatile bool was_quiesced; /** * Did we hit some system or process-wide resource limit while * trying to accept() the last time? If so, we don't accept new * connections until we close an existing one. This effectively * temporarily lowers the "connection_limit" to the current * number of connections. */ bool at_limit; /* * Do we need to process resuming connections? */ volatile bool resuming; /** * Indicate that new connections in @e new_connections_head list * need to be processed. */ volatile bool have_new; /** * 'True' if some data is already waiting to be processed. * If set to 'true' - zero timeout for select()/poll*() * is used. * Should be reset each time before processing connections * and raised by any connection which require additional * immediately processing (application does not provide * data for response, data waiting in TLS buffers etc.) */ bool data_already_pending; /** * Limit on the number of parallel connections. */ unsigned int connection_limit; /** * After how many milliseconds of inactivity should * this connection time out? * Zero for no timeout. */ uint64_t connection_timeout_ms; /** * Maximum number of connections per IP, or 0 for * unlimited. */ unsigned int per_ip_connection_limit; /** * The strictness level for parsing of incoming data. * @see #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ int client_discipline; #ifdef HAS_FD_SETSIZE_OVERRIDABLE /** * The value of FD_SETSIZE used by the daemon. * For external sockets polling this is the value provided by the application * via MHD_OPTION_APP_FD_SETSIZE or current FD_SETSIZE value. * For internal threads modes this is always current FD_SETSIZE value. */ int fdset_size; /** * Indicates whether @a fdset_size value was set by application. * 'false' if default value is used. */ bool fdset_size_set_by_app; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ /** * True if SIGPIPE is blocked */ bool sigpipe_blocked; #ifdef HTTPS_SUPPORT #ifdef UPGRADE_SUPPORT /** * Head of DLL of upgrade response handles we are processing. * Used for upgraded TLS connections when thread-per-connection * is not used. */ struct MHD_UpgradeResponseHandle *urh_head; /** * Tail of DLL of upgrade response handles we are processing. * Used for upgraded TLS connections when thread-per-connection * is not used. */ struct MHD_UpgradeResponseHandle *urh_tail; #endif /* UPGRADE_SUPPORT */ /** * Desired cipher algorithms. */ gnutls_priority_t priority_cache; /** * What kind of credentials are we offering * for SSL/TLS? */ gnutls_credentials_type_t cred_type; /** * Server x509 credentials */ gnutls_certificate_credentials_t x509_cred; /** * Diffie-Hellman parameters */ gnutls_dh_params_t dh_params; /** * Server PSK credentials */ gnutls_psk_server_credentials_t psk_cred; #if GNUTLS_VERSION_MAJOR >= 3 /** * Function that can be used to obtain the certificate. Needed * for SNI support. See #MHD_OPTION_HTTPS_CERT_CALLBACK. */ gnutls_certificate_retrieve_function2 *cert_callback; /** * Function that can be used to obtain the shared key. */ MHD_PskServerCredentialsCallback cred_callback; /** * Closure for @e cred_callback. */ void *cred_callback_cls; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 /** * Function that can be used to obtain the certificate. Needed * for OCSP stapling support. See #MHD_OPTION_HTTPS_CERT_CALLBACK2. */ gnutls_certificate_retrieve_function3 *cert_callback2; #endif /** * Pointer to our SSL/TLS key (in ASCII) in memory. */ const char *https_mem_key; /** * Pointer to our SSL/TLS certificate (in ASCII) in memory. */ const char *https_mem_cert; /** * Pointer to 0-terminated HTTPS passphrase in memory. */ const char *https_key_password; /** * Pointer to our SSL/TLS certificate authority (in ASCII) in memory. */ const char *https_mem_trust; /** * Our Diffie-Hellman parameters in memory. */ gnutls_dh_params_t https_mem_dhparams; /** * true if we have initialized @e https_mem_dhparams. */ bool have_dhparams; /** * true if ALPN is disabled. */ bool disable_alpn; #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Character array of random values. */ const char *digest_auth_random; /** * Size of @a digest_auth_random. */ size_t digest_auth_rand_size; /** * The malloc'ed copy of the @a digest_auth_random. */ void *digest_auth_random_copy; /** * An array that contains the map nonce-nc. */ struct MHD_NonceNc *nnc; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * A rw-lock for synchronizing access to @e nnc. */ MHD_mutex_ nnc_lock; #endif /** * Size of the nonce-nc array. */ unsigned int nonce_nc_size; /** * Nonce bind type. */ unsigned int dauth_bind_type; /** * Default nonce validity length. */ unsigned int dauth_def_nonce_timeout; /** * Default maximum nc (nonce count) value. */ uint32_t dauth_def_max_nc; #endif #ifdef TCP_FASTOPEN /** * The queue size for incoming SYN + DATA packets. */ unsigned int fastopen_queue_size; #endif /** * The size of queue for listen socket. */ unsigned int listen_backlog_size; /* TODO: replace with a single member */ /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_listen_fd; #ifdef EPOLL_SUPPORT /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_epoll_fd; #endif /* EPOLL_SUPPORT */ /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_num_connections; /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_flags; /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_port; #if defined(_DEBUG) && defined(HAVE_ACCEPT4) /** * If set to 'true', accept() function will be used instead of accept4() even * if accept4() is available. * This is a workaround for zzuf, which does not support sockets created * by accept4() function. * There is no API to change the value of this member, it can be flipped * only by direct access to the struct member. */ bool avoid_accept4; #endif /* _DEBUG */ }; #if defined(HAVE_POLL) && defined(EPOLL_SUPPORT) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) \ (0 == (d->options & (MHD_USE_POLL | MHD_USE_EPOLL))) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL)) #elif defined(HAVE_POLL) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0) #elif defined(EPOLL_SUPPORT) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_EPOLL)) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL)) #else /* select() only */ /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) ((void) (d), ! 0) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0) #endif /* select() only */ #if defined(MHD_USE_THREADS) /** * Checks whether the @a d daemon is using internal polling thread */ #define MHD_D_IS_USING_THREADS_(d) \ (0 != (d->options & (MHD_USE_INTERNAL_POLLING_THREAD))) /** * Checks whether the @a d daemon is using thread-per-connection mode */ #define MHD_D_IS_USING_THREAD_PER_CONN_(d) \ (0 != ((d)->options & MHD_USE_THREAD_PER_CONNECTION)) /** * Check whether the @a d daemon has thread-safety enabled. */ #define MHD_D_IS_THREAD_SAFE_(d) \ (0 == ((d)->options & MHD_USE_NO_THREAD_SAFETY)) #else /* ! MHD_USE_THREADS */ /** * Checks whether the @a d daemon is using internal polling thread */ #define MHD_D_IS_USING_THREADS_(d) ((void) d, 0) /** * Checks whether the @a d daemon is using thread-per-connection mode */ #define MHD_D_IS_USING_THREAD_PER_CONN_(d) ((void) d, 0) /** * Check whether the @a d daemon has thread-safety enabled. */ #define MHD_D_IS_THREAD_SAFE_(d) ((void) d, 0) #endif /* ! MHD_USE_THREADS */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE /** * Get FD_SETSIZE used by the daemon @a d */ #define MHD_D_GET_FD_SETSIZE_(d) ((d)->fdset_size) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /** * Get FD_SETSIZE used by the daemon @a d */ #define MHD_D_GET_FD_SETSIZE_(d) (FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /** * Check whether socket @a sckt fits fd_sets used by the daemon @a d */ #define MHD_D_DOES_SCKT_FIT_FDSET_(sckt,d) \ MHD_SCKT_FD_FITS_FDSET_SETSIZE_(sckt,NULL,MHD_D_GET_FD_SETSIZE_(d)) #ifdef DAUTH_SUPPORT /** * Parameter of request's Digest Authorization header */ struct MHD_RqDAuthParam { /** * The string with length, NOT zero-terminated */ struct _MHD_str_w_len value; /** * True if string must be "unquoted" before processing. * This member is false if the string is used in DQUOTE marks, but no * backslash-escape is used in the string. */ bool quoted; }; /** * Request client's Digest Authorization header parameters */ struct MHD_RqDAuth { struct MHD_RqDAuthParam nonce; struct MHD_RqDAuthParam opaque; struct MHD_RqDAuthParam response; struct MHD_RqDAuthParam username; struct MHD_RqDAuthParam username_ext; struct MHD_RqDAuthParam realm; struct MHD_RqDAuthParam uri; /* The raw QOP value, used in the 'response' calculation */ struct MHD_RqDAuthParam qop_raw; struct MHD_RqDAuthParam cnonce; struct MHD_RqDAuthParam nc; /* Decoded values are below */ bool userhash; /* True if 'userhash' parameter has value 'true'. */ enum MHD_DigestAuthAlgo3 algo3; enum MHD_DigestAuthQOP qop; }; #endif /* DAUTH_SUPPORT */ /** * Insert an element at the head of a DLL. Assumes that head, tail and * element are structs with prev and next fields. * * @param head pointer to the head of the DLL * @param tail pointer to the tail of the DLL * @param element element to insert */ #define DLL_insert(head,tail,element) do { \ mhd_assert (NULL == (element)->next); \ mhd_assert (NULL == (element)->prev); \ (element)->next = (head); \ (element)->prev = NULL; \ if ((tail) == NULL) { \ (tail) = element; \ } else { \ (head)->prev = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a DLL. Assumes * that head, tail and element are structs * with prev and next fields. * * @param head pointer to the head of the DLL * @param tail pointer to the tail of the DLL * @param element element to remove */ #define DLL_remove(head,tail,element) do { \ mhd_assert ( (NULL != (element)->next) || ((element) == (tail))); \ mhd_assert ( (NULL != (element)->prev) || ((element) == (head))); \ if ((element)->prev == NULL) { \ (head) = (element)->next; \ } else { \ (element)->prev->next = (element)->next; \ } \ if ((element)->next == NULL) { \ (tail) = (element)->prev; \ } else { \ (element)->next->prev = (element)->prev; \ } \ (element)->next = NULL; \ (element)->prev = NULL; } while (0) /** * Insert an element at the head of a XDLL. Assumes that head, tail and * element are structs with prevX and nextX fields. * * @param head pointer to the head of the XDLL * @param tail pointer to the tail of the XDLL * @param element element to insert */ #define XDLL_insert(head,tail,element) do { \ mhd_assert (NULL == (element)->nextX); \ mhd_assert (NULL == (element)->prevX); \ (element)->nextX = (head); \ (element)->prevX = NULL; \ if (NULL == (tail)) { \ (tail) = element; \ } else { \ (head)->prevX = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a XDLL. Assumes * that head, tail and element are structs * with prevX and nextX fields. * * @param head pointer to the head of the XDLL * @param tail pointer to the tail of the XDLL * @param element element to remove */ #define XDLL_remove(head,tail,element) do { \ mhd_assert ( (NULL != (element)->nextX) || ((element) == (tail))); \ mhd_assert ( (NULL != (element)->prevX) || ((element) == (head))); \ if (NULL == (element)->prevX) { \ (head) = (element)->nextX; \ } else { \ (element)->prevX->nextX = (element)->nextX; \ } \ if (NULL == (element)->nextX) { \ (tail) = (element)->prevX; \ } else { \ (element)->nextX->prevX = (element)->prevX; \ } \ (element)->nextX = NULL; \ (element)->prevX = NULL; } while (0) /** * Insert an element at the head of a EDLL. Assumes that head, tail and * element are structs with prevE and nextE fields. * * @param head pointer to the head of the EDLL * @param tail pointer to the tail of the EDLL * @param element element to insert */ #define EDLL_insert(head,tail,element) do { \ (element)->nextE = (head); \ (element)->prevE = NULL; \ if ((tail) == NULL) { \ (tail) = element; \ } else { \ (head)->prevE = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a EDLL. Assumes * that head, tail and element are structs * with prevE and nextE fields. * * @param head pointer to the head of the EDLL * @param tail pointer to the tail of the EDLL * @param element element to remove */ #define EDLL_remove(head,tail,element) do { \ if ((element)->prevE == NULL) { \ (head) = (element)->nextE; \ } else { \ (element)->prevE->nextE = (element)->nextE; \ } \ if ((element)->nextE == NULL) { \ (tail) = (element)->prevE; \ } else { \ (element)->nextE->prevE = (element)->prevE; \ } \ (element)->nextE = NULL; \ (element)->prevE = NULL; } while (0) /** * Convert all occurrences of '+' to ' '. * * @param arg string that is modified (in place), must be 0-terminated */ void MHD_unescape_plus (char *arg); /** * Callback invoked when iterating over @a key / @a value * argument pairs during parsing. * * @param cls context of the iteration * @param key 0-terminated key string, never NULL * @param key_size number of bytes in key * @param value 0-terminated binary data, may include binary zeros, may be NULL * @param value_size number of bytes in value * @param kind origin of the key-value pair * @return #MHD_YES on success (continue to iterate) * #MHD_NO to signal failure (and abort iteration) */ typedef enum MHD_Result (*MHD_ArgumentIterator_)(void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind); /** * Parse and unescape the arguments given by the client * as part of the HTTP request URI. * * @param kind header kind to pass to @a cb * @param connection connection to add headers to * @param[in,out] args argument URI string (after "?" in URI), * clobbered in the process! * @param cb function to call on each key-value pair found * @param cls the iterator context * @return #MHD_NO on failure (@a cb returned #MHD_NO), * #MHD_YES for success (parsing succeeded, @a cb always * returned #MHD_YES) */ enum MHD_Result MHD_parse_arguments_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, char *args, MHD_ArgumentIterator_ cb, void *cls); /** * Check whether response header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * * @param response the response to query * @param key header name * @param key_len the length of @a key, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ bool MHD_check_response_header_token_ci (const struct MHD_Response *response, const char *key, size_t key_len, const char *token, size_t token_len); /** * Check whether response header contains particular static @a tkn. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param r the response to query * @param k header name * @param tkn the static string of token to find * @return true if token is found in specified header, * false otherwise */ #define MHD_check_response_header_s_token_ci(r,k,tkn) \ MHD_check_response_header_token_ci ((r),(k),MHD_STATICSTR_LEN_ (k), \ (tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Internal version of #MHD_suspend_connection(). * * @remark In thread-per-connection mode: can be called from any thread, * in any other mode: to be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the connection to suspend */ void internal_suspend_connection_ (struct MHD_Connection *connection); /** * Trace up to and return master daemon. If the supplied daemon * is a master, then return the daemon itself. * * @param daemon handle to a daemon * @return master daemon handle */ _MHD_static_inline struct MHD_Daemon * MHD_get_master (struct MHD_Daemon *const daemon) { struct MHD_Daemon *ret; if (NULL != daemon->master) ret = daemon->master; else ret = daemon; mhd_assert (NULL == ret->master); return ret; } #ifdef UPGRADE_SUPPORT /** * Mark upgraded connection as closed by application. * * The @a connection pointer must not be used after call of this function * as it may be freed in other thread immediately. * @param connection the upgraded connection to mark as closed by application */ void MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection); #endif /* UPGRADE_SUPPORT */ #endif libmicrohttpd-1.0.2/src/microhttpd/mhd_byteorder.h0000644000175000017500000001357015035214301017243 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_byteorder.h * @brief macro definitions for host byte order * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BYTEORDER_H #define MHD_BYTEORDER_H #include "mhd_options.h" #include #ifdef HAVE_ENDIAN_H #include #endif #ifdef HAVE_SYS_PARAM_H #include #endif #ifdef HAVE_MACHINE_ENDIAN_H #include #endif #ifdef HAVE_SYS_ENDIAN_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_BYTEORDER_H #include #endif #ifdef HAVE_SYS_MACHINE_H #include #endif #ifdef HAVE_MACHINE_PARAM_H #include #endif #ifdef HAVE_SYS_ISA_DEFS_H #include #endif #define _MHD_BIG_ENDIAN 1234 #define _MHD_LITTLE_ENDIAN 4321 #define _MHD_PDP_ENDIAN 2143 #if defined(__BYTE_ORDER__) #if defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == \ __ORDER_LITTLE_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__ORDER_PDP_ENDIAN__) && __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ */ #elif defined(__BYTE_ORDER) #if defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__PDP_ENDIAN) && __BYTE_ORDER == __PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER == __PDP_ENDIAN */ #elif defined(BYTE_ORDER) #if defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(PDP_ENDIAN) && BYTE_ORDER == PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER == _PDP_ENDIAN */ #elif defined(_BYTE_ORDER) #if defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(_PDP_ENDIAN) && _BYTE_ORDER == _PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* _BYTE_ORDER == _PDP_ENDIAN */ #endif /* _BYTE_ORDER */ #ifndef _MHD_BYTE_ORDER /* Byte order specification didn't detected in system headers */ /* Try some guessing */ #if (defined(__BIG_ENDIAN__) && ! defined(__LITTLE_ENDIAN__)) || \ (defined(_BIG_ENDIAN) && ! defined(_LITTLE_ENDIAN)) /* Seems that we are on big endian platform */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif (defined(__LITTLE_ENDIAN__) && ! defined(__BIG_ENDIAN__)) || \ (defined(_LITTLE_ENDIAN) && ! defined(_BIG_ENDIAN)) /* Seems that we are on little endian platform */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \ defined(__x86_64) || \ defined(_M_X64) || defined(_M_AMD64) || defined(i386) || defined(__i386) || \ defined(__i386__) || defined(__i486__) || defined(__i586__) || \ defined(__i686__) || \ defined(_M_IX86) || defined(_X86_) || defined(__THW_INTEL__) /* x86 family is little endian */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \ defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) /* Looks like we are on ARM/MIPS in big endian mode */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) /* Looks like we are on ARM/MIPS in little endian mode */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__m68k__) || defined(M68000) || defined(__hppa__) || \ defined(__hppa) || \ defined(__HPPA__) || defined(__370__) || defined(__THW_370__) || \ defined(__s390__) || defined(__s390x__) || defined(__SYSC_ZARCH__) /* Looks like we are on big endian platform */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ia64__) || defined(_IA64) || defined(__IA64__) || \ defined(__ia64) || \ defined(_M_IA64) || defined(__itanium__) || defined(__bfin__) || \ defined(__BFIN__) || defined(bfin) || defined(BFIN) /* Looks like we are on little endian platform */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(_WIN32) /* W32 is always little endian on all platforms */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(WORDS_BIGENDIAN) /* Use byte order detected by configure */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #endif /* _WIN32 */ #endif /* !_MHD_BYTE_ORDER */ #ifdef _MHD_BYTE_ORDER /* Some safety checks */ #if defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN #error \ Configure detected big endian byte order but headers specify different byte order #elif ! defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #error \ Configure did not detect big endian byte order but headers specify big endian byte order #endif /* !WORDS_BIGENDIAN && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ #endif /* _MHD_BYTE_ORDER */ #endif /* !MHD_BYTEORDER_H */ libmicrohttpd-1.0.2/src/microhttpd/response.c0000644000175000017500000022724214760713574016274 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file response.c * @brief Methods for managing response objects * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #define MHD_NO_DEPRECATION 1 #include "mhd_options.h" #ifdef HAVE_SYS_IOCTL_H #include #endif /* HAVE_SYS_IOCTL_H */ #if defined(_WIN32) && ! defined(__CYGWIN__) #include #endif /* _WIN32 && !__CYGWIN__ */ #include "internal.h" #include "response.h" #include "mhd_limits.h" #include "mhd_sockets.h" #include "mhd_itc.h" #include "mhd_str.h" #include "connection.h" #include "memorypool.h" #include "mhd_send.h" #include "mhd_compat.h" #include "mhd_assert.h" #if defined(MHD_W32_MUTEX_) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif /* MHD_W32_MUTEX_ */ #if defined(_WIN32) #include /* for lseek(), read() */ #endif /* _WIN32 */ /** * Size of single file read operation for * file-backed responses. */ #ifndef MHD_FILE_READ_BLOCK_SIZE #ifdef _WIN32 #define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */ #else /* _WIN32 */ #define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */ #endif /* _WIN32 */ #endif /* !MHD_FD_BLOCK_SIZE */ /** * Insert a new header at the first position of the response */ #define _MHD_insert_header_first(presponse, phdr) do { \ mhd_assert (NULL == phdr->next); \ mhd_assert (NULL == phdr->prev); \ if (NULL == presponse->first_header) \ { \ mhd_assert (NULL == presponse->last_header); \ presponse->first_header = phdr; \ presponse->last_header = phdr; \ } \ else \ { \ mhd_assert (NULL != presponse->last_header); \ presponse->first_header->prev = phdr; \ phdr->next = presponse->first_header; \ presponse->first_header = phdr; \ } \ } while (0) /** * Insert a new header at the last position of the response */ #define _MHD_insert_header_last(presponse, phdr) do { \ mhd_assert (NULL == phdr->next); \ mhd_assert (NULL == phdr->prev); \ if (NULL == presponse->last_header) \ { \ mhd_assert (NULL == presponse->first_header); \ presponse->last_header = phdr; \ presponse->first_header = phdr; \ } \ else \ { \ mhd_assert (NULL != presponse->first_header); \ presponse->last_header->next = phdr; \ phdr->prev = presponse->last_header; \ presponse->last_header = phdr; \ } \ } while (0) /** * Remove a header from the response */ #define _MHD_remove_header(presponse, phdr) do { \ mhd_assert (NULL != presponse->first_header); \ mhd_assert (NULL != presponse->last_header); \ if (NULL == phdr->prev) \ { \ mhd_assert (phdr == presponse->first_header); \ presponse->first_header = phdr->next; \ } \ else \ { \ mhd_assert (phdr != presponse->first_header); \ mhd_assert (phdr == phdr->prev->next); \ phdr->prev->next = phdr->next; \ } \ if (NULL == phdr->next) \ { \ mhd_assert (phdr == presponse->last_header); \ presponse->last_header = phdr->prev; \ } \ else \ { \ mhd_assert (phdr != presponse->last_header); \ mhd_assert (phdr == phdr->next->prev); \ phdr->next->prev = phdr->prev; \ } \ } while (0) /** * Add preallocated strings a header or footer line to the response without * checking. * * Header/footer strings are not checked and assumed to be correct. * * The string must not be statically allocated! * The strings must be malloc()'ed and zero terminated. The strings will * be free()'ed when the response is destroyed. * * @param response response to add a header to * @param kind header or footer * @param header the header string to add, must be malloc()'ed and * zero-terminated * @param header_len the length of the @a header * @param content the value string to add, must be malloc()'ed and * zero-terminated * @param content_len the length of the @a content */ bool MHD_add_response_entry_no_alloc_ (struct MHD_Response *response, enum MHD_ValueKind kind, char *header, size_t header_len, char *content, size_t content_len) { struct MHD_HTTP_Res_Header *hdr; mhd_assert (0 != header_len); mhd_assert (0 != content_len); if (NULL == (hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)))) return false; hdr->header = header; hdr->header_size = header_len; hdr->value = content; hdr->value_size = content_len; hdr->kind = kind; _MHD_insert_header_last (response, hdr); return true; /* Success exit point */ } /** * Add a header or footer line to the response without checking. * * It is assumed that parameters are correct. * * @param response response to add a header to * @param kind header or footer * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (like out-of-memory), * true if succeed */ bool MHD_add_response_entry_no_check_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len) { char *header_malloced; char *value_malloced; mhd_assert (0 != header_len); mhd_assert (0 != content_len); header_malloced = malloc (header_len + 1); if (NULL == header_malloced) return false; memcpy (header_malloced, header, header_len); header_malloced[header_len] = 0; value_malloced = malloc (content_len + 1); if (NULL != value_malloced) { memcpy (value_malloced, content, content_len); value_malloced[content_len] = 0; if (MHD_add_response_entry_no_alloc_ (response, kind, header_malloced, header_len, value_malloced, content_len)) return true; /* Success exit point */ free (value_malloced); } free (header_malloced); return false; /* Failure exit point */ } /** * Add a header or footer line to the response. * * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (out-of-memory, invalid header or content), * true if succeed */ static bool add_response_entry_n (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len) { if (NULL == response) return false; if (0 == header_len) return false; if (0 == content_len) return false; if (NULL != memchr (header, '\t', header_len)) return false; if (NULL != memchr (header, ' ', header_len)) return false; if (NULL != memchr (header, '\r', header_len)) return false; if (NULL != memchr (header, '\n', header_len)) return false; if (NULL != memchr (content, '\r', content_len)) return false; if (NULL != memchr (content, '\n', content_len)) return false; return MHD_add_response_entry_no_check_ (response, kind, header, header_len, content, content_len); } /** * Add a header or footer line to the response. * * @param response response to add a header to * @param kind header or footer * @param header the header to add * @param content value to add * @return #MHD_NO on error (i.e. invalid header or content format). */ static enum MHD_Result add_response_entry (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, const char *content) { size_t header_len; size_t content_len; if (NULL == content) return MHD_NO; header_len = strlen (header); content_len = strlen (content); return add_response_entry_n (response, kind, header, header_len, content, content_len) ? MHD_YES : MHD_NO; } /** * Add "Connection:" header to the response with special processing. * * "Connection:" header value will be combined with any existing "Connection:" * header, "close" token (if any) will be de-duplicated and moved to the first * position. * * @param response the response to add a header to * @param value the value to add * @return #MHD_NO on error (no memory). */ static enum MHD_Result add_response_header_connection (struct MHD_Response *response, const char *value) { static const char *key = MHD_HTTP_HEADER_CONNECTION; /** the length of the "Connection" key */ static const size_t key_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION); size_t value_len; /**< the length of the @a value */ size_t old_value_len; /**< the length of the existing "Connection" value */ size_t buf_size; /**< the size of the buffer */ size_t norm_len; /**< the length of the normalised value */ char *buf; /**< the temporal buffer */ struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ bool value_has_close; /**< the @a value has "close" token */ bool already_has_close; /**< existing "Connection" header has "close" token */ size_t pos = 0; /**< position of addition in the @a buf */ if ( (NULL != strchr (value, '\r')) || (NULL != strchr (value, '\n')) ) return MHD_NO; if (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, key, key_len); already_has_close = (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); mhd_assert (already_has_close == (0 == memcmp (hdr->value, "close", 5))); mhd_assert (NULL != hdr); } else { hdr = NULL; already_has_close = false; mhd_assert (NULL == MHD_get_response_element_n_ (response, MHD_HEADER_KIND, key, key_len)); mhd_assert (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); } if (NULL != hdr) old_value_len = hdr->value_size + 2; /* additional size for ", " */ else old_value_len = 0; value_len = strlen (value); if (value_len >= SSIZE_MAX) return MHD_NO; /* Additional space for normalisation and zero-termination */ norm_len = value_len + value_len / 2 + 1; if (norm_len >= SSIZE_MAX) return MHD_NO; buf_size = old_value_len + (size_t) norm_len; buf = malloc (buf_size); if (NULL == buf) return MHD_NO; if (1) { /* local scope */ ssize_t norm_len_s = (ssize_t) norm_len; /* Remove "close" token (if any), it will be moved to the front */ value_has_close = MHD_str_remove_token_caseless_ (value, value_len, "close", MHD_STATICSTR_LEN_ ( \ "close"), buf + old_value_len, &norm_len_s); mhd_assert (0 <= norm_len_s); if (0 > norm_len_s) { /* Must never happen with realistic sizes */ free (buf); return MHD_NO; } else norm_len = (size_t) norm_len_s; } #ifdef UPGRADE_SUPPORT if ( (NULL != response->upgrade_handler) && value_has_close) { /* The "close" token cannot be used with connection "upgrade" */ free (buf); return MHD_NO; } #endif /* UPGRADE_SUPPORT */ if (0 != norm_len) MHD_str_remove_tokens_caseless_ (buf + old_value_len, &norm_len, "keep-alive", MHD_STATICSTR_LEN_ ("keep-alive")); if (0 == norm_len) { /* New value is empty after normalisation */ if (! value_has_close) { /* The new value had no tokens */ free (buf); return MHD_NO; } if (already_has_close) { /* The "close" token is already present, nothing to modify */ free (buf); return MHD_YES; } } /* Add "close" token if required */ if (value_has_close && ! already_has_close) { /* Need to insert "close" token at the first position */ mhd_assert (buf_size >= old_value_len + norm_len \ + MHD_STATICSTR_LEN_ ("close, ") + 1); if (0 != norm_len) memmove (buf + MHD_STATICSTR_LEN_ ("close, ") + old_value_len, buf + old_value_len, norm_len + 1); memcpy (buf, "close", MHD_STATICSTR_LEN_ ("close")); pos += MHD_STATICSTR_LEN_ ("close"); } /* Add old value tokens (if any) */ if (0 != old_value_len) { if (0 != pos) { buf[pos++] = ','; buf[pos++] = ' '; } memcpy (buf + pos, hdr->value, hdr->value_size); pos += hdr->value_size; } /* Add new value token (if any) */ if (0 != norm_len) { if (0 != pos) { buf[pos++] = ','; buf[pos++] = ' '; } /* The new value tokens must be already at the correct position */ mhd_assert ((value_has_close && ! already_has_close) ? \ (MHD_STATICSTR_LEN_ ("close, ") + old_value_len == pos) : \ (old_value_len == pos)); pos += norm_len; } mhd_assert (buf_size > pos); buf[pos] = 0; /* Null terminate the result */ if (NULL == hdr) { struct MHD_HTTP_Res_Header *new_hdr; /**< new "Connection" header */ /* Create new response header entry */ new_hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)); if (NULL != new_hdr) { new_hdr->header = malloc (key_len + 1); if (NULL != new_hdr->header) { memcpy (new_hdr->header, key, key_len + 1); new_hdr->header_size = key_len; new_hdr->value = buf; new_hdr->value_size = pos; new_hdr->kind = MHD_HEADER_KIND; if (value_has_close) response->flags_auto = (MHD_RAF_HAS_CONNECTION_HDR | MHD_RAF_HAS_CONNECTION_CLOSE); else response->flags_auto = MHD_RAF_HAS_CONNECTION_HDR; _MHD_insert_header_first (response, new_hdr); return MHD_YES; } free (new_hdr); } free (buf); return MHD_NO; } /* Update existing header entry */ free (hdr->value); hdr->value = buf; hdr->value_size = pos; if (value_has_close && ! already_has_close) response->flags_auto |= MHD_RAF_HAS_CONNECTION_CLOSE; return MHD_YES; } /** * Remove tokens from "Connection:" header of the response. * * Provided tokens will be removed from "Connection:" header value. * * @param response the response to manipulate "Connection:" header * @param value the tokens to remove * @return #MHD_NO on error (no headers or tokens found). */ static enum MHD_Result del_response_header_connection (struct MHD_Response *response, const char *value) { struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_CONNECTION)); if (NULL == hdr) return MHD_NO; if (! MHD_str_remove_tokens_caseless_ (hdr->value, &hdr->value_size, value, strlen (value))) return MHD_NO; if (0 == hdr->value_size) { _MHD_remove_header (response, hdr); free (hdr->value); free (hdr->header); free (hdr); response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_HDR | (enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else { hdr->value[hdr->value_size] = 0; /* Null-terminate the result */ if (0 != (response->flags_auto & ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE))) { if (MHD_STATICSTR_LEN_ ("close") == hdr->value_size) { if (0 != memcmp (hdr->value, "close", MHD_STATICSTR_LEN_ ("close"))) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else if (MHD_STATICSTR_LEN_ ("close, ") < hdr->value_size) { if (0 != memcmp (hdr->value, "close, ", MHD_STATICSTR_LEN_ ("close, "))) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } } return MHD_YES; } /** * Add a header line to the response. * * When reply is generated with queued response, some headers are generated * automatically. Automatically generated headers are only sent to the client, * but not added back to the response object. * * The list of automatic headers: * + "Date" header is added automatically unless already set by * this function * @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK * + "Content-Length" is added automatically when required, attempt to set * it manually by this function is ignored. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * + "Transfer-Encoding" with value "chunked" is added automatically, * when chunked transfer encoding is used automatically. Same header with * the same value can be set manually by this function to enforce chunked * encoding, however for HTTP/1.0 clients chunked encoding will not be used * and manually set "Transfer-Encoding" header is automatically removed * for HTTP/1.0 clients * + "Connection" may be added automatically with value "Keep-Alive" (only * for HTTP/1.0 clients) or "Close". The header "Connection" with value * "Close" could be set by this function to enforce closure of * the connection after sending this response. "Keep-Alive" cannot be * enforced and will be removed automatically. * @see #MHD_RF_SEND_KEEP_ALIVE_HEADER * * Some headers are pre-processed by this function: * * "Connection" headers are combined into single header entry, value is * normilised, "Keep-Alive" tokens are removed. * * "Transfer-Encoding" header: the only one header is allowed, the only * allowed value is "chunked". * * "Date" header: the only one header is allowed, the second added header * replaces the first one. * * "Content-Length" application-defined header is not allowed. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * * Headers are used in order as they were added. * * @param response the response to add a header to * @param header the header name to add, no need to be static, an internal copy * will be created automatically * @param content the header value to add, no need to be static, an internal * copy will be created automatically * @return #MHD_YES on success, * #MHD_NO on error (i.e. invalid header or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content) { if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONNECTION)) return add_response_header_connection (response, content); if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_TRANSFER_ENCODING)) { if (! MHD_str_equal_caseless_ (content, "chunked")) return MHD_NO; /* Only "chunked" encoding is allowed */ if (0 != (response->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) return MHD_YES; /* Already has "chunked" encoding header */ if ( (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) && (0 == (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) ) return MHD_NO; /* Has "Content-Length" header and no "Insanity" flag */ if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_TRANS_ENC_CHUNKED; return MHD_YES; } return MHD_NO; } if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_DATE)) { if (0 != (response->flags_auto & MHD_RAF_HAS_DATE_HDR)) { struct MHD_HTTP_Res_Header *hdr; hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_DATE, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_DATE)); mhd_assert (NULL != hdr); _MHD_remove_header (response, hdr); if (NULL != hdr->value) free (hdr->value); free (hdr->header); free (hdr); } if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_DATE_HDR; return MHD_YES; } return MHD_NO; } if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONTENT_LENGTH)) { /* Generally MHD sets automatically correct "Content-Length" always when * needed. * Custom "Content-Length" header is allowed only in special cases. */ if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) || ((0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) && (0 == (response->flags_auto & (MHD_RAF_HAS_TRANS_ENC_CHUNKED | MHD_RAF_HAS_CONTENT_LENGTH)))) ) { if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_CONTENT_LENGTH; return MHD_YES; } } return MHD_NO; } return add_response_entry (response, MHD_HEADER_KIND, header, content); } /** * Add a footer line to the response. * * @param response response to remove a header from * @param footer the footer to delete * @param content value to delete * @return #MHD_NO on error (i.e. invalid footer or content format). * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content) { return add_response_entry (response, MHD_FOOTER_KIND, footer, content); } /** * Delete a header (or footer) line from the response. * * For "Connection" headers this function remove all tokens from existing * value. Successful result means that at least one token has been removed. * If all tokens are removed from "Connection" header, the empty "Connection" * header removed. * * @param response response to remove a header from * @param header the header to delete * @param content value to delete * @return #MHD_NO on error (no such header known) * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content) { struct MHD_HTTP_Res_Header *pos; size_t header_len; size_t content_len; if ( (NULL == header) || (NULL == content) ) return MHD_NO; header_len = strlen (header); if ((0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) && (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONNECTION, header_len)) return del_response_header_connection (response, content); content_len = strlen (content); pos = response->first_header; while (NULL != pos) { if ((header_len == pos->header_size) && (content_len == pos->value_size) && (0 == memcmp (header, pos->header, header_len)) && (0 == memcmp (content, pos->value, content_len))) { _MHD_remove_header (response, pos); free (pos->header); free (pos->value); free (pos); if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_TRANSFER_ENCODING, header_len) ) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_TRANS_ENC_CHUNKED); else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_DATE) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_DATE, header_len) ) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_DATE_HDR); else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONTENT_LENGTH, header_len) ) { if (NULL == MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH, header_len)) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONTENT_LENGTH); } return MHD_YES; } pos = pos->next; } return MHD_NO; } /** * Get all of the headers (and footers) added to a response. * * @param response response to query * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup response */ _MHD_EXTERN int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) { int numHeaders = 0; struct MHD_HTTP_Res_Header *pos; for (pos = response->first_header; NULL != pos; pos = pos->next) { numHeaders++; if ((NULL != iterator) && (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->value))) break; } return numHeaders; } /** * Get a particular header (or footer) from the response. * * @param response response to query * @param key which header to get * @return NULL if header does not exist * @ingroup response */ _MHD_EXTERN const char * MHD_get_response_header (struct MHD_Response *response, const char *key) { struct MHD_HTTP_Res_Header *pos; size_t key_size; if (NULL == key) return NULL; key_size = strlen (key); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ((pos->header_size == key_size) && (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) return pos->value; } return NULL; } /** * Get a particular header (or footer) element from the response. * * Function returns the first found element. * @param response response to query * @param kind the kind of element: header or footer * @param key the key which header to get * @param key_len the length of the @a key * @return NULL if header element does not exist * @ingroup response */ struct MHD_HTTP_Res_Header * MHD_get_response_element_n_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *key, size_t key_len) { struct MHD_HTTP_Res_Header *pos; mhd_assert (NULL != key); mhd_assert (0 != key[0]); mhd_assert (0 != key_len); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ((pos->header_size == key_len) && (kind == pos->kind) && (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) return pos; } return NULL; } /** * Check whether response header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * * @param response the response to query * @param key header name * @param key_len the length of @a key, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ bool MHD_check_response_header_token_ci (const struct MHD_Response *response, const char *key, size_t key_len, const char *token, size_t token_len) { struct MHD_HTTP_Res_Header *pos; if ( (NULL == key) || ('\0' == key[0]) || (NULL == token) || ('\0' == token[0]) ) return false; /* Token must not contain binary zero! */ mhd_assert (strlen (token) == token_len); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ( (pos->kind == MHD_HEADER_KIND) && (key_len == pos->header_size) && MHD_str_equal_caseless_bin_n_ (pos->header, key, key_len) && MHD_str_has_token_caseless_ (pos->value, token, token_len) ) return true; } return false; } /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown * @param block_size preferred block size for querying crc (advisory only, * MHD may still call @a crc using smaller chunks); this * is essentially the buffer size used for IO, clients * should pick a value that is appropriate for IO and * memory performance requirements * @param crc callback to use to obtain response data * @param crc_cls extra argument to @a crc * @param crfc callback to call to free @a crc_cls resources * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc) { struct MHD_Response *response; if ((NULL == crc) || (0 == block_size)) return NULL; if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response) + block_size))) return NULL; response->fd = -1; response->data = (void *) &response[1]; response->data_buffer_size = block_size; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } #endif response->crc = crc; response->crfc = crfc; response->crc_cls = crc_cls; response->reference_count = 1; response->total_size = size; return response; } /** * Set special flags and options for a response. * * @param response the response to modify * @param flags to set for the response * @param ... #MHD_RO_END terminated list of options * @return #MHD_YES on success, #MHD_NO on error */ _MHD_EXTERN enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...) { va_list ap; enum MHD_Result ret; enum MHD_ResponseOptions ro; if (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) { /* Response has custom "Content-Lengh" header */ if ( (0 != (response->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) && (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH))) { /* Request to remove MHD_RF_INSANITY_HEADER_CONTENT_LENGTH flag */ return MHD_NO; } if ( (0 != (response->flags & MHD_RF_HEAD_ONLY_RESPONSE)) && (0 == (flags & MHD_RF_HEAD_ONLY_RESPONSE))) { /* Request to remove MHD_RF_HEAD_ONLY_RESPONSE flag */ if (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) return MHD_NO; } } if ( (0 != (flags & MHD_RF_HEAD_ONLY_RESPONSE)) && (0 != response->total_size) ) return MHD_NO; ret = MHD_YES; response->flags = flags; va_start (ap, flags); while (MHD_RO_END != (ro = va_arg (ap, enum MHD_ResponseOptions))) { switch (ro) { case MHD_RO_END: /* Not possible */ break; default: ret = MHD_NO; break; } } va_end (ap); return ret; } /** * Given a file descriptor, read data from the file * to generate the response. * * @param cls pointer to the response * @param pos offset in the file to access * @param buf where to write the data * @param max number of bytes to write at most * @return number of bytes written */ static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response *response = cls; #if ! defined(_WIN32) || defined(__CYGWIN__) ssize_t n; #else /* _WIN32 && !__CYGWIN__ */ const HANDLE fh = (HANDLE) (uintptr_t) _get_osfhandle (response->fd); #endif /* _WIN32 && !__CYGWIN__ */ const int64_t offset64 = (int64_t) (pos + response->fd_off); if (offset64 < 0) return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ #if ! defined(_WIN32) || defined(__CYGWIN__) if (max > SSIZE_MAX) max = SSIZE_MAX; /* Clamp to maximum return value. */ #if defined(HAVE_PREAD64) n = pread64 (response->fd, buf, max, offset64); #elif defined(HAVE_PREAD) if ( (sizeof(off_t) < sizeof (uint64_t)) && (offset64 > (uint64_t) INT32_MAX) ) return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */ n = pread (response->fd, buf, max, (off_t) offset64); #else /* ! HAVE_PREAD */ #if defined(HAVE_LSEEK64) if (lseek64 (response->fd, offset64, SEEK_SET) != offset64) return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ #else /* ! HAVE_LSEEK64 */ if ( (sizeof(off_t) < sizeof (uint64_t)) && (offset64 > (uint64_t) INT32_MAX) ) return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ if (lseek (response->fd, (off_t) offset64, SEEK_SET) != (off_t) offset64) return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ #endif /* ! HAVE_LSEEK64 */ n = read (response->fd, buf, max); #endif /* ! HAVE_PREAD */ if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; if (n < 0) return MHD_CONTENT_READER_END_WITH_ERROR; return n; #else /* _WIN32 && !__CYGWIN__ */ if (INVALID_HANDLE_VALUE == fh) return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */ else { OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0}; /* Initialize to zero. */ ULARGE_INTEGER pos_uli; DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max; DWORD resRead; pos_uli.QuadPart = (uint64_t) offset64; /* Simple transformation 64bit -> 2x32bit. */ f_ol.Offset = pos_uli.LowPart; f_ol.OffsetHigh = pos_uli.HighPart; if (! ReadFile (fh, (void *) buf, toRead, &resRead, &f_ol)) return MHD_CONTENT_READER_END_WITH_ERROR; /* Read error. */ if (0 == resRead) return MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) resRead; } #endif /* _WIN32 && !__CYGWIN__ */ } /** * Given a pipe descriptor, read data from the pipe * to generate the response. * * @param cls pointer to the response * @param pos offset in the pipe to access (ignored) * @param buf where to write the data * @param max number of bytes to write at most * @return number of bytes written */ static ssize_t pipe_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response *response = cls; ssize_t n; (void) pos; #ifndef _WIN32 if (SSIZE_MAX < max) max = SSIZE_MAX; n = read (response->fd, buf, (MHD_SCKT_SEND_SIZE_) max); #else /* _WIN32 */ if (UINT_MAX < max) max = INT_MAX; n = read (response->fd, buf, (unsigned int) max); #endif /* _WIN32 */ if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; if (n < 0) return MHD_CONTENT_READER_END_WITH_ERROR; return n; } /** * Destroy file reader context. Closes the file * descriptor. * * @param cls pointer to file descriptor */ static void free_callback (void *cls) { struct MHD_Response *response = cls; (void) close (response->fd); response->fd = -1; } #undef MHD_create_response_from_fd_at_offset /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * Be careful! `off_t` may have been compiled to be a * 64-bit variable for MHD, in which case your application * also has to be compiled using the same options! Read * the MHD manual for more details. * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset) { if (0 > offset) return NULL; return MHD_create_response_from_fd_at_offset64 (size, fd, (uint64_t) offset); } /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * reading file beyond 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset64 (uint64_t size, int fd, uint64_t offset) { struct MHD_Response *response; #if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64) if ( (sizeof(uint64_t) > sizeof(off_t)) && ( (size > (uint64_t) INT32_MAX) || (offset > (uint64_t) INT32_MAX) || ((size + offset) >= (uint64_t) INT32_MAX) ) ) return NULL; #endif if ( ((int64_t) size < 0) || ((int64_t) offset < 0) || ((int64_t) (size + offset) < 0) ) return NULL; response = MHD_create_response_from_callback (size, MHD_FILE_READ_BLOCK_SIZE, &file_reader, NULL, &free_callback); if (NULL == response) return NULL; response->fd = fd; response->is_pipe = false; response->fd_off = offset; response->crc_cls = response; return response; } /** * Create a response object with the response body created by reading * the provided pipe. * * The response object can be extended with header information and * then be used ONLY ONCE. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param fd file descriptor referring to a read-end of a pipe with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_pipe (int fd) { struct MHD_Response *response; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, MHD_FILE_READ_BLOCK_SIZE, &pipe_reader, NULL, &free_callback); if (NULL == response) return NULL; response->fd = fd; response->is_pipe = true; response->crc_cls = response; return response; } /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the data * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd (size_t size, int fd) { return MHD_create_response_from_fd_at_offset64 (size, fd, 0); } /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd64 (uint64_t size, int fd) { return MHD_create_response_from_fd_at_offset64 (size, fd, 0); } /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the @a data portion of the response * @param data the data itself * @param must_free libmicrohttpd should free data when done * @param must_copy libmicrohttpd must make a copy of @a data * right away, the data may be released anytime after * this call returns * @return NULL on error (i.e. invalid arguments, out of memory) * @deprecated use #MHD_create_response_from_buffer instead * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy) { enum MHD_ResponseMemoryMode mode; if (0 != must_copy) mode = MHD_RESPMEM_MUST_COPY; else if (0 != must_free) mode = MHD_RESPMEM_MUST_FREE; else mode = MHD_RESPMEM_PERSISTENT; return MHD_create_response_from_buffer (size, data, mode); } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param mode flags for buffer management * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *buffer, enum MHD_ResponseMemoryMode mode) { if (MHD_RESPMEM_MUST_FREE == mode) return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, &free, buffer); if (MHD_RESPMEM_MUST_COPY == mode) return MHD_create_response_from_buffer_copy (size, buffer); return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, NULL, NULL); } /** * Create a response object with the content of provided statically allocated * buffer used as the response body. * * The buffer must be valid for the lifetime of the response. The easiest way * to achieve this is to use a statically allocated buffer. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_static (size_t size, const void *buffer) { return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, NULL, NULL); } /** * Create a response object with the content of provided temporal buffer * used as the response body. * * An internal copy of the buffer will be made automatically, so buffer have * to be valid only during the call of this function (as a typical example: * buffer is a local (non-static) array). * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_copy (size_t size, const void *buffer) { struct MHD_Response *r; void *mhd_copy; if (0 == size) return MHD_create_response_from_buffer_with_free_callback_cls (0, NULL, NULL, NULL); if (NULL == buffer) return NULL; mhd_copy = malloc (size); if (NULL == mhd_copy) return NULL; memcpy (mhd_copy, buffer, size); r = MHD_create_response_from_buffer_with_free_callback_cls (size, mhd_copy, &free, mhd_copy); if (NULL == r) free (mhd_copy); else { /* TODO: remove the next assignment, the buffer should not be modifiable */ r->data_buffer_size = size; } return r; } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to free the @a buffer * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *buffer, MHD_ContentReaderFreeCallback crfc) { return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, crfc, buffer); } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to cleanup, if set to NULL then callback * is not called * @param crfc_cls an argument for @a crfc * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097302 * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback_cls (size_t size, const void *buffer, MHD_ContentReaderFreeCallback crfc, void *crfc_cls) { struct MHD_Response *r; if ((NULL == buffer) && (size > 0)) return NULL; #if SIZEOF_SIZE_T >= SIZEOF_UINT64_T if (MHD_SIZE_UNKNOWN == size) return NULL; #endif /* SIZEOF_SIZE_T >= SIZEOF_UINT64_T */ r = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == r) return NULL; #if defined(MHD_USE_THREADS) if (! MHD_mutex_init_ (&r->mutex)) { free (r); return NULL; } #endif r->fd = -1; r->reference_count = 1; r->total_size = size; r->data = buffer; r->data_size = size; r->crfc = crfc; r->crc_cls = crfc_cls; return r; } /** * Create a response object with an array of memory buffers * used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param iov the array for response data buffers, an internal copy of this * will be made * @param iovcnt the number of elements in @a iov * @param free_cb the callback to clean up any data associated with @a iov when * the response is destroyed. * @param cls the argument passed to @a free_cb * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, unsigned int iovcnt, MHD_ContentReaderFreeCallback free_cb, void *cls) { struct MHD_Response *response; unsigned int i; int i_cp = 0; /**< Index in the copy of iov */ uint64_t total_size = 0; const void *last_valid_buffer = NULL; if ((NULL == iov) && (0 < iovcnt)) return NULL; response = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == response) return NULL; if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } /* Calculate final size, number of valid elements, and check 'iov' */ for (i = 0; i < iovcnt; ++i) { if (0 == iov[i].iov_len) continue; /* skip zero-sized elements */ if (NULL == iov[i].iov_base) { i_cp = -1; /* error */ break; } if ( (total_size > (total_size + iov[i].iov_len)) || (INT_MAX == i_cp) || (SSIZE_MAX < (total_size + iov[i].iov_len)) ) { i_cp = -1; /* overflow */ break; } last_valid_buffer = iov[i].iov_base; total_size += iov[i].iov_len; #if defined(MHD_POSIX_SOCKETS) || ! defined(_WIN64) i_cp++; #else /* ! MHD_POSIX_SOCKETS && _WIN64 */ { int64_t i_add; i_add = (int64_t) (iov[i].iov_len / ULONG_MAX); if (0 != iov[i].iov_len % ULONG_MAX) i_add++; if (INT_MAX < (i_add + i_cp)) { i_cp = -1; /* overflow */ break; } i_cp += (int) i_add; } #endif /* ! MHD_POSIX_SOCKETS && _WIN64 */ } if (-1 == i_cp) { /* Some error condition */ MHD_mutex_destroy_chk_ (&response->mutex); free (response); return NULL; } response->fd = -1; response->reference_count = 1; response->total_size = total_size; response->crc_cls = cls; response->crfc = free_cb; if (0 == i_cp) { mhd_assert (0 == total_size); return response; } if (1 == i_cp) { mhd_assert (NULL != last_valid_buffer); response->data = last_valid_buffer; response->data_size = (size_t) total_size; return response; } mhd_assert (1 < i_cp); if (1) { /* for local variables local scope only */ MHD_iovec_ *iov_copy; int num_copy_elements = i_cp; iov_copy = MHD_calloc_ ((size_t) num_copy_elements, \ sizeof(MHD_iovec_)); if (NULL == iov_copy) { MHD_mutex_destroy_chk_ (&response->mutex); free (response); return NULL; } i_cp = 0; for (i = 0; i < iovcnt; ++i) { size_t element_size = iov[i].iov_len; const uint8_t *buf = (const uint8_t *) iov[i].iov_base; if (0 == element_size) continue; /* skip zero-sized elements */ #if defined(MHD_WINSOCK_SOCKETS) && defined(_WIN64) while (MHD_IOV_ELMN_MAX_SIZE < element_size) { iov_copy[i_cp].iov_base = (char *) _MHD_DROP_CONST (buf); iov_copy[i_cp].iov_len = ULONG_MAX; buf += ULONG_MAX; element_size -= ULONG_MAX; i_cp++; } #endif /* MHD_WINSOCK_SOCKETS && _WIN64 */ iov_copy[i_cp].iov_base = _MHD_DROP_CONST (buf); iov_copy[i_cp].iov_len = (MHD_iov_size_) element_size; i_cp++; } mhd_assert (num_copy_elements == i_cp); mhd_assert (0 <= i_cp); response->data_iov = iov_copy; response->data_iovcnt = (unsigned int) i_cp; } return response; } /** * Create a response object with empty (zero size) body. * * The response object can be extended with header information and then be used * any number of times. * * This function is a faster equivalent of #MHD_create_response_from_buffer call * with zero size combined with call of #MHD_set_response_options. * * @param flags the flags for the new response object * @return NULL on error (i.e. invalid arguments, out of memory), * the pointer to the created response object otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_empty (enum MHD_ResponseFlags flags) { struct MHD_Response *r; r = (struct MHD_Response *) MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL != r) { if (MHD_mutex_init_ (&r->mutex)) { r->fd = -1; r->reference_count = 1; /* If any flags combination will be not allowed, replace the next * assignment with MHD_set_response_options() call. */ r->flags = flags; return r; /* Successful result */ } free (r); } return NULL; /* Something failed */ } #ifdef UPGRADE_SUPPORT /** * This connection-specific callback is provided by MHD to * applications (unusual) during the #MHD_UpgradeHandler. * It allows applications to perform 'special' actions on * the underlying socket from the upgrade. * * @param urh the handle identifying the connection to perform * the upgrade @a action on. * @param action which action should be performed * @param ... arguments to the action (depends on the action) * @return #MHD_NO on error, #MHD_YES on success */ _MHD_EXTERN enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...) { struct MHD_Connection *connection; struct MHD_Daemon *daemon; if (NULL == urh) return MHD_NO; connection = urh->connection; /* Precaution checks on external data. */ if (NULL == connection) return MHD_NO; daemon = connection->daemon; if (NULL == daemon) return MHD_NO; switch (action) { case MHD_UPGRADE_ACTION_CLOSE: if (urh->was_closed) return MHD_NO; /* Already closed. */ /* transition to special 'closed' state for start of cleanup */ #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS) ) { /* signal that app is done by shutdown() of 'app' socket */ /* Application will not use anyway this socket after this command. */ shutdown (urh->app.socket, SHUT_RDWR); } #endif /* HTTPS_SUPPORT */ mhd_assert (MHD_CONNECTION_UPGRADE == connection->state); /* The next function will mark the connection as closed by application * by setting 'urh->was_closed'. * As soon as connection will be marked with BOTH * 'urh->was_closed' AND 'urh->clean_ready', it will * be moved to cleanup list by MHD_resume_connection(). */ MHD_upgraded_connection_mark_app_closed_ (connection); return MHD_YES; case MHD_UPGRADE_ACTION_CORK_ON: /* Unportable API. TODO: replace with portable action. */ return MHD_connection_set_cork_state_ (connection, true) ? MHD_YES : MHD_NO; case MHD_UPGRADE_ACTION_CORK_OFF: /* Unportable API. TODO: replace with portable action. */ return MHD_connection_set_cork_state_ (connection, false) ? MHD_YES : MHD_NO; default: /* we don't understand this one */ return MHD_NO; } } /** * We are done sending the header of a given response to the client. * Now it is time to perform the upgrade and hand over the connection * to the application. * @remark To be called only from thread that process connection's * recv(), send() and response. Must be called right after sending * response headers. * * @param response the response that was created for an upgrade * @param connection the specific connection we are upgrading * @return #MHD_YES on success, #MHD_NO on failure (will cause * connection to be closed) */ enum MHD_Result MHD_response_execute_upgrade_ (struct MHD_Response *response, struct MHD_Connection *connection) { #if defined(HTTPS_SUPPORT) || defined(_DEBUG) || defined(HAVE_MESSAGES) struct MHD_Daemon *const daemon = connection->daemon; #endif /* HTTPS_SUPPORT || _DEBUG || HAVE_MESSAGES */ struct MHD_UpgradeResponseHandle *urh; size_t rbo; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ /* "Upgrade" responses accepted only if MHD_ALLOW_UPGRADE is enabled */ mhd_assert (0 != (daemon->options & MHD_ALLOW_UPGRADE)); /* The header was checked when response queued */ mhd_assert (NULL != \ MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_UPGRADE))); if (! connection->sk_nonblck) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot execute \"upgrade\" as the socket is in " \ "the blocking mode.\n")); #endif return MHD_NO; } urh = MHD_calloc_ (1, sizeof (struct MHD_UpgradeResponseHandle)); if (NULL == urh) return MHD_NO; urh->connection = connection; rbo = connection->read_buffer_offset; connection->read_buffer_offset = 0; MHD_connection_set_nodelay_state_ (connection, false); MHD_connection_set_cork_state_ (connection, false); #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS) ) { MHD_socket sv[2]; #if defined(MHD_socket_nosignal_) || ! defined(MHD_socket_pair_nblk_) int res1; int res2; #endif /* MHD_socket_nosignal_ || !MHD_socket_pair_nblk_ */ #ifdef MHD_socket_pair_nblk_ if (! MHD_socket_pair_nblk_ (sv)) { free (urh); return MHD_NO; } #else /* !MHD_socket_pair_nblk_ */ if (! MHD_socket_pair_ (sv)) { free (urh); return MHD_NO; } res1 = MHD_socket_nonblocking_ (sv[0]); res2 = MHD_socket_nonblocking_ (sv[1]); if ( (! res1) || (! res2) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to make loopback sockets non-blocking.\n")); #endif if (! res2) { /* Socketpair cannot be used. */ MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } } #endif /* !MHD_socket_pair_nblk_ */ #ifdef MHD_socket_nosignal_ res1 = MHD_socket_nosignal_ (sv[0]); res2 = MHD_socket_nosignal_ (sv[1]); if ( (! res1) || (! res2) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set SO_NOSIGPIPE on loopback sockets.\n")); #endif #ifndef MSG_NOSIGNAL if (! res2) { /* Socketpair cannot be used. */ MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } #endif /* ! MSG_NOSIGNAL */ } #endif /* MHD_socket_nosignal_ */ if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (sv[1], daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Socketpair descriptor is not less than FD_SETSIZE: " \ "%d >= %d\n"), (int) sv[1], (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } urh->app.socket = sv[0]; urh->app.urh = urh; urh->app.celi = MHD_EPOLL_STATE_UNREADY; urh->mhd.socket = sv[1]; urh->mhd.urh = urh; urh->mhd.celi = MHD_EPOLL_STATE_UNREADY; #ifdef EPOLL_SUPPORT /* Launch IO processing by the event loop */ if (MHD_D_IS_USING_EPOLL_ (daemon)) { /* We're running with epoll(), need to add the sockets to the event set of the daemon's `epoll_upgrade_fd` */ struct epoll_event event; mhd_assert (-1 != daemon->epoll_upgrade_fd); /* First, add network socket */ event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = &urh->app; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } /* Second, add our end of the UNIX socketpair() */ event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = &urh->mhd; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_ADD, urh->mhd.socket, &event)) { event.events = EPOLLIN | EPOLLOUT | EPOLLPRI; event.data.ptr = &urh->app; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, connection->socket_fd, &event)) MHD_PANIC (_ ("Error cleaning up while handling epoll error.\n")); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } EDLL_insert (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = true; } #endif /* EPOLL_SUPPORT */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* This takes care of further processing for most event loops: simply add to DLL for bi-direcitonal processing */ DLL_insert (daemon->urh_head, daemon->urh_tail, urh); } /* In thread-per-connection mode, thread will switch to forwarding once * connection.urh is not NULL and connection.state == MHD_CONNECTION_UPGRADE. */ } else { urh->app.socket = MHD_INVALID_SOCKET; urh->mhd.socket = MHD_INVALID_SOCKET; /* Non-TLS connection do not hold any additional resources. */ urh->clean_ready = true; } #else /* ! HTTPS_SUPPORT */ urh->clean_ready = true; #endif /* ! HTTPS_SUPPORT */ connection->urh = urh; /* As far as MHD's event loops are concerned, this connection is suspended; it will be resumed once application is done by the #MHD_upgrade_action() function */ internal_suspend_connection_ (connection); /* hand over socket to application */ response->upgrade_handler (response->upgrade_handler_cls, connection, connection->rq.client_context, connection->read_buffer, rbo, #ifdef HTTPS_SUPPORT (0 == (daemon->options & MHD_USE_TLS) ) ? connection->socket_fd : urh->app.socket, #else /* ! HTTPS_SUPPORT */ connection->socket_fd, #endif /* ! HTTPS_SUPPORT */ urh); #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS)) { struct MemoryPool *const pool = connection->pool; size_t avail; char *buf; /* All data should be sent already */ mhd_assert (connection->write_buffer_send_offset == \ connection->write_buffer_append_offset); MHD_pool_deallocate (pool, connection->write_buffer, connection->write_buffer_size); connection->write_buffer_append_offset = 0; connection->write_buffer_send_offset = 0; connection->write_buffer_size = 0; connection->write_buffer = NULL; /* Extra read data should be processed already by the application */ MHD_pool_deallocate (pool, connection->read_buffer, connection->read_buffer_size); connection->read_buffer_offset = 0; connection->read_buffer_size = 0; connection->read_buffer = NULL; avail = MHD_pool_get_free (pool); if (avail < RESERVE_EBUF_SIZE) { /* connection's pool is totally at the limit, use our 'emergency' buffer of #RESERVE_EBUF_SIZE bytes. */ avail = RESERVE_EBUF_SIZE; buf = urh->e_buf; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Memory shortage in connection's memory pool. " \ "The \"upgraded\" communication will be inefficient.\n")); #endif } else { /* Normal case: grab all remaining memory from the connection's pool for the IO buffers; the connection certainly won't need it anymore as we've upgraded to another protocol. */ buf = MHD_pool_allocate (pool, avail, false); } /* use half the buffer for inbound, half for outbound */ urh->in_buffer_size = avail / 2; urh->out_buffer_size = avail - urh->in_buffer_size; urh->in_buffer = buf; urh->out_buffer = buf + urh->in_buffer_size; } #endif /* HTTPS_SUPPORT */ return MHD_YES; } /** * Create a response object that can be used for 101 UPGRADE * responses, for example to implement WebSockets. After sending the * response, control over the data stream is given to the callback (which * can then, for example, start some bi-directional communication). * If the response is queued for multiple connections, the callback * will be called for each connection. The callback * will ONLY be called after the response header was successfully passed * to the OS; if there are communication errors before, the usual MHD * connection error handling code will be performed. * * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS) * and setting correct HTTP headers for the upgrade must be done * manually (this way, it is possible to implement most existing * WebSocket versions using this API; in fact, this API might be useful * for any protocol switch, not just WebSockets). Note that * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 * Switching Protocols" (if the response code 101 is used). * * As usual, the response object can be extended with header * information and then be used any number of times (as long as the * header information is not connection-specific). * * @param upgrade_handler function to call with the 'upgraded' socket * @param upgrade_handler_cls closure for @a upgrade_handler * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) { struct MHD_Response *response; if (NULL == upgrade_handler) return NULL; /* invalid request */ response = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == response) return NULL; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } #endif response->upgrade_handler = upgrade_handler; response->upgrade_handler_cls = upgrade_handler_cls; response->total_size = 0; response->reference_count = 1; if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "Upgrade")) { MHD_destroy_response (response); return NULL; } return response; } #endif /* UPGRADE_SUPPORT */ /** * Destroy a response object and associated resources. Note that * libmicrohttpd may keep some of the resources around if the response * is still in the queue for some clients, so the memory may not * necessarily be freed immediately. * * @param response response to destroy * @ingroup response */ _MHD_EXTERN void MHD_destroy_response (struct MHD_Response *response) { struct MHD_HTTP_Res_Header *pos; if (NULL == response) return; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&response->mutex); #endif if (0 != --(response->reference_count)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); MHD_mutex_destroy_chk_ (&response->mutex); #endif if (NULL != response->crfc) response->crfc (response->crc_cls); if (NULL != response->data_iov) { free (response->data_iov); } while (NULL != response->first_header) { pos = response->first_header; response->first_header = pos->next; free (pos->header); free (pos->value); free (pos); } free (response); } /** * Increments the reference counter for the @a response. * * @param response object to modify */ void MHD_increment_response_rc (struct MHD_Response *response) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&response->mutex); #endif (response->reference_count)++; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif } /* end of response.c */ libmicrohttpd-1.0.2/src/microhttpd/mhd_align.h0000644000175000017500000000570515035214301016337 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_align.h * @brief types alignment macros * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_ALIGN_H #define MHD_ALIGN_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include #endif #ifdef HAVE_C_ALIGNOF #ifdef HAVE_STDALIGN_H #include #endif /* HAVE_STDALIGN_H */ #define _MHD_ALIGNOF(type) alignof(type) #endif /* HAVE_C_ALIGNOF */ #ifndef _MHD_ALIGNOF #if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER >= 1700 #define _MHD_ALIGNOF(type) __alignof(type) #endif /* _MSC_VER >= 1700 */ #endif /* !_MHD_ALIGNOF */ #ifdef _MHD_ALIGNOF #if (defined(__GNUC__) && __GNUC__ < 4 && __GNUC_MINOR__ < 9 && \ ! defined(__clang__)) || \ (defined(__clang__) && __clang_major__ < 8) || \ (defined(__clang__) && __clang_major__ < 11 && \ defined(__apple_build_version__)) /* GCC before 4.9 and clang before 8.0 have incorrect implementation of 'alignof()' which returns preferred alignment instead of minimal required alignment */ #define _MHD_ALIGNOF_UNRELIABLE 1 #endif #if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER < 1900 /* MSVC has the same problem as old GCC versions: '__alignof()' may return "preferred" alignment instead of "required". */ #define _MHD_ALIGNOF_UNRELIABLE 1 #endif /* _MSC_VER < 1900 */ #endif /* _MHD_ALIGNOF */ #ifdef offsetof #define _MHD_OFFSETOF(strct, membr) offsetof(strct, membr) #else /* ! offsetof */ #define _MHD_OFFSETOF(strct, membr) (size_t)(((char*)&(((strct*)0)->membr)) - \ ((char*)((strct*)0))) #endif /* ! offsetof */ /* Provide a limited set of alignment macros */ /* The set could be extended as needed */ #if defined(_MHD_ALIGNOF) && ! defined(_MHD_ALIGNOF_UNRELIABLE) #define _MHD_UINT32_ALIGN _MHD_ALIGNOF(uint32_t) #define _MHD_UINT64_ALIGN _MHD_ALIGNOF(uint64_t) #else /* ! _MHD_ALIGNOF */ struct _mhd_dummy_uint32_offset_test { char dummy; uint32_t ui32; }; #define _MHD_UINT32_ALIGN \ _MHD_OFFSETOF(struct _mhd_dummy_uint32_offset_test, ui32) struct _mhd_dummy_uint64_offset_test { char dummy; uint64_t ui64; }; #define _MHD_UINT64_ALIGN \ _MHD_OFFSETOF(struct _mhd_dummy_uint64_offset_test, ui64) #endif /* ! _MHD_ALIGNOF */ #endif /* ! MHD_ALIGN_H */ libmicrohttpd-1.0.2/src/microhttpd/microhttpd_dll_res.rc.in0000644000175000017500000000331715035214301021055 00000000000000/* W32 resources */ #include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US VS_VERSION_INFO VERSIONINFO FILEVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0 PRODUCTVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0 FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #if defined(_DEBUG) FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0 #endif FILEOS VOS_NT_WINDOWS32 #ifdef DLL_EXPORT FILETYPE VFT_DLL #else FILETYPE VFT_STATIC_LIB #endif FILESUBTYPE VFT2_UNKNOWN BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "04090000" /* Lang = US English, Charset = ASCII */ BEGIN VALUE "ProductName", "GNU libmicrohttpd\0" VALUE "ProductVersion", "@PACKAGE_VERSION@\0" VALUE "FileVersion", "@PACKAGE_VERSION@\0" #ifdef DLL_EXPORT VALUE "FileDescription", "GNU libmicrohttpd DLL for Windows (MinGW build, @W32CRT@ run-time lib)\0" #else VALUE "FileDescription", "GNU libmicrohttpd static library for Windows (MinGW build, @W32CRT@ run-time lib)\0" #endif VALUE "InternalName", "libmicrohttpd\0" #ifdef DLL_EXPORT VALUE "OriginalFilename", "libmicrohttpd-@MHD_W32_DLL_SUFF@.dll\0" #else VALUE "OriginalFilename", "libmicrohttpd.lib\0" #endif VALUE "CompanyName", "Free Software Foundation\0" VALUE "LegalCopyright", "Copyright (C) 2007-2024 Christian Grothoff, Evgeny Grin, and project contributors\0" VALUE "Comments", "http://www.gnu.org/software/libmicrohttpd/\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0409, 0 /* US English, ASCII */ END END libmicrohttpd-1.0.2/src/microhttpd/memorypool.h0000644000175000017500000001433115035214301016612 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007--2024 Daniel Pittman and Christian Grothoff Copyright (C) 2016--2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file memorypool.h * @brief memory pool; mostly used for efficient (de)allocation * for each connection and bounding memory use for each * request * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MEMORYPOOL_H #define MEMORYPOOL_H #include "mhd_options.h" #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STDBOOL_H #include #endif /** * Opaque handle for a memory pool. * Pools are not reentrant and must not be used * by multiple threads. */ struct MemoryPool; /** * Initialize values for memory pools */ void MHD_init_mem_pools_ (void); /** * Create a memory pool. * * @param max maximum size of the pool * @return NULL on error */ struct MemoryPool * MHD_pool_create (size_t max); /** * Destroy a memory pool. * * @param pool memory pool to destroy */ void MHD_pool_destroy (struct MemoryPool *pool); /** * Allocate size bytes from the pool. * * @param pool memory pool to use for the operation * @param size number of bytes to allocate * @param from_end allocate from end of pool (set to 'true'); * use this for small, persistent allocations that * will never be reallocated * @return NULL if the pool cannot support size more * bytes */ void * MHD_pool_allocate (struct MemoryPool *pool, size_t size, bool from_end); /** * Checks whether allocated block is re-sizable in-place. * If block is not re-sizable in-place, it still could be shrunk, but freed * memory will not be re-used until reset of the pool. * @param pool the memory pool to use * @param block the pointer to the allocated block to check * @param block_size the size of the allocated @a block * @return true if block can be resized in-place in the optimal way, * false otherwise */ bool MHD_pool_is_resizable_inplace (struct MemoryPool *pool, void *block, size_t block_size); /** * Try to allocate @a size bytes memory area from the @a pool. * * If allocation fails, @a required_bytes is updated with size required to be * freed in the @a pool from rellocatable area to allocate requested number * of bytes. * Allocated memory area is always not rellocatable ("from end"). * * @param pool memory pool to use for the operation * @param size the size of memory in bytes to allocate * @param[out] required_bytes the pointer to variable to be updated with * the size of the required additional free * memory area, set to 0 if function succeeds. * Cannot be NULL. * @return the pointer to allocated memory area if succeed, * NULL if the pool doesn't have enough space, required_bytes is updated * with amount of space needed to be freed in rellocatable area or * set to SIZE_MAX if requested size is too large for the pool. */ void * MHD_pool_try_alloc (struct MemoryPool *pool, size_t size, size_t *required_bytes); /** * Reallocate a block of memory obtained from the pool. * This is particularly efficient when growing or * shrinking the block that was last (re)allocated. * If the given block is not the most recently * (re)allocated block, the memory of the previous * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param old the existing block * @param old_size the size of the existing block * @param new_size the new size of the block * @return new address of the block, or * NULL if the pool cannot support @a new_size * bytes (old continues to be valid for @a old_size) */ void * MHD_pool_reallocate (struct MemoryPool *pool, void *old, size_t old_size, size_t new_size); /** * Check how much memory is left in the @a pool * * @param pool pool to check * @return number of bytes still available in @a pool */ size_t MHD_pool_get_free (struct MemoryPool *pool); /** * Deallocate a block of memory obtained from the pool. * * If the given block is not the most recently * (re)allocated block, the memory of the this block * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param block the allocated block, the NULL is tolerated * @param block_size the size of the allocated block */ void MHD_pool_deallocate (struct MemoryPool *pool, void *block, size_t block_size); /** * Clear all entries from the memory pool except * for @a keep of the given @a copy_bytes. The pointer * returned should be a buffer of @a new_size where * the first @a copy_bytes are from @a keep. * * @param pool memory pool to use for the operation * @param keep pointer to the entry to keep (maybe NULL) * @param copy_bytes how many bytes need to be kept at this address * @param new_size how many bytes should the allocation we return have? * (should be larger or equal to @a copy_bytes) * @return addr new address of @a keep (if it had to change) */ void * MHD_pool_reset (struct MemoryPool *pool, void *keep, size_t copy_bytes, size_t new_size); #endif libmicrohttpd-1.0.2/src/microhttpd/postprocessor.h0000644000175000017500000001205514760713577017365 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007-2022 Daniel Pittman, Christian Grothoff, and Evgeny Grin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file postprocessor.h * @brief Declarations for parsing POST data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_POSTPROCESSOR_H #define MHD_POSTPROCESSOR_H 1 #include "internal.h" /** * States in the PP parser's state machine. */ enum PP_State { /* general states */ PP_Error, PP_Done, PP_Init, PP_NextBoundary, /* url encoding-states */ PP_ProcessKey, PP_ProcessValue, PP_Callback, /* post encoding-states */ PP_ProcessEntryHeaders, PP_PerformCheckMultipart, PP_ProcessValueToBoundary, PP_PerformCleanup, /* nested post-encoding states */ PP_Nested_Init, PP_Nested_PerformMarking, PP_Nested_ProcessEntryHeaders, PP_Nested_ProcessValueToBoundary, PP_Nested_PerformCleanup }; enum RN_State { /** * No RN-preprocessing in this state. */ RN_Inactive = 0, /** * If the next character is CR, skip it. Otherwise, * just go inactive. */ RN_OptN = 1, /** * Expect CRLF (and only CRLF). As always, we also * expect only LF or only CR. */ RN_Full = 2, /** * Expect either CRLF or '--'CRLF. If '--'CRLF, transition into dash-state * for the main state machine */ RN_Dash = 3, /** * Got a single dash, expect second dash. */ RN_Dash2 = 4 }; /** * Bits for the globally known fields that * should not be deleted when we exit the * nested state. */ enum NE_State { NE_none = 0, NE_content_name = 1, NE_content_type = 2, NE_content_filename = 4, NE_content_transfer_encoding = 8 }; /** * Internal state of the post-processor. Note that the fields * are sorted by type to enable optimal packing by the compiler. */ struct MHD_PostProcessor { /** * The connection for which we are doing * POST processing. */ struct MHD_Connection *connection; /** * Function to call with POST data. */ MHD_PostDataIterator ikvi; /** * Extra argument to ikvi. */ void *cls; /** * Encoding as given by the headers of the connection. */ const char *encoding; /** * Primary boundary (points into encoding string) */ const char *boundary; /** * Nested boundary (if we have multipart/mixed encoding). */ char *nested_boundary; /** * Pointer to the name given in disposition. */ char *content_name; /** * Pointer to the (current) content type. */ char *content_type; /** * Pointer to the (current) filename. */ char *content_filename; /** * Pointer to the (current) encoding. */ char *content_transfer_encoding; /** * Value data left over from previous iteration. */ char xbuf[2]; /** * Size of our buffer for the key. */ size_t buffer_size; /** * Current position in the key buffer. */ size_t buffer_pos; /** * Current position in @e xbuf. */ size_t xbuf_pos; /** * Current offset in the value being processed. */ uint64_t value_offset; /** * strlen(boundary) -- if boundary != NULL. */ size_t blen; /** * strlen(nested_boundary) -- if nested_boundary != NULL. */ size_t nlen; /** * Do we have to call the 'ikvi' callback when processing the * multipart post body even if the size of the payload is zero? * Set to #MHD_YES whenever we parse a new multiparty entry header, * and to #MHD_NO the first time we call the 'ikvi' callback. * Used to ensure that we do always call 'ikvi' even if the * payload is empty (but not more than once). */ bool must_ikvi; /** * Set if we still need to run the unescape logic * on the key allocated at the end of this struct. */ bool must_unescape_key; /** * State of the parser. */ enum PP_State state; /** * Side-state-machine: skip CRLF (or just LF). * Set to 0 if we are not in skip mode. Set to 2 * if a CRLF is expected, set to 1 if a CR should * be skipped if it is the next character. */ enum RN_State skip_rn; /** * If we are in skip_rn with "dash" mode and * do find 2 dashes, what state do we go into? */ enum PP_State dash_state; /** * Which headers are global? (used to tell which * headers were only valid for the nested multipart). */ enum NE_State have; }; #endif /* ! MHD_POSTPROCESSOR_H */ libmicrohttpd-1.0.2/src/microhttpd/test_set_panic.c0000644000175000017500000014113114760713574017432 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_set_panic.c * @brief Testcase for MHD_set_panic_func() * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_SYSCTL #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SYSCTL_H #include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #ifdef HAVE_NETINET_IP_ICMP_H #include #endif /* HAVE_NETINET_IP_ICMP_H */ #ifdef HAVE_NETINET_ICMP_VAR_H #include #endif /* HAVE_NETINET_ICMP_VAR_H */ #endif /* HAVE_SYSCTL */ #include #include "mhd_sockets.h" /* only macros used */ #include "test_helpers.h" #include "mhd_assert.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Time in ms to wait for final packets to be delivered */ #define FINAL_PACKETS_MS 20 #define EXPECTED_URI_BASE_PATH "/a" #define REQ_HOST "localhost" #define REQ_METHOD "PUT" #define REQ_BODY "Some content data." #define REQ_LINE_END "\r\n" /* Mandatory request headers */ #define REQ_HEADER_HOST_NAME "Host" #define REQ_HEADER_HOST_VALUE REQ_HOST #define REQ_HEADER_HOST \ REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END #define REQ_HEADER_UA_NAME "User-Agent" #define REQ_HEADER_UA_VALUE "dummyclient/0.9" #define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END /* Optional request headers */ #define REQ_HEADER_CT_NAME "Content-Type" #define REQ_HEADER_CT_VALUE "text/plain" #define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } #ifndef MHD_POSIX_SOCKETS /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) externalErrorExit (); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else externalErrorExitDesc ("No sleep function available on this system"); #endif } #endif /* ! MHD_POSIX_SOCKETS */ /* Global parameters */ static int verbose; /**< Be verbose */ static uint16_t global_port; /**< MHD daemons listen port number */ static void test_global_init (void) { if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) externalErrorExitDesc ("Error suppressing SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif } } static void test_global_cleanup (void) { } /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags & ~O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags | O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } enum _MHD_clientStage { DUMB_CLIENT_INIT = 0, DUMB_CLIENT_CONNECTING, DUMB_CLIENT_CONNECTED, DUMB_CLIENT_REQ_SENDING, DUMB_CLIENT_REQ_SENT, DUMB_CLIENT_HEADER_RECVEIVING, DUMB_CLIENT_HEADER_RECVEIVED, DUMB_CLIENT_BODY_RECVEIVING, DUMB_CLIENT_BODY_RECVEIVED, DUMB_CLIENT_FINISHING, DUMB_CLIENT_FINISHED }; struct _MHD_dumbClient { MHD_socket sckt; /**< the socket to communicate */ int sckt_nonblock; /**< non-zero if socket is non-blocking */ uint16_t port; /**< the port to connect to */ char *send_buf; /**< the buffer for the request, malloced */ size_t req_size; /**< the size of the request, including header */ size_t send_off; /**< the number of bytes already sent */ enum _MHD_clientStage stage; /* the test-specific variables */ size_t single_send_size; /**< the maximum number of bytes to be sent by single send() */ size_t send_size_limit; /**< the total number of send bytes limit */ }; struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked); void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send); void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt); void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es); /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es); /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt); /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt); struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked) { struct _MHD_dumbClient *clnt; size_t method_size; size_t url_size; size_t add_hdrs_size; size_t buf_alloc_size; char *send_buf; mhd_assert (0 != port); mhd_assert (NULL != req_body || 0 == req_body_size); mhd_assert (0 == req_body_size || NULL != req_body); clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient)); if (NULL == clnt) externalErrorExit (); memset (clnt, 0, sizeof(struct _MHD_dumbClient)); clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == clnt->sckt) externalErrorExitDesc ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (clnt->sckt)) externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ clnt->sckt_nonblock = 0; if (clnt->sckt_nonblock) make_nonblocking (clnt->sckt); else make_blocking (clnt->sckt); if (1) { /* Always set TCP NODELAY */ const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) externalErrorExitDesc ("Cannot set TCP_NODELAY option"); } clnt->port = port; if (NULL != method) method_size = strlen (method); else { method = MHD_HTTP_METHOD_GET; method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET); } mhd_assert (0 != method_size); if (NULL != url) url_size = strlen (url); else { url = "/"; url_size = 1; } mhd_assert (0 != url_size); add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers); buf_alloc_size = 1024 + method_size + url_size + add_hdrs_size + req_body_size; send_buf = (char *) malloc (buf_alloc_size); if (NULL == send_buf) externalErrorExit (); clnt->req_size = 0; /* Form the request line */ memcpy (send_buf + clnt->req_size, method, method_size); clnt->req_size += method_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, url, url_size); clnt->req_size += url_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1, MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1); send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Form the header */ memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST, MHD_STATICSTR_LEN_ (REQ_HEADER_HOST)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST); memcpy (send_buf + clnt->req_size, REQ_HEADER_UA, MHD_STATICSTR_LEN_ (REQ_HEADER_UA)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA); if ((NULL != req_body) || chunked) { if (! chunked) { int prn_size; memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%u", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } else { memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n"); } } if (0 != add_hdrs_size) { memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size); clnt->req_size += add_hdrs_size; } /* Terminate header */ send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Add body (if any) */ if (! chunked) { if (0 != req_body_size) { memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; } } else { if (0 != req_body_size) { int prn_size; prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%x", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } send_buf[clnt->req_size++] = '0'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } mhd_assert (clnt->req_size < buf_alloc_size); clnt->send_buf = send_buf; return clnt; } void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send) { clnt->single_send_size = step_size; clnt->send_size_limit = max_total_send; } /* internal */ static void _MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt) { struct sockaddr_in sa; mhd_assert (DUMB_CLIENT_INIT == clnt->stage); sa.sin_family = AF_INET; sa.sin_port = htons (clnt->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa))) { const int err = MHD_socket_get_error_ (); if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) || (MHD_SCKT_ERR_IS_EAGAIN_ (err))) clnt->stage = DUMB_CLIENT_CONNECTING; else externalErrorExitDesc ("Cannot 'connect()' the client socket"); } else clnt->stage = DUMB_CLIENT_CONNECTED; } void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt) { mhd_assert (DUMB_CLIENT_INIT == clnt->stage); _MHD_dumbClient_connect_init (clnt); } /* internal */ static void _MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt) { int err = 0; socklen_t err_size = sizeof(err); mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage); if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR, (void *) &err, &err_size)) externalErrorExitDesc ("'getsockopt()' call failed"); if (0 != err) externalErrorExitDesc ("Socket connect() failed"); clnt->stage = DUMB_CLIENT_CONNECTED; } /* internal */ static void _MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt) { size_t send_size; ssize_t res; mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage); mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage); mhd_assert (clnt->req_size > clnt->send_off); send_size = (((0 != clnt->send_size_limit) && (clnt->req_size > clnt->send_size_limit)) ? clnt->send_size_limit : clnt->req_size) - clnt->send_off; mhd_assert (0 != send_size); if ((0 != clnt->single_send_size) && (clnt->single_send_size < send_size)) send_size = clnt->single_send_size; res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size); if (res < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) return; if (MHD_SCKT_ERR_IS_EINTR_ (err)) return; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("The connection was aborted by MHD"); if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) mhdErrorExitDesc ("The connection was shut down on MHD side"); externalErrorExitDesc ("Unexpected network error"); } clnt->send_off += (size_t) res; mhd_assert (clnt->send_off <= clnt->req_size); mhd_assert (clnt->send_off <= clnt->send_size_limit || \ 0 == clnt->send_size_limit); if (clnt->req_size == clnt->send_off) clnt->stage = DUMB_CLIENT_REQ_SENT; if ((0 != clnt->send_size_limit) && (clnt->send_size_limit == clnt->send_off)) clnt->stage = DUMB_CLIENT_FINISHING; } /* internal */ _MHD_NORETURN /* not implemented */ static void _MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt) { (void) clnt; externalErrorExitDesc ("Not implemented for this test"); } int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt) { return DUMB_CLIENT_REQ_SENT <= clnt->stage; } /* internal */ static void _MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (! MHD_socket_close_ (clnt->sckt)) externalErrorExitDesc ("Unexpected error while closing " \ "the client socket"); clnt->sckt = MHD_INVALID_SOCKET; } } /* internal */ static void _MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (0 != shutdown (clnt->sckt, SHUT_WR)) { const int err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) && ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("Unexpected error when shutting down " \ "the client socket"); } } clnt->stage = DUMB_CLIENT_FINISHED; } /* internal */ static int _MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt) { return ((DUMB_CLIENT_CONNECTING <= clnt->stage) && (DUMB_CLIENT_REQ_SENT > clnt->stage)) || (DUMB_CLIENT_FINISHING == clnt->stage); } /* internal */ static int _MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt) { return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) && (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage); } /* internal */ /** * Check whether the client needs unconditionally process the data. * @param clnt the client to check * @return non-zero if client needs unconditionally process the data, * zero otherwise. */ static int _MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt) { switch (clnt->stage) { case DUMB_CLIENT_INIT: case DUMB_CLIENT_REQ_SENT: case DUMB_CLIENT_HEADER_RECVEIVED: case DUMB_CLIENT_BODY_RECVEIVED: case DUMB_CLIENT_FINISHED: return ! 0; case DUMB_CLIENT_CONNECTING: case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: case DUMB_CLIENT_HEADER_RECVEIVING: case DUMB_CLIENT_BODY_RECVEIVING: case DUMB_CLIENT_FINISHING: default: return 0; } return 0; /* Should be unreachable */ } /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt) { do { switch (clnt->stage) { case DUMB_CLIENT_INIT: _MHD_dumbClient_connect_init (clnt); break; case DUMB_CLIENT_CONNECTING: _MHD_dumbClient_connect_finish (clnt); break; case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: _MHD_dumbClient_send_req (clnt); break; case DUMB_CLIENT_REQ_SENT: mhd_assert (0); clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING; break; case DUMB_CLIENT_HEADER_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_HEADER_RECVEIVED: clnt->stage = DUMB_CLIENT_BODY_RECVEIVING; break; case DUMB_CLIENT_BODY_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_BODY_RECVEIVED: clnt->stage = DUMB_CLIENT_FINISHING; break; case DUMB_CLIENT_FINISHING: _MHD_dumbClient_finalize (clnt); break; case DUMB_CLIENT_FINISHED: return ! 0; default: mhd_assert (0); mhdErrorExit (); } } while (_MHD_dumbClient_needs_process (clnt)); return DUMB_CLIENT_FINISHED == clnt->stage; } void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es) { mhd_assert (NULL != rs); mhd_assert (NULL != ws); mhd_assert (NULL != es); if (DUMB_CLIENT_FINISHED > clnt->stage) { if (MHD_INVALID_SOCKET != clnt->sckt) { if ( (MHD_INVALID_SOCKET == *maxsckt) || (clnt->sckt > *maxsckt) ) *maxsckt = clnt->sckt; if (_MHD_dumbClient_needs_recv (clnt)) FD_SET (clnt->sckt, rs); if (_MHD_dumbClient_needs_send (clnt)) FD_SET (clnt->sckt, ws); FD_SET (clnt->sckt, es); } } } /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es) { if (_MHD_dumbClient_needs_process (clnt)) return _MHD_dumbClient_process (clnt); else if (MHD_INVALID_SOCKET != clnt->sckt) { if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs)) return _MHD_dumbClient_process (clnt); else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws)) return _MHD_dumbClient_process (clnt); else if (FD_ISSET (clnt->sckt, es)) return _MHD_dumbClient_process (clnt); } return DUMB_CLIENT_FINISHED == clnt->stage; } /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt) { time_t start; time_t now; start = time (NULL); now = start; do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; struct timeval tv; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! _MHD_dumbClient_needs_process (clnt)) { maxMhdSk = MHD_INVALID_SOCKET; _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); mhd_assert (now >= start); #ifndef _WIN32 tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1); #else tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1); #endif tv.tv_usec = 250 * 1000; if (-1 == select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else /* ! MHD_POSIX_SOCKETS */ mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \ (0 != es.fd_count)); externalErrorExitDesc ("Unexpected select() error"); _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif /* ! MHD_POSIX_SOCKETS */ continue; } if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) return 0; } /* Use double timeout value here as MHD must catch timeout situations * in this test. Timeout in client as a last resort. */ } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2)); return 1; } /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt) { if (DUMB_CLIENT_FINISHED != clnt->stage) _MHD_dumbClient_finalize (clnt); _MHD_dumbClient_socket_close (clnt); if (NULL != clnt->send_buf) { free ((void *) clnt->send_buf); clnt->send_buf = NULL; } free (clnt); } _MHD_NORETURN static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { (void) cls; /* Unused */ (void) socket_context; /* Unused */ (void) toe; /* Unused */ MHD_suspend_connection (c); /* Should trigger panic */ mhdErrorExitDesc ("Function \"MHD_suspend_connection()\" succeed, while " \ "it must fail as daemon was started without MHD_ALLOW_SUSPEND_RESUME " \ "flag"); } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; const char *volatile rq_method; const char *volatile rq_url; const char *volatile req_body; volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */ size_t req_body_size; /**< The number of bytes in @a req_body */ size_t req_body_uploaded; /* Updated by callback */ }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; (void) connection; /* Unused */ if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); param->cb_called++; if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) { const char *const upload_body = param->req_body; if (NULL == upload_data) mhdErrorExitDesc ("'upload_data' is NULL while " \ "'*upload_data_size' value is not zero"); if (NULL == upload_body) mhdErrorExitDesc ("'*upload_data_size' value is not zero " \ "while no request body is expected"); if (param->req_body_uploaded + *upload_data_size > param->req_body_size) { fprintf (stderr, "Too large upload body received. Got %u, expected %u", (unsigned int) (param->req_body_uploaded + *upload_data_size), (unsigned int) param->req_body_size); mhdErrorExit (); } if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded, *upload_data_size)) { fprintf (stderr, "Unexpected request body at offset %u: " \ "'%.*s', expected: '%.*s'\n", (unsigned int) param->req_body_uploaded, (int) *upload_data_size, upload_data, (int) *upload_data_size, upload_body + param->req_body_uploaded); mhdErrorExit (); } param->req_body_uploaded += *upload_data_size; *upload_data_size = 0; } if (&marker != *req_cls) { /* The first call of the callback for this connection */ mhd_assert (NULL == upload_data); param->req_body_uploaded = 0; *req_cls = ▮ return MHD_YES; } if (NULL != upload_data) return MHD_YES; /* Full request has not been received so far */ #if 0 /* Code unused in this test */ struct MHD_Response *response; response = MHD_create_response_from_buffer (param->rp_data_size, (void *) param->rp_data, MHD_RESPMEM_MUST_COPY); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); #else if (NULL == upload_data) mhdErrorExitDesc ("Full request received, " \ "while incomplete request expected"); ret = MHD_NO; #endif return ret; } struct simpleQueryParams { /* Destination path for HTTP query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for HTTP query */ uint16_t queryPort; /* Additional request headers, static */ const char *headers; /* NULL for request without body */ const uint8_t *req_body; size_t req_body_size; /* Non-zero to use chunked encoding for request body */ int chunked; /* HTTP query result error flag */ volatile int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* returns non-zero if timed-out */ static int performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt) { time_t start; struct timeval tv; int ret; const union MHD_DaemonInfo *di; MHD_socket lstn_sk; int client_accepted; int full_req_recieved; int full_req_sent; int some_data_recieved; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (NULL == di) mhdErrorExitDesc ("Cannot get listener socket"); lstn_sk = di->listen_fd; ret = 1; /* will be replaced with real result */ client_accepted = 0; _MHD_dumbClient_start_connect (clnt); full_req_recieved = 0; some_data_recieved = 0; start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int num_ready; int do_client; /**< Process data in client */ maxMhdSk = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL == clnt) { /* client has finished, check whether MHD is still * processing any connections */ full_req_sent = 1; do_client = 0; if (client_accepted && (0 > MHD_get_timeout64s (d))) { ret = 0; break; /* MHD finished as well */ } } else { full_req_sent = _MHD_dumbClient_is_req_sent (clnt); if (! full_req_sent) do_client = 1; /* Request hasn't been sent yet, send the data */ else { /* All request data has been sent. * Client will close the socket as the next step. */ if (full_req_recieved) do_client = 1; /* All data has been received by the MHD */ else if (some_data_recieved) { /* at least something was received by the MHD */ do_client = 1; } else { /* The MHD must receive at least something before closing * the connection. */ do_client = 0; } } if (do_client) _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); if (do_client) { tv.tv_sec = 1; tv.tv_usec = 250 * 1000; } else { /* Request completely sent but not yet fully received */ tv.tv_sec = 0; tv.tv_usec = FINAL_PACKETS_MS * 1000; } num_ready = select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv); if (-1 == num_ready) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif continue; } if (0 == num_ready) { /* select() finished by timeout, looks like no more packets are pending */ if (do_client) externalErrorExitDesc ("Timeout waiting for sockets"); if (full_req_sent && (! full_req_recieved)) full_req_recieved = 1; } if (full_req_recieved) mhdErrorExitDesc ("Full request has been received by MHD, while it " "must be aborted by the panic function"); if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); if (! client_accepted) client_accepted = FD_ISSET (lstn_sk, &rs); else { /* Client connection was already accepted by MHD */ if (! some_data_recieved) { if (! do_client) { if (0 != num_ready) { /* Connection was accepted before, "ready" socket means data */ some_data_recieved = 1; } } else { if (2 == num_ready) some_data_recieved = 1; else if ((1 == num_ready) && ((MHD_INVALID_SOCKET == clnt->sckt) || ! FD_ISSET (clnt->sckt, &ws))) some_data_recieved = 1; } } } if (do_client) { if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) clnt = NULL; } /* Use double timeout value here so MHD would be able to catch timeout * internally */ } while (time (NULL) - start <= (TIMEOUTS_VAL * 2)); return ret; } /* Returns zero for successful response and non-zero for failed response */ static int doClientQueryInThread (struct MHD_Daemon *d, struct simpleQueryParams *p) { const union MHD_DaemonInfo *dinfo; struct _MHD_dumbClient *c; int errornum; int use_external_poll; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (0 == p->queryPort) externalErrorExit (); c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); _MHD_dumbClient_set_send_limits (c, 1, 0); /* 'internal' polling should not be used in this test */ mhd_assert (use_external_poll); if (! use_external_poll) errornum = _MHD_dumbClient_perform (c); else errornum = performQueryExternal (d, c); if (errornum) fprintf (stderr, "Request timeout out.\n"); else mhdErrorExitDesc ("Request succeed, but it must fail"); _MHD_dumbClient_close (c); return errornum; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param) { struct simpleQueryParams qParam; /* Common parameters, to be individually overridden by specific test cases * if needed */ qParam.queryPort = d_port; qParam.method = MHD_HTTP_METHOD_PUT; qParam.queryPath = EXPECTED_URI_BASE_PATH; qParam.headers = REQ_HEADER_CT; qParam.req_body = (const uint8_t *) REQ_BODY; qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY); qParam.chunked = 0; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = MHD_HTTP_METHOD_PUT; ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->req_body = (const char *) qParam.req_body; ahc_param->req_body_size = qParam.req_body_size; /* Make sure that maximum size is tested */ /* To be updated by callbacks */ ahc_param->cb_called = 0; if (0 != doClientQueryInThread (d, &qParam)) fprintf (stderr, "FAILED: client query failed."); MHD_stop_daemon (d); free (ahc_param); return 1; /* Always error if reached this point */ } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } #define PANIC_MAGIC_CHECK 1133 _MHD_NORETURN static void myPanicCallback (void *cls, const char *file, unsigned int line, const char *reason) { int *const param = (int *) cls; if (NULL == cls) mhdErrorExitDesc ("The 'cls' parameter is NULL"); if (PANIC_MAGIC_CHECK != *param) mhdErrorExitDesc ("Wrong '*cls' value"); #ifdef HAVE_MESSAGES if (NULL == file) mhdErrorExitDesc ("The 'file' parameter is NULL"); if (NULL == reason) mhdErrorExitDesc ("The 'reason' parameter is NULL"); #else /* ! HAVE_MESSAGES */ if (NULL != file) mhdErrorExitDesc ("The 'file' parameter is not NULL"); if (NULL != reason) mhdErrorExitDesc ("The 'reason' parameter is not NULL"); #endif /* ! HAVE_MESSAGES */ fflush (stderr); fflush (stdout); printf ("User panic function has been called from file '%s' at line '%u' " "with the reason:\n%s", file, line, ((NULL != reason) ? reason : "(NULL)\n")); fflush (stdout); exit (0); } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; static int magic_panic_param = PANIC_MAGIC_CHECK; if (NULL == ahc_param) externalErrorExit (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4190; } MHD_set_panic_func (&myPanicCallback, (void *) &magic_panic_param); if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); if (NULL == d) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param); return performTestQueries (d, d_port, ahc_param); } #if 0 /* disabled runners, not suitable for this test */ static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param, &term_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } #endif /* disabled runners, not suitable for this test */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; (void) has_in_name; /* Unused, mute compiler warning */ if ((NULL == argv) || (0 == argv[0])) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; #if 0 /* disabled runners, not suitable for this test */ if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } #endif /* disabled runners, not suitable for this test */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.2/src/microhttpd/test_helpers.h0000644000175000017500000000545414760713577017146 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_helpers.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ static int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } /** * Check whether one of strings in array is equal to @a param. * String @a argv[0] is ignored. * @param argc number of strings in @a argv, as passed to main function * @param argv array of strings, as passed to main function * @param param parameter to look for. * @return zero if @a argv is NULL, @a param is NULL or empty string, * @a argc is less then 2 or @a param is not found in @a argv, * non-zero if one of strings in @a argv is equal to @a param. */ static int has_param (int argc, char *const argv[], const char *param) { int i; if (! argv || ! param || ! param[0]) return 0; for (i = 1; i < argc; i++) { if (argv[i] && (strcmp (argv[i], param) == 0) ) return ! 0; } return 0; } libmicrohttpd-1.0.2/src/microhttpd/reason_phrase.c0000644000175000017500000002352614760713574017266 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007, 2011, 2017, 2019 Christian Grothoff Copyright (C) 2017-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file reason_phrase.c * @brief Tables of the string response phrases * @author Elliot Glaysher * @author Christian Grothoff (minor code clean up) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "mhd_str.h" #ifndef NULL #define NULL ((void*) 0) #endif static const struct _MHD_cstr_w_len invalid_hundred[] = { { NULL, 0 } }; static const struct _MHD_cstr_w_len one_hundred[] = { /* 100 */ _MHD_S_STR_W_LEN ("Continue"), /* RFC9110, Section 15.2.1 */ /* 101 */ _MHD_S_STR_W_LEN ("Switching Protocols"), /* RFC9110, Section 15.2.2 */ /* 102 */ _MHD_S_STR_W_LEN ("Processing"), /* RFC2518 */ /* 103 */ _MHD_S_STR_W_LEN ("Early Hints") /* RFC8297 */ }; static const struct _MHD_cstr_w_len two_hundred[] = { /* 200 */ _MHD_S_STR_W_LEN ("OK"), /* RFC9110, Section 15.3.1 */ /* 201 */ _MHD_S_STR_W_LEN ("Created"), /* RFC9110, Section 15.3.2 */ /* 202 */ _MHD_S_STR_W_LEN ("Accepted"), /* RFC9110, Section 15.3.3 */ /* 203 */ _MHD_S_STR_W_LEN ("Non-Authoritative Information"), /* RFC9110, Section 15.3.4 */ /* 204 */ _MHD_S_STR_W_LEN ("No Content"), /* RFC9110, Section 15.3.5 */ /* 205 */ _MHD_S_STR_W_LEN ("Reset Content"), /* RFC9110, Section 15.3.6 */ /* 206 */ _MHD_S_STR_W_LEN ("Partial Content"), /* RFC9110, Section 15.3.7 */ /* 207 */ _MHD_S_STR_W_LEN ("Multi-Status"), /* RFC4918 */ /* 208 */ _MHD_S_STR_W_LEN ("Already Reported"), /* RFC5842 */ /* 209 */ {"Unknown", 0}, /* Not used */ /* 210 */ {"Unknown", 0}, /* Not used */ /* 211 */ {"Unknown", 0}, /* Not used */ /* 212 */ {"Unknown", 0}, /* Not used */ /* 213 */ {"Unknown", 0}, /* Not used */ /* 214 */ {"Unknown", 0}, /* Not used */ /* 215 */ {"Unknown", 0}, /* Not used */ /* 216 */ {"Unknown", 0}, /* Not used */ /* 217 */ {"Unknown", 0}, /* Not used */ /* 218 */ {"Unknown", 0}, /* Not used */ /* 219 */ {"Unknown", 0}, /* Not used */ /* 220 */ {"Unknown", 0}, /* Not used */ /* 221 */ {"Unknown", 0}, /* Not used */ /* 222 */ {"Unknown", 0}, /* Not used */ /* 223 */ {"Unknown", 0}, /* Not used */ /* 224 */ {"Unknown", 0}, /* Not used */ /* 225 */ {"Unknown", 0}, /* Not used */ /* 226 */ _MHD_S_STR_W_LEN ("IM Used") /* RFC3229 */ }; static const struct _MHD_cstr_w_len three_hundred[] = { /* 300 */ _MHD_S_STR_W_LEN ("Multiple Choices"), /* RFC9110, Section 15.4.1 */ /* 301 */ _MHD_S_STR_W_LEN ("Moved Permanently"), /* RFC9110, Section 15.4.2 */ /* 302 */ _MHD_S_STR_W_LEN ("Found"), /* RFC9110, Section 15.4.3 */ /* 303 */ _MHD_S_STR_W_LEN ("See Other"), /* RFC9110, Section 15.4.4 */ /* 304 */ _MHD_S_STR_W_LEN ("Not Modified"), /* RFC9110, Section 15.4.5 */ /* 305 */ _MHD_S_STR_W_LEN ("Use Proxy"), /* RFC9110, Section 15.4.6 */ /* 306 */ _MHD_S_STR_W_LEN ("Switch Proxy"), /* Not used! RFC9110, Section 15.4.7 */ /* 307 */ _MHD_S_STR_W_LEN ("Temporary Redirect"), /* RFC9110, Section 15.4.8 */ /* 308 */ _MHD_S_STR_W_LEN ("Permanent Redirect") /* RFC9110, Section 15.4.9 */ }; static const struct _MHD_cstr_w_len four_hundred[] = { /* 400 */ _MHD_S_STR_W_LEN ("Bad Request"), /* RFC9110, Section 15.5.1 */ /* 401 */ _MHD_S_STR_W_LEN ("Unauthorized"), /* RFC9110, Section 15.5.2 */ /* 402 */ _MHD_S_STR_W_LEN ("Payment Required"), /* RFC9110, Section 15.5.3 */ /* 403 */ _MHD_S_STR_W_LEN ("Forbidden"), /* RFC9110, Section 15.5.4 */ /* 404 */ _MHD_S_STR_W_LEN ("Not Found"), /* RFC9110, Section 15.5.5 */ /* 405 */ _MHD_S_STR_W_LEN ("Method Not Allowed"), /* RFC9110, Section 15.5.6 */ /* 406 */ _MHD_S_STR_W_LEN ("Not Acceptable"), /* RFC9110, Section 15.5.7 */ /* 407 */ _MHD_S_STR_W_LEN ("Proxy Authentication Required"), /* RFC9110, Section 15.5.8 */ /* 408 */ _MHD_S_STR_W_LEN ("Request Timeout"), /* RFC9110, Section 15.5.9 */ /* 409 */ _MHD_S_STR_W_LEN ("Conflict"), /* RFC9110, Section 15.5.10 */ /* 410 */ _MHD_S_STR_W_LEN ("Gone"), /* RFC9110, Section 15.5.11 */ /* 411 */ _MHD_S_STR_W_LEN ("Length Required"), /* RFC9110, Section 15.5.12 */ /* 412 */ _MHD_S_STR_W_LEN ("Precondition Failed"), /* RFC9110, Section 15.5.13 */ /* 413 */ _MHD_S_STR_W_LEN ("Content Too Large"), /* RFC9110, Section 15.5.14 */ /* 414 */ _MHD_S_STR_W_LEN ("URI Too Long"), /* RFC9110, Section 15.5.15 */ /* 415 */ _MHD_S_STR_W_LEN ("Unsupported Media Type"), /* RFC9110, Section 15.5.16 */ /* 416 */ _MHD_S_STR_W_LEN ("Range Not Satisfiable"), /* RFC9110, Section 15.5.17 */ /* 417 */ _MHD_S_STR_W_LEN ("Expectation Failed"), /* RFC9110, Section 15.5.18 */ /* 418 */ {"Unknown", 0}, /* Not used */ /* 419 */ {"Unknown", 0}, /* Not used */ /* 420 */ {"Unknown", 0}, /* Not used */ /* 421 */ _MHD_S_STR_W_LEN ("Misdirected Request"), /* RFC9110, Section 15.5.20 */ /* 422 */ _MHD_S_STR_W_LEN ("Unprocessable Content"), /* RFC9110, Section 15.5.21 */ /* 423 */ _MHD_S_STR_W_LEN ("Locked"), /* RFC4918 */ /* 424 */ _MHD_S_STR_W_LEN ("Failed Dependency"), /* RFC4918 */ /* 425 */ _MHD_S_STR_W_LEN ("Too Early"), /* RFC8470 */ /* 426 */ _MHD_S_STR_W_LEN ("Upgrade Required"), /* RFC9110, Section 15.5.22 */ /* 427 */ {"Unknown", 0}, /* Not used */ /* 428 */ _MHD_S_STR_W_LEN ("Precondition Required"), /* RFC6585 */ /* 429 */ _MHD_S_STR_W_LEN ("Too Many Requests"), /* RFC6585 */ /* 430 */ {"Unknown", 0}, /* Not used */ /* 431 */ _MHD_S_STR_W_LEN ("Request Header Fields Too Large"), /* RFC6585 */ /* 432 */ {"Unknown", 0}, /* Not used */ /* 433 */ {"Unknown", 0}, /* Not used */ /* 434 */ {"Unknown", 0}, /* Not used */ /* 435 */ {"Unknown", 0}, /* Not used */ /* 436 */ {"Unknown", 0}, /* Not used */ /* 437 */ {"Unknown", 0}, /* Not used */ /* 438 */ {"Unknown", 0}, /* Not used */ /* 439 */ {"Unknown", 0}, /* Not used */ /* 440 */ {"Unknown", 0}, /* Not used */ /* 441 */ {"Unknown", 0}, /* Not used */ /* 442 */ {"Unknown", 0}, /* Not used */ /* 443 */ {"Unknown", 0}, /* Not used */ /* 444 */ {"Unknown", 0}, /* Not used */ /* 445 */ {"Unknown", 0}, /* Not used */ /* 446 */ {"Unknown", 0}, /* Not used */ /* 447 */ {"Unknown", 0}, /* Not used */ /* 448 */ {"Unknown", 0}, /* Not used */ /* 449 */ _MHD_S_STR_W_LEN ("Reply With"), /* MS IIS extension */ /* 450 */ _MHD_S_STR_W_LEN ("Blocked by Windows Parental Controls"), /* MS extension */ /* 451 */ _MHD_S_STR_W_LEN ("Unavailable For Legal Reasons") /* RFC7725 */ }; static const struct _MHD_cstr_w_len five_hundred[] = { /* 500 */ _MHD_S_STR_W_LEN ("Internal Server Error"), /* RFC9110, Section 15.6.1 */ /* 501 */ _MHD_S_STR_W_LEN ("Not Implemented"), /* RFC9110, Section 15.6.2 */ /* 502 */ _MHD_S_STR_W_LEN ("Bad Gateway"), /* RFC9110, Section 15.6.3 */ /* 503 */ _MHD_S_STR_W_LEN ("Service Unavailable"), /* RFC9110, Section 15.6.4 */ /* 504 */ _MHD_S_STR_W_LEN ("Gateway Timeout"), /* RFC9110, Section 15.6.5 */ /* 505 */ _MHD_S_STR_W_LEN ("HTTP Version Not Supported"), /* RFC9110, Section 15.6.6 */ /* 506 */ _MHD_S_STR_W_LEN ("Variant Also Negotiates"), /* RFC2295 */ /* 507 */ _MHD_S_STR_W_LEN ("Insufficient Storage"), /* RFC4918 */ /* 508 */ _MHD_S_STR_W_LEN ("Loop Detected"), /* RFC5842 */ /* 509 */ _MHD_S_STR_W_LEN ("Bandwidth Limit Exceeded"), /* Apache extension */ /* 510 */ _MHD_S_STR_W_LEN ("Not Extended"), /* (OBSOLETED) RFC2774; status-change-http-experiments-to-historic */ /* 511 */ _MHD_S_STR_W_LEN ("Network Authentication Required") /* RFC6585 */ }; struct MHD_Reason_Block { size_t max; const struct _MHD_cstr_w_len *const data; }; #define BLOCK(m) { (sizeof(m) / sizeof(m[0])), m } static const struct MHD_Reason_Block reasons[] = { BLOCK (invalid_hundred), BLOCK (one_hundred), BLOCK (two_hundred), BLOCK (three_hundred), BLOCK (four_hundred), BLOCK (five_hundred), }; _MHD_EXTERN const char * MHD_get_reason_phrase_for (unsigned int code) { if ( (code >= 100) && (code < 600) && (reasons[code / 100].max > (code % 100)) ) return reasons[code / 100].data[code % 100].str; return "Unknown"; } _MHD_EXTERN size_t MHD_get_reason_phrase_len_for (unsigned int code) { if ( (code >= 100) && (code < 600) && (reasons[code / 100].max > (code % 100)) ) return reasons[code / 100].data[code % 100].len; return 0; } libmicrohttpd-1.0.2/src/microhttpd/memorypool.c0000644000175000017500000006057515035214301016620 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2007--2024 Daniel Pittman and Christian Grothoff Copyright (C) 2014--2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file memorypool.c * @brief memory pool * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "memorypool.h" #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include #include #include "mhd_assert.h" #ifdef HAVE_SYS_MMAN_H #include #endif #ifdef _WIN32 #include #endif #ifdef HAVE_SYSCONF #include #if defined(_SC_PAGE_SIZE) #define MHD_SC_PAGESIZE _SC_PAGE_SIZE #elif defined(_SC_PAGESIZE) #define MHD_SC_PAGESIZE _SC_PAGESIZE #endif /* _SC_PAGESIZE */ #endif /* HAVE_SYSCONF */ #include "mhd_limits.h" /* for SIZE_MAX, PAGESIZE / PAGE_SIZE */ #if defined(MHD_USE_PAGESIZE_MACRO) || defined(MHD_USE_PAGE_SIZE_MACRO) #ifndef HAVE_SYSCONF /* Avoid duplicate include */ #include #endif /* HAVE_SYSCONF */ #ifdef HAVE_SYS_PARAM_H #include #endif /* HAVE_SYS_PARAM_H */ #endif /* MHD_USE_PAGESIZE_MACRO || MHD_USE_PAGE_SIZE_MACRO */ /** * Fallback value of page size */ #define _MHD_FALLBACK_PAGE_SIZE (4096) #if defined(MHD_USE_PAGESIZE_MACRO) #define MHD_DEF_PAGE_SIZE_ PAGESIZE #elif defined(MHD_USE_PAGE_SIZE_MACRO) #define MHD_DEF_PAGE_SIZE_ PAGE_SIZE #else /* ! PAGESIZE */ #define MHD_DEF_PAGE_SIZE_ _MHD_FALLBACK_PAGE_SIZE #endif /* ! PAGESIZE */ #ifdef MHD_ASAN_POISON_ACTIVE #include #endif /* MHD_ASAN_POISON_ACTIVE */ /* define MAP_ANONYMOUS for Mac OS X */ #if defined(MAP_ANON) && ! defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif #if defined(_WIN32) #define MAP_FAILED NULL #elif ! defined(MAP_FAILED) #define MAP_FAILED ((void*) -1) #endif /** * Align to 2x word size (as GNU libc does). */ #define ALIGN_SIZE (2 * sizeof(void*)) /** * Round up 'n' to a multiple of ALIGN_SIZE. */ #define ROUND_TO_ALIGN(n) (((n) + (ALIGN_SIZE - 1)) \ / (ALIGN_SIZE) *(ALIGN_SIZE)) #ifndef MHD_ASAN_POISON_ACTIVE #define _MHD_NOSANITIZE_PTRS /**/ #define _MHD_RED_ZONE_SIZE (0) #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) ROUND_TO_ALIGN(n) #define _MHD_POISON_MEMORY(pointer, size) (void)0 #define _MHD_UNPOISON_MEMORY(pointer, size) (void)0 /** * Boolean 'true' if the first pointer is less or equal the second pointer */ #define mp_ptr_le_(p1,p2) \ (((const uint8_t*)(p1)) <= ((const uint8_t*)(p2))) /** * The difference in bytes between positions of the first and * the second pointers */ #define mp_ptr_diff_(p1,p2) \ ((size_t)(((const uint8_t*)(p1)) - ((const uint8_t*)(p2)))) #else /* MHD_ASAN_POISON_ACTIVE */ #define _MHD_RED_ZONE_SIZE (ALIGN_SIZE) #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) (ROUND_TO_ALIGN(n) + _MHD_RED_ZONE_SIZE) #define _MHD_POISON_MEMORY(pointer, size) \ ASAN_POISON_MEMORY_REGION ((pointer), (size)) #define _MHD_UNPOISON_MEMORY(pointer, size) \ ASAN_UNPOISON_MEMORY_REGION ((pointer), (size)) #if defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS) /** * Boolean 'true' if the first pointer is less or equal the second pointer */ #define mp_ptr_le_(p1,p2) \ (((uintptr_t)((const void*)(p1))) <= ((uintptr_t)((const void*)(p2)))) /** * The difference in bytes between positions of the first and * the second pointers */ #define mp_ptr_diff_(p1,p2) \ ((size_t)(((uintptr_t)((const uint8_t*)(p1))) - \ ((uintptr_t)((const uint8_t*)(p2))))) #elif defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \ defined(FUNC_ATTR_PTRSUBTRACT_WORKS) #ifdef _DEBUG /** * Boolean 'true' if the first pointer is less or equal the second pointer */ __attribute__((no_sanitize ("pointer-compare"))) static bool mp_ptr_le_ (const void *p1, const void *p2) { return (((const uint8_t *) p1) <= ((const uint8_t *) p2)); } #endif /* _DEBUG */ /** * The difference in bytes between positions of the first and * the second pointers */ __attribute__((no_sanitize ("pointer-subtract"))) static size_t mp_ptr_diff_ (const void *p1, const void *p2) { return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2)); } #elif defined(FUNC_ATTR_NOSANITIZE_WORKS) #ifdef _DEBUG /** * Boolean 'true' if the first pointer is less or equal the second pointer */ __attribute__((no_sanitize ("address"))) static bool mp_ptr_le_ (const void *p1, const void *p2) { return (((const uint8_t *) p1) <= ((const uint8_t *) p2)); } #endif /* _DEBUG */ /** * The difference in bytes between positions of the first and * the second pointers */ __attribute__((no_sanitize ("address"))) static size_t mp_ptr_diff_ (const void *p1, const void *p2) { return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2)); } #else /* ! FUNC_ATTR_NOSANITIZE_WORKS */ #error User-poisoning cannot be used #endif /* ! FUNC_ATTR_NOSANITIZE_WORKS */ #endif /* MHD_ASAN_POISON_ACTIVE */ /** * Size of memory page */ static size_t MHD_sys_page_size_ = (size_t) #if defined(MHD_USE_PAGESIZE_MACRO_STATIC) PAGESIZE; #elif defined(MHD_USE_PAGE_SIZE_MACRO_STATIC) PAGE_SIZE; #else /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */ _MHD_FALLBACK_PAGE_SIZE; /* Default fallback value */ #endif /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */ /** * Initialise values for memory pools */ void MHD_init_mem_pools_ (void) { #ifdef MHD_SC_PAGESIZE long result; result = sysconf (MHD_SC_PAGESIZE); if (-1 != result) MHD_sys_page_size_ = (size_t) result; else MHD_sys_page_size_ = (size_t) MHD_DEF_PAGE_SIZE_; #elif defined(_WIN32) SYSTEM_INFO si; GetSystemInfo (&si); MHD_sys_page_size_ = (size_t) si.dwPageSize; #else MHD_sys_page_size_ = (size_t) MHD_DEF_PAGE_SIZE_; #endif /* _WIN32 */ mhd_assert (0 == (MHD_sys_page_size_ % ALIGN_SIZE)); } /** * Handle for a memory pool. Pools are not reentrant and must not be * used by multiple threads. */ struct MemoryPool { /** * Pointer to the pool's memory */ uint8_t *memory; /** * Size of the pool. */ size_t size; /** * Offset of the first unallocated byte. */ size_t pos; /** * Offset of the byte after the last unallocated byte. */ size_t end; /** * 'false' if pool was malloc'ed, 'true' if mmapped (VirtualAlloc'ed for W32). */ bool is_mmap; }; /** * Create a memory pool. * * @param max maximum size of the pool * @return NULL on error */ struct MemoryPool * MHD_pool_create (size_t max) { struct MemoryPool *pool; size_t alloc_size; mhd_assert (max > 0); alloc_size = 0; pool = malloc (sizeof (struct MemoryPool)); if (NULL == pool) return NULL; #if defined(MAP_ANONYMOUS) || defined(_WIN32) if ( (max <= 32 * 1024) || (max < MHD_sys_page_size_ * 4 / 3) ) { pool->memory = MAP_FAILED; } else { /* Round up allocation to page granularity. */ alloc_size = max + MHD_sys_page_size_ - 1; alloc_size -= alloc_size % MHD_sys_page_size_; #if defined(MAP_ANONYMOUS) && ! defined(_WIN32) pool->memory = mmap (NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #elif defined(_WIN32) pool->memory = VirtualAlloc (NULL, alloc_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #endif /* _WIN32 */ } #else /* ! _WIN32 && ! MAP_ANONYMOUS */ pool->memory = MAP_FAILED; #endif /* ! _WIN32 && ! MAP_ANONYMOUS */ if (MAP_FAILED == pool->memory) { alloc_size = ROUND_TO_ALIGN (max); pool->memory = malloc (alloc_size); if (NULL == pool->memory) { free (pool); return NULL; } pool->is_mmap = false; } #if defined(MAP_ANONYMOUS) || defined(_WIN32) else { pool->is_mmap = true; } #endif /* _WIN32 || MAP_ANONYMOUS */ mhd_assert (0 == (((uintptr_t) pool->memory) % ALIGN_SIZE)); pool->pos = 0; pool->end = alloc_size; pool->size = alloc_size; mhd_assert (0 < alloc_size); _MHD_POISON_MEMORY (pool->memory, pool->size); return pool; } /** * Destroy a memory pool. * * @param pool memory pool to destroy */ void MHD_pool_destroy (struct MemoryPool *pool) { if (NULL == pool) return; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); _MHD_UNPOISON_MEMORY (pool->memory, pool->size); if (! pool->is_mmap) free (pool->memory); else #if defined(MAP_ANONYMOUS) && ! defined(_WIN32) munmap (pool->memory, pool->size); #elif defined(_WIN32) VirtualFree (pool->memory, 0, MEM_RELEASE); #else abort (); #endif free (pool); } /** * Check how much memory is left in the @a pool * * @param pool pool to check * @return number of bytes still available in @a pool */ size_t MHD_pool_get_free (struct MemoryPool *pool) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); #ifdef MHD_ASAN_POISON_ACTIVE if ((pool->end - pool->pos) <= _MHD_RED_ZONE_SIZE) return 0; #endif /* MHD_ASAN_POISON_ACTIVE */ return (pool->end - pool->pos) - _MHD_RED_ZONE_SIZE; } /** * Allocate size bytes from the pool. * * @param pool memory pool to use for the operation * @param size number of bytes to allocate * @param from_end allocate from end of pool (set to 'true'); * use this for small, persistent allocations that * will never be reallocated * @return NULL if the pool cannot support size more * bytes */ void * MHD_pool_allocate (struct MemoryPool *pool, size_t size, bool from_end) { void *ret; size_t asize; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size); if ( (0 == asize) && (0 != size) ) return NULL; /* size too close to SIZE_MAX */ if (asize > pool->end - pool->pos) return NULL; if (from_end) { ret = &pool->memory[pool->end - asize]; pool->end -= asize; } else { ret = &pool->memory[pool->pos]; pool->pos += asize; } _MHD_UNPOISON_MEMORY (ret, size); return ret; } /** * Checks whether allocated block is re-sizable in-place. * If block is not re-sizable in-place, it still could be shrunk, but freed * memory will not be re-used until reset of the pool. * @param pool the memory pool to use * @param block the pointer to the allocated block to check * @param block_size the size of the allocated @a block * @return true if block can be resized in-place in the optimal way, * false otherwise */ bool MHD_pool_is_resizable_inplace (struct MemoryPool *pool, void *block, size_t block_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (block != NULL || block_size == 0); mhd_assert (pool->size >= block_size); if (NULL != block) { const size_t block_offset = mp_ptr_diff_ (block, pool->memory); mhd_assert (mp_ptr_le_ (pool->memory, block)); mhd_assert (pool->size >= block_offset); mhd_assert (pool->size >= block_offset + block_size); return (pool->pos == ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size)); } return false; /* Unallocated blocks cannot be resized in-place */ } /** * Try to allocate @a size bytes memory area from the @a pool. * * If allocation fails, @a required_bytes is updated with size required to be * freed in the @a pool from rellocatable area to allocate requested number * of bytes. * Allocated memory area is always not rellocatable ("from end"). * * @param pool memory pool to use for the operation * @param size the size of memory in bytes to allocate * @param[out] required_bytes the pointer to variable to be updated with * the size of the required additional free * memory area, set to 0 if function succeeds. * Cannot be NULL. * @return the pointer to allocated memory area if succeed, * NULL if the pool doesn't have enough space, required_bytes is updated * with amount of space needed to be freed in rellocatable area or * set to SIZE_MAX if requested size is too large for the pool. */ void * MHD_pool_try_alloc (struct MemoryPool *pool, size_t size, size_t *required_bytes) { void *ret; size_t asize; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size); if ( (0 == asize) && (0 != size) ) { /* size is too close to SIZE_MAX, very unlikely */ *required_bytes = SIZE_MAX; return NULL; } if (asize > pool->end - pool->pos) { mhd_assert ((pool->end - pool->pos) == \ ROUND_TO_ALIGN (pool->end - pool->pos)); if (asize <= pool->end) *required_bytes = asize - (pool->end - pool->pos); else *required_bytes = SIZE_MAX; return NULL; } *required_bytes = 0; ret = &pool->memory[pool->end - asize]; pool->end -= asize; _MHD_UNPOISON_MEMORY (ret, size); return ret; } /** * Reallocate a block of memory obtained from the pool. * This is particularly efficient when growing or * shrinking the block that was last (re)allocated. * If the given block is not the most recently * (re)allocated block, the memory of the previous * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param old the existing block * @param old_size the size of the existing block * @param new_size the new size of the block * @return new address of the block, or * NULL if the pool cannot support @a new_size * bytes (old continues to be valid for @a old_size) */ void * MHD_pool_reallocate (struct MemoryPool *pool, void *old, size_t old_size, size_t new_size) { size_t asize; uint8_t *new_blc; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (old != NULL || old_size == 0); mhd_assert (pool->size >= old_size); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); #if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED) mhd_assert (NULL == __asan_region_is_poisoned (old, old_size)); #endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */ if (NULL != old) { /* Have previously allocated data */ const size_t old_offset = mp_ptr_diff_ (old, pool->memory); const bool shrinking = (old_size > new_size); mhd_assert (mp_ptr_le_ (pool->memory, old)); /* (pool->memory + pool->size >= (uint8_t*) old + old_size) */ mhd_assert ((pool->size - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size)); /* Blocks "from the end" must not be reallocated */ /* (old_size == 0 || pool->memory + pool->pos > (uint8_t*) old) */ mhd_assert ((old_size == 0) || \ (pool->pos > old_offset)); mhd_assert ((old_size == 0) || \ ((pool->end - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size))); /* Try resizing in-place */ if (shrinking) { /* Shrinking in-place, zero-out freed part */ memset ((uint8_t *) old + new_size, 0, old_size - new_size); _MHD_POISON_MEMORY ((uint8_t *) old + new_size, old_size - new_size); } if (pool->pos == ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + old_size)) { /* "old" block is the last allocated block */ const size_t new_apos = ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + new_size); if (! shrinking) { /* Grow in-place, check for enough space. */ if ( (new_apos > pool->end) || (new_apos < pool->pos) ) /* Value wrap */ return NULL; /* No space */ } /* Resized in-place */ pool->pos = new_apos; _MHD_UNPOISON_MEMORY (old, new_size); return old; } if (shrinking) return old; /* Resized in-place, freed part remains allocated */ } /* Need to allocate new block */ asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size); if ( ( (0 == asize) && (0 != new_size) ) || /* Value wrap, too large new_size. */ (asize > pool->end - pool->pos) ) /* Not enough space */ return NULL; new_blc = pool->memory + pool->pos; pool->pos += asize; _MHD_UNPOISON_MEMORY (new_blc, new_size); if (0 != old_size) { /* Move data to new block, old block remains allocated */ memcpy (new_blc, old, old_size); /* Zero-out old block */ memset (old, 0, old_size); _MHD_POISON_MEMORY (old, old_size); } return new_blc; } /** * Deallocate a block of memory obtained from the pool. * * If the given block is not the most recently * (re)allocated block, the memory of the this block * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param block the allocated block, the NULL is tolerated * @param block_size the size of the allocated block */ void MHD_pool_deallocate (struct MemoryPool *pool, void *block, size_t block_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (block != NULL || block_size == 0); mhd_assert (pool->size >= block_size); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); if (NULL != block) { /* Have previously allocated data */ const size_t block_offset = mp_ptr_diff_ (block, pool->memory); mhd_assert (mp_ptr_le_ (pool->memory, block)); mhd_assert (block_offset <= pool->size); mhd_assert ((block_offset != pool->pos) || (block_size == 0)); /* Zero-out deallocated region */ if (0 != block_size) { memset (block, 0, block_size); _MHD_POISON_MEMORY (block, block_size); } #if ! defined(MHD_FAVOR_SMALL_CODE) && ! defined(MHD_ASAN_POISON_ACTIVE) else return; /* Zero size, no need to do anything */ #endif /* ! MHD_FAVOR_SMALL_CODE && ! MHD_ASAN_POISON_ACTIVE */ if (block_offset <= pool->pos) { /* "Normal" block, not allocated "from the end". */ const size_t alg_end = ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size); mhd_assert (alg_end <= pool->pos); if (alg_end == pool->pos) { /* The last allocated block, return deallocated block to the pool */ size_t alg_start = ROUND_TO_ALIGN (block_offset); mhd_assert (alg_start >= block_offset); #if defined(MHD_ASAN_POISON_ACTIVE) if (alg_start != block_offset) { _MHD_POISON_MEMORY (pool->memory + block_offset, \ alg_start - block_offset); } else if (0 != alg_start) { bool need_red_zone_before; mhd_assert (_MHD_RED_ZONE_SIZE <= alg_start); #if defined(HAVE___ASAN_REGION_IS_POISONED) need_red_zone_before = (NULL == __asan_region_is_poisoned (pool->memory + alg_start - _MHD_RED_ZONE_SIZE, _MHD_RED_ZONE_SIZE)); #elif defined(HAVE___ASAN_ADDRESS_IS_POISONED) need_red_zone_before = (0 == __asan_address_is_poisoned (pool->memory + alg_start - 1)); #else /* ! HAVE___ASAN_ADDRESS_IS_POISONED */ need_red_zone_before = true; /* Unknown, assume new red zone needed */ #endif /* ! HAVE___ASAN_ADDRESS_IS_POISONED */ if (need_red_zone_before) { _MHD_POISON_MEMORY (pool->memory + alg_start, _MHD_RED_ZONE_SIZE); alg_start += _MHD_RED_ZONE_SIZE; } } #endif /* MHD_ASAN_POISON_ACTIVE */ mhd_assert (alg_start <= pool->pos); mhd_assert (alg_start == ROUND_TO_ALIGN (alg_start)); pool->pos = alg_start; } } else { /* Allocated "from the end" block. */ /* The size and the pointers of such block should not be manipulated by MHD code (block split is disallowed). */ mhd_assert (block_offset >= pool->end); mhd_assert (ROUND_TO_ALIGN (block_offset) == block_offset); if (block_offset == pool->end) { /* The last allocated block, return deallocated block to the pool */ const size_t alg_end = ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size); pool->end = alg_end; } } } } /** * Clear all entries from the memory pool except * for @a keep of the given @a copy_bytes. The pointer * returned should be a buffer of @a new_size where * the first @a copy_bytes are from @a keep. * * @param pool memory pool to use for the operation * @param keep pointer to the entry to keep (maybe NULL) * @param copy_bytes how many bytes need to be kept at this address * @param new_size how many bytes should the allocation we return have? * (should be larger or equal to @a copy_bytes) * @return addr new address of @a keep (if it had to change) */ void * MHD_pool_reset (struct MemoryPool *pool, void *keep, size_t copy_bytes, size_t new_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (copy_bytes <= new_size); mhd_assert (copy_bytes <= pool->size); mhd_assert (keep != NULL || copy_bytes == 0); mhd_assert (keep == NULL || mp_ptr_le_ (pool->memory, keep)); /* (keep == NULL || pool->memory + pool->size >= (uint8_t*) keep + copy_bytes) */ mhd_assert ((keep == NULL) || \ (pool->size >= mp_ptr_diff_ (keep, pool->memory) + copy_bytes)); #if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED) mhd_assert (NULL == __asan_region_is_poisoned (keep, copy_bytes)); #endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */ _MHD_UNPOISON_MEMORY (pool->memory, new_size); if ( (NULL != keep) && (keep != pool->memory) ) { if (0 != copy_bytes) memmove (pool->memory, keep, copy_bytes); } /* technically not needed, but safer to zero out */ if (pool->size > copy_bytes) { size_t to_zero; /** Size of area to zero-out */ to_zero = pool->size - copy_bytes; _MHD_UNPOISON_MEMORY (pool->memory + copy_bytes, to_zero); #ifdef _WIN32 if (pool->is_mmap) { size_t to_recommit; /** Size of decommitted and re-committed area. */ uint8_t *recommit_addr; /* Round down to page size */ to_recommit = to_zero - to_zero % MHD_sys_page_size_; recommit_addr = pool->memory + pool->size - to_recommit; /* De-committing and re-committing again clear memory and make * pages free / available for other needs until accessed. */ if (VirtualFree (recommit_addr, to_recommit, MEM_DECOMMIT)) { to_zero -= to_recommit; if (recommit_addr != VirtualAlloc (recommit_addr, to_recommit, MEM_COMMIT, PAGE_READWRITE)) abort (); /* Serious error, must never happen */ } } #endif /* _WIN32 */ memset (&pool->memory[copy_bytes], 0, to_zero); } pool->pos = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size); pool->end = pool->size; _MHD_POISON_MEMORY (((uint8_t *) pool->memory) + new_size, \ pool->size - new_size); return pool->memory; } /* end of memorypool.c */ libmicrohttpd-1.0.2/src/microhttpd/gen_auth.c0000644000175000017500000005632415035214301016205 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/gen_auth.c * @brief HTTP authorisation general functions * @author Karlson2k (Evgeny Grin) */ #include "gen_auth.h" #include "internal.h" #include "connection.h" #include "mhd_str.h" #include "mhd_assert.h" #ifdef BAUTH_SUPPORT #include "basicauth.h" #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT #include "digestauth.h" #endif /* DAUTH_SUPPORT */ #if ! defined(BAUTH_SUPPORT) && ! defined(DAUTH_SUPPORT) #error This file requires Basic or Digest authentication support #endif /** * Type of authorisation */ enum MHD_AuthType { MHD_AUTHTYPE_NONE = 0,/**< No authorisation, unused */ MHD_AUTHTYPE_BASIC, /**< Basic Authorisation, RFC 7617 */ MHD_AUTHTYPE_DIGEST, /**< Digest Authorisation, RFC 7616 */ MHD_AUTHTYPE_UNKNOWN, /**< Unknown/Unsupported authorisation type, unused */ MHD_AUTHTYPE_INVALID /**< Wrong/broken authorisation header, unused */ }; /** * Find required "Authorization" request header * @param c the connection with request * @param type the type of the authorisation: basic or digest * @param[out] auth_value will be set to the remaining of header value after * authorisation token (after "Basic " or "Digest ") * @return true if requested header is found, * false otherwise */ static bool find_auth_rq_header_ (const struct MHD_Connection *c, enum MHD_AuthType type, struct _MHD_str_w_len *auth_value) { const struct MHD_HTTP_Req_Header *h; const char *token; size_t token_len; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= c->state); if (MHD_CONNECTION_HEADERS_PROCESSED > c->state) return false; #ifdef DAUTH_SUPPORT if (MHD_AUTHTYPE_DIGEST == type) { token = _MHD_AUTH_DIGEST_BASE; token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE); } else /* combined with the next line */ #endif /* DAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if (MHD_AUTHTYPE_BASIC == type) { token = _MHD_AUTH_BASIC_BASE; token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_BASIC_BASE); } else /* combined with the next line */ #endif /* BAUTH_SUPPORT */ { mhd_assert (0); return false; } for (h = c->rq.headers_received; NULL != h; h = h->next) { if (MHD_HEADER_KIND != h->kind) continue; if (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION) != h->header_size) continue; if (token_len > h->value_size) continue; if (! MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_AUTHORIZATION, h->header, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_AUTHORIZATION))) continue; if (! MHD_str_equal_caseless_bin_n_ (h->value, token, token_len)) continue; /* Match only if token string is full header value or token is * followed by space or tab * Note: RFC 9110 (and RFC 7234) allows only space character, but * tab is supported here as well for additional flexibility and uniformity * as tabs are supported as separators between parameters. */ if ((token_len == h->value_size) || (' ' == h->value[token_len]) || ('\t' == h->value[token_len])) { if (token_len != h->value_size) { /* Skip whitespace */ auth_value->str = h->value + token_len + 1; auth_value->len = h->value_size - (token_len + 1); } else { /* No whitespace to skip */ auth_value->str = h->value + token_len; auth_value->len = h->value_size - token_len; } return true; /* Found a match */ } } return false; /* No matching header has been found */ } #ifdef BAUTH_SUPPORT /** * Parse request Authorization header parameters for Basic Authentication * @param str the header string, everything after "Basic " substring * @param str_len the length of @a str in characters * @param[out] pbauth the pointer to the structure with Basic Authentication * parameters * @return true if parameters has been successfully parsed, * false if format of the @a str is invalid */ static bool parse_bauth_params (const char *str, size_t str_len, struct MHD_RqBAuth *pbauth) { size_t i; i = 0; /* Skip all whitespaces at start */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; if (str_len > i) { size_t token68_start; size_t token68_len; /* 'i' points to the first non-whitespace char after scheme token */ token68_start = i; /* Find end of the token. Token cannot contain whitespace. */ while (i < str_len && ' ' != str[i] && '\t' != str[i]) { if (0 == str[i]) return false; /* Binary zero is not allowed */ if ((',' == str[i]) || (';' == str[i])) return false; /* Only single token68 is allowed */ i++; } token68_len = i - token68_start; mhd_assert (0 != token68_len); /* Skip all whitespaces */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; /* Check whether any garbage is present at the end of the string */ if (str_len != i) return false; else { /* No more data in the string, only single token68. */ pbauth->token68.str = str + token68_start; pbauth->token68.len = token68_len; } } return true; } /** * Return request's Basic Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqBAuth * MHD_get_rq_bauth_params_ (struct MHD_Connection *connection) { struct _MHD_str_w_len h_auth_value; struct MHD_RqBAuth *bauth; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state); if (connection->rq.bauth_tried) return connection->rq.bauth; if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state) return NULL; if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_BASIC, &h_auth_value)) { connection->rq.bauth_tried = true; connection->rq.bauth = NULL; return NULL; } bauth = (struct MHD_RqBAuth *) MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqBAuth)); if (NULL == bauth) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection's pool to allocate " \ "for Basic Authorization header parsing.\n")); #endif /* HAVE_MESSAGES */ return NULL; } memset (bauth, 0, sizeof(struct MHD_RqBAuth)); if (parse_bauth_params (h_auth_value.str, h_auth_value.len, bauth)) connection->rq.bauth = bauth; else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Basic Authorization client's header has " "incorrect format.\n")); #endif /* HAVE_MESSAGES */ connection->rq.bauth = NULL; /* Memory in the pool remains allocated until next request */ } connection->rq.bauth_tried = true; return connection->rq.bauth; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Get client's Digest Authorization algorithm type. * If no algorithm is specified by client, MD5 is assumed. * @param params the Digest Authorization 'algorithm' parameter * @return the algorithm type */ static enum MHD_DigestAuthAlgo3 get_rq_dauth_algo (const struct MHD_RqDAuthParam *const algo_param) { if (NULL == algo_param->value.str) return MHD_DIGEST_AUTH_ALGO3_MD5; /* Assume MD5 by default */ if (algo_param->quoted) { if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_MD5_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_MD5; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA256_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA256; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_MD5_TOKEN _MHD_SESS_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA512_256_TOKEN \ _MHD_SESS_TOKEN)) /* Algorithms below are not supported by MHD for authentication */ return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA256_TOKEN \ _MHD_SESS_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA512_256_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION; /* No known algorithm has been detected */ return MHD_DIGEST_AUTH_ALGO3_INVALID; } /* The algorithm value is not quoted */ if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_MD5; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA256; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256; /* Algorithms below are not supported by MHD for authentication */ if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION; /* No known algorithm has been detected */ return MHD_DIGEST_AUTH_ALGO3_INVALID; } /** * Get QOP ('quality of protection') type. * @param qop_param the Digest Authorization 'QOP' parameter * @return detected QOP ('quality of protection') type. */ static enum MHD_DigestAuthQOP get_rq_dauth_qop (const struct MHD_RqDAuthParam *const qop_param) { if (NULL == qop_param->value.str) return MHD_DIGEST_AUTH_QOP_NONE; if (qop_param->quoted) { if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \ qop_param->value.len, \ MHD_TOKEN_AUTH_)) return MHD_DIGEST_AUTH_QOP_AUTH; if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \ qop_param->value.len, \ MHD_TOKEN_AUTH_INT_)) return MHD_DIGEST_AUTH_QOP_AUTH_INT; } else { if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_, \ qop_param->value.str, \ qop_param->value.len)) return MHD_DIGEST_AUTH_QOP_AUTH; if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_INT_, \ qop_param->value.str, \ qop_param->value.len)) return MHD_DIGEST_AUTH_QOP_AUTH_INT; } /* No know QOP has been detected */ return MHD_DIGEST_AUTH_QOP_INVALID; } /** * Parse request Authorization header parameters for Digest Authentication * @param str the header string, everything after "Digest " substring * @param str_len the length of @a str in characters * @param[out] pdauth the pointer to the structure with Digest Authentication * parameters * @return true if parameters has been successfully parsed, * false if format of the @a str is invalid */ static bool parse_dauth_params (const char *str, const size_t str_len, struct MHD_RqDAuth *pdauth) { /* The tokens */ static const struct _MHD_cstr_w_len nonce_tk = _MHD_S_STR_W_LEN ("nonce"); static const struct _MHD_cstr_w_len opaque_tk = _MHD_S_STR_W_LEN ("opaque"); static const struct _MHD_cstr_w_len algorithm_tk = _MHD_S_STR_W_LEN ("algorithm"); static const struct _MHD_cstr_w_len response_tk = _MHD_S_STR_W_LEN ("response"); static const struct _MHD_cstr_w_len username_tk = _MHD_S_STR_W_LEN ("username"); static const struct _MHD_cstr_w_len username_ext_tk = _MHD_S_STR_W_LEN ("username*"); static const struct _MHD_cstr_w_len realm_tk = _MHD_S_STR_W_LEN ("realm"); static const struct _MHD_cstr_w_len uri_tk = _MHD_S_STR_W_LEN ("uri"); static const struct _MHD_cstr_w_len qop_tk = _MHD_S_STR_W_LEN ("qop"); static const struct _MHD_cstr_w_len cnonce_tk = _MHD_S_STR_W_LEN ("cnonce"); static const struct _MHD_cstr_w_len nc_tk = _MHD_S_STR_W_LEN ("nc"); static const struct _MHD_cstr_w_len userhash_tk = _MHD_S_STR_W_LEN ("userhash"); /* The locally processed parameters */ struct MHD_RqDAuthParam userhash; struct MHD_RqDAuthParam algorithm; /* Indexes */ size_t i; size_t p; /* The list of the tokens. The order of the elements matches the next array. */ static const struct _MHD_cstr_w_len *const tk_names[] = { &nonce_tk, /* 0 */ &opaque_tk, /* 1 */ &algorithm_tk, /* 2 */ &response_tk, /* 3 */ &username_tk, /* 4 */ &username_ext_tk, /* 5 */ &realm_tk, /* 6 */ &uri_tk, /* 7 */ &qop_tk, /* 8 */ &cnonce_tk, /* 9 */ &nc_tk, /* 10 */ &userhash_tk /* 11 */ }; /* The list of the parameters. The order of the elements matches the previous array. */ struct MHD_RqDAuthParam *params[sizeof(tk_names) / sizeof(tk_names[0])]; params[0 ] = &(pdauth->nonce); /* 0 */ params[1 ] = &(pdauth->opaque); /* 1 */ params[2 ] = &algorithm; /* 2 */ params[3 ] = &(pdauth->response); /* 3 */ params[4 ] = &(pdauth->username); /* 4 */ params[5 ] = &(pdauth->username_ext); /* 5 */ params[6 ] = &(pdauth->realm); /* 6 */ params[7 ] = &(pdauth->uri); /* 7 */ params[8 ] = &(pdauth->qop_raw); /* 8 */ params[9 ] = &(pdauth->cnonce); /* 9 */ params[10] = &(pdauth->nc); /* 10 */ params[11] = &userhash; /* 11 */ mhd_assert ((sizeof(tk_names) / sizeof(tk_names[0])) == \ (sizeof(params) / sizeof(params[0]))); memset (&userhash, 0, sizeof(userhash)); memset (&algorithm, 0, sizeof(algorithm)); i = 0; /* Skip all whitespaces at start */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; while (str_len > i) { size_t left; mhd_assert (' ' != str[i]); mhd_assert ('\t' != str[i]); left = str_len - i; if ('=' == str[i]) return false; /* The equal sign is not allowed as the first character */ for (p = 0; p < (sizeof(tk_names) / sizeof(tk_names[0])); ++p) { const struct _MHD_cstr_w_len *const tk_name = tk_names[p]; struct MHD_RqDAuthParam *const param = params[p]; if ( (tk_name->len <= left) && MHD_str_equal_caseless_bin_n_ (str + i, tk_name->str, tk_name->len) && ((tk_name->len == left) || ('=' == str[i + tk_name->len]) || (' ' == str[i + tk_name->len]) || ('\t' == str[i + tk_name->len]) || (',' == str[i + tk_name->len]) || (';' == str[i + tk_name->len])) ) { size_t value_start; size_t value_len; bool quoted; /* Only mark as "quoted" if backslash-escape used */ if (tk_name->len == left) return false; /* No equal sign after parameter name, broken data */ quoted = false; i += tk_name->len; /* Skip all whitespaces before '=' */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((i == str_len) || ('=' != str[i])) return false; /* No equal sign, broken data */ i++; /* Skip all whitespaces after '=' */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((str_len > i) && ('"' == str[i])) { /* Value is in quotation marks */ i++; /* Advance after the opening quote */ value_start = i; while (str_len > i && '"' != str[i]) { if ('\\' == str[i]) { i++; quoted = true; /* Have escaped chars */ } if (0 == str[i]) return false; /* Binary zero in parameter value */ i++; } if (str_len <= i) return false; /* No closing quote */ mhd_assert ('"' == str[i]); value_len = i - value_start; i++; /* Advance after the closing quote */ } else { value_start = i; while (str_len > i && ',' != str[i] && ' ' != str[i] && '\t' != str[i] && ';' != str[i]) { if (0 == str[i]) return false; /* Binary zero in parameter value */ i++; } if (';' == str[i]) return false; /* Semicolon in parameter value */ value_len = i - value_start; } /* Skip all whitespaces after parameter value */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((str_len > i) && (',' != str[i])) return false; /* Garbage after parameter value */ /* Have valid parameter name and value */ mhd_assert (! quoted || 0 != value_len); param->value.str = str + value_start; param->value.len = value_len; param->quoted = quoted; break; /* Found matching parameter name */ } } if (p == (sizeof(tk_names) / sizeof(tk_names[0]))) { /* No matching parameter name */ while (str_len > i && ',' != str[i]) { if ((0 == str[i]) || (';' == str[i])) return false; /* Not allowed characters */ if ('"' == str[i]) { /* Skip quoted part */ i++; /* Advance after the opening quote */ while (str_len > i && '"' != str[i]) { if (0 == str[i]) return false; /* Binary zero is not allowed */ if ('\\' == str[i]) i++; /* Skip escaped char */ i++; } if (str_len <= i) return false; /* No closing quote */ mhd_assert ('"' == str[i]); } i++; } } mhd_assert (str_len == i || ',' == str[i]); if (str_len > i) i++; /* Advance after ',' */ /* Skip all whitespaces before next parameter name */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; } /* Postprocess values */ if (NULL != userhash.value.str) { if (userhash.quoted) pdauth->userhash = MHD_str_equal_caseless_quoted_s_bin_n (userhash.value.str, \ userhash.value.len, \ "true"); else pdauth->userhash = MHD_str_equal_caseless_s_bin_n_ ("true", userhash.value.str, \ userhash.value.len); } else pdauth->userhash = false; pdauth->algo3 = get_rq_dauth_algo (&algorithm); pdauth->qop = get_rq_dauth_qop (&pdauth->qop_raw); return true; } /** * Return request's Digest Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqDAuth * MHD_get_rq_dauth_params_ (struct MHD_Connection *connection) { struct _MHD_str_w_len h_auth_value; struct MHD_RqDAuth *dauth; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state); if (connection->rq.dauth_tried) return connection->rq.dauth; if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state) return NULL; if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_DIGEST, &h_auth_value)) { connection->rq.dauth_tried = true; connection->rq.dauth = NULL; return NULL; } dauth = (struct MHD_RqDAuth *) MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqDAuth)); if (NULL == dauth) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection's pool to allocate " \ "for Digest Authorization header parsing.\n")); #endif /* HAVE_MESSAGES */ return NULL; } memset (dauth, 0, sizeof(struct MHD_RqDAuth)); if (parse_dauth_params (h_auth_value.str, h_auth_value.len, dauth)) connection->rq.dauth = dauth; else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Digest Authorization client's header has " "incorrect format.\n")); #endif /* HAVE_MESSAGES */ connection->rq.dauth = NULL; /* Memory in the pool remains allocated until next request */ } connection->rq.dauth_tried = true; return connection->rq.dauth; } #endif /* DAUTH_SUPPORT */ libmicrohttpd-1.0.2/src/microhttpd/mhd_threads.h0000644000175000017500000004536515035214301016705 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_threads.h * @brief Header for platform-independent threads abstraction * @author Karlson2k (Evgeny Grin) * * Provides basic abstraction for threads. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. * * @warning Unlike pthread functions, most of functions return * nonzero on success. */ #ifndef MHD_THREADS_H #define MHD_THREADS_H 1 #include "mhd_options.h" #ifdef HAVE_STDDEF_H # include /* for size_t */ #elif defined(HAVE_STDLIB_H) # include /* for size_t */ #else /* ! HAVE_STDLIB_H */ # include /* for size_t */ #endif /* ! HAVE_STDLIB_H */ #if defined(MHD_USE_POSIX_THREADS) # undef HAVE_CONFIG_H # include # define HAVE_CONFIG_H 1 # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #elif defined(MHD_USE_W32_THREADS) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #else # error No threading API is available. #endif #ifdef HAVE_STDBOOL_H # include #endif /* HAVE_STDBOOL_H */ #if defined(MHD_USE_POSIX_THREADS) && defined(MHD_USE_W32_THREADS) # error Both MHD_USE_POSIX_THREADS and MHD_USE_W32_THREADS are defined #endif /* MHD_USE_POSIX_THREADS && MHD_USE_W32_THREADS */ #ifndef MHD_NO_THREAD_NAMES # if defined(MHD_USE_POSIX_THREADS) # if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \ defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) || \ defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) || \ defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) # define MHD_USE_THREAD_NAME_ # endif /* HAVE_PTHREAD_SETNAME_NP */ # elif defined(MHD_USE_W32_THREADS) # ifdef _MSC_FULL_VER /* Thread names only available with VC compiler */ # define MHD_USE_THREAD_NAME_ # endif /* _MSC_FULL_VER */ # endif #endif /* ** Thread handle - used to control the thread ** */ #if defined(MHD_USE_POSIX_THREADS) /** * Wait until specified thread is ended and free thread handle on success. * @param thread handle to watch * @return nonzero on success, zero otherwise */ # define MHD_join_thread_(native_handle) \ (! pthread_join ((native_handle), NULL)) #elif defined(MHD_USE_W32_THREADS) /** * Wait until specified thread is ended and free thread handle on success. * @param thread handle to watch * @return nonzero on success, zero otherwise */ # define MHD_join_thread_(native_handle) \ ( (WAIT_OBJECT_0 == WaitForSingleObject ( (native_handle), INFINITE)) ? \ (CloseHandle ( (native_handle)), ! 0) : 0 ) #endif #if defined(MHD_USE_POSIX_THREADS) /** * The native type to control the thread from other threads */ typedef pthread_t MHD_thread_handle_native_; #elif defined(MHD_USE_W32_THREADS) /** * The native type to control the thread from other threads */ typedef HANDLE MHD_thread_handle_native_; #endif #if defined(MHD_USE_POSIX_THREADS) # if defined(__gnu_linux__) || \ (defined(__linux__) && defined(__GLIBC__)) /* The next part of code is disabled because it relies on undocumented behaviour. It could be enabled for neglectable performance and size improvements. */ # if 0 /* Disabled code */ /** * The native invalid value for native thread handle */ # define MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ \ ((MHD_thread_handle_native_) 0) # endif /* Disabled code */ # endif /* __gnu_linux__ || (__linux__ && __GLIBC__) */ #elif defined(MHD_USE_W32_THREADS) /** * The native invalid value for native thread handle */ # define MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ \ ((MHD_thread_handle_native_) NULL) #endif /* MHD_USE_W32_THREADS */ #if ! defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * Structure with thread handle and validity flag */ struct MHD_thread_handle_struct_ { bool valid; /**< true if native handle is set */ MHD_thread_handle_native_ native; /**< the native thread handle */ }; /** * Type with thread handle that can be set to invalid value */ typedef struct MHD_thread_handle_struct_ MHD_thread_handle_; /** * Set variable pointed by @a handle_ptr to invalid (unset) value */ # define MHD_thread_handle_set_invalid_(handle_ptr) \ ((handle_ptr)->valid = false) /** * Set native handle in variable pointed by @a handle_ptr * to @a native_val value */ # define MHD_thread_handle_set_native_(handle_ptr,native_val) \ ((handle_ptr)->valid = true, (handle_ptr)->native = native_val) /** * Check whether native handle value is set in @a handle_var variable */ # define MHD_thread_handle_is_valid_(handle_var) \ ((handle_var).valid) /** * Get native handle value from @a handle_var variable */ # define MHD_thread_handle_get_native_(handle_var) \ ((handle_var).native) #else /* MHD_THREAD_HANDLE_NATIVE_INVALID_ */ /** * Type with thread handle that can be set to invalid value */ typedef MHD_thread_handle_native_ MHD_thread_handle_; /** * Set variable pointed by @a handle_ptr to invalid (unset) value */ # define MHD_thread_handle_set_invalid_(handle_ptr) \ ((*(handle_ptr)) = MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * Set native handle in the variable pointed by @a handle_ptr * to @a native_val value */ # define MHD_thread_handle_set_native_(handle_ptr,native_val) \ ((*(handle_ptr)) = native_val) /** * Check whether native handle value is set in @a handle_var variable */ # define MHD_thread_handle_is_valid_(handle_var) \ (MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ != handle_var) /** * Get native handle value from @a handle_var variable */ # define MHD_thread_handle_get_native_(handle_var) \ (handle_var) /** * Get pointer to native handle stored the variable pointed by @a handle_ptr * @note This macro could not available if direct manipulation of * the native handle is not possible */ # define MHD_thread_handle_get_native_ptr_(handle_ptr) \ (handle_ptr) #endif /* MHD_THREAD_HANDLE_NATIVE_INVALID_ */ /* ** Thread ID - used to check threads match ** */ #if defined(MHD_USE_POSIX_THREADS) /** * The native type used to check whether current thread matches expected thread */ typedef pthread_t MHD_thread_ID_native_; /** * Function to get the current thread native ID. */ # define MHD_thread_ID_native_current_ pthread_self /** * Check whether two native thread IDs are equal. * @return non-zero if equal, zero if not equal */ # define MHD_thread_ID_native_equal_(id1,id2) \ (pthread_equal(id1,id2)) #elif defined(MHD_USE_W32_THREADS) /** * The native type used to check whether current thread matches expected thread */ typedef DWORD MHD_thread_ID_native_; /** * Function to get the current thread native ID. */ # define MHD_thread_ID_native_current_ GetCurrentThreadId /** * Check whether two native thread IDs are equal. * @return non-zero if equal, zero if not equal */ # define MHD_thread_ID_native_equal_(id1,id2) \ ((id1) == (id2)) #endif /** * Check whether specified thread ID matches current thread. * @param id the thread ID to match * @return nonzero on match, zero otherwise */ #define MHD_thread_ID_native_is_current_thread_(id) \ MHD_thread_ID_native_equal_(id, MHD_thread_ID_native_current_()) #if defined(MHD_USE_POSIX_THREADS) # if defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * The native invalid value for native thread ID */ # define MHD_THREAD_ID_NATIVE_VALUE_INVALID_ \ MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ # endif /* MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ */ #elif defined(MHD_USE_W32_THREADS) /** * The native invalid value for native thread ID */ # define MHD_THREAD_ID_NATIVE_VALUE_INVALID_ \ ((MHD_thread_ID_native_) 0) #endif /* MHD_USE_W32_THREADS */ #if ! defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) /** * Structure with thread id and validity flag */ struct MHD_thread_ID_struct_ { bool valid; /**< true if native ID is set */ MHD_thread_ID_native_ native; /**< the native thread ID */ }; /** * Type with thread ID that can be set to invalid value */ typedef struct MHD_thread_ID_struct_ MHD_thread_ID_; /** * Set variable pointed by @a ID_ptr to invalid (unset) value */ # define MHD_thread_ID_set_invalid_(ID_ptr) \ ((ID_ptr)->valid = false) /** * Set native ID in variable pointed by @a ID_ptr * to @a native_val value */ # define MHD_thread_ID_set_native_(ID_ptr,native_val) \ ((ID_ptr)->valid = true, (ID_ptr)->native = native_val) /** * Check whether native ID value is set in @a ID_var variable */ # define MHD_thread_ID_is_valid_(ID_var) \ ((ID_var).valid) /** * Get native ID value from @a ID_var variable */ # define MHD_thread_ID_get_native_(ID_var) \ ((ID_var).native) /** * Check whether @a ID_var variable is equal current thread */ # define MHD_thread_ID_is_current_thread_(ID_var) \ (MHD_thread_ID_is_valid_(ID_var) && \ MHD_thread_ID_native_is_current_thread_((ID_var).native)) #else /* MHD_THREAD_ID_NATIVE_INVALID_ */ /** * Type with thread ID that can be set to invalid value */ typedef MHD_thread_ID_native_ MHD_thread_ID_; /** * Set variable pointed by @a ID_ptr to invalid (unset) value */ # define MHD_thread_ID_set_invalid_(ID_ptr) \ ((*(ID_ptr)) = MHD_THREAD_ID_NATIVE_VALUE_INVALID_) /** * Set native ID in variable pointed by @a ID_ptr * to @a native_val value */ # define MHD_thread_ID_set_native_(ID_ptr,native_val) \ ((*(ID_ptr)) = native_val) /** * Check whether native ID value is set in @a ID_var variable */ # define MHD_thread_ID_is_valid_(ID_var) \ (MHD_THREAD_ID_NATIVE_VALUE_INVALID_ != ID_var) /** * Get native ID value from @a ID_var variable */ # define MHD_thread_ID_get_native_(ID_var) \ (ID_var) /** * Check whether @a ID_var variable is equal current thread */ # define MHD_thread_ID_is_current_thread_(ID_var) \ MHD_thread_ID_native_is_current_thread_(ID_var) #endif /* MHD_THREAD_ID_NATIVE_INVALID_ */ /** * Set current thread ID in variable pointed by @a ID_ptr */ # define MHD_thread_ID_set_current_thread_(ID_ptr) \ MHD_thread_ID_set_native_(ID_ptr,MHD_thread_ID_native_current_()) #if defined(MHD_USE_POSIX_THREADS) # if defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ ! defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) # error \ MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is defined, but MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is not defined # elif ! defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) # error \ MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is not defined, but MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is defined # endif #endif /* MHD_USE_POSIX_THREADS */ /* When staring a new thread, the kernel (and thread implementation) may * pause the calling (initial) thread and start the new thread. * If thread identifier is assigned to variable in the initial thread then * the value of the identifier variable will be undefined in the new thread * until the initial thread continue processing. * However, it is also possible that the new thread created, but not executed * for some time while the initial thread continue execution. In this case any * variable assigned in the new thread will be undefined for some time until * they really processed by the new thread. * To avoid data races, a special structure MHD_thread_handle_ID_ is used. * The "handle" is assigned by calling (initial) thread and should be always * defined when checked in the initial thread. * The "ID" is assigned by the new thread and should be always defined when * checked inside the new thread. */ /* Depending on implementation, pthread_create() MAY set thread ID into * provided pointer and after it start thread OR start thread and after * it set thread ID. In the latter case, to avoid data races, additional * pthread_self() call is required in thread routine. If some platform * is known for setting thread ID BEFORE starting thread macro * MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD could be defined * to save some resources. */ /* #define MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD 1 */ /* * handle - must be valid when other thread knows that particular thread is started. * ID - must be valid when code is executed inside thread */ #if defined(MHD_USE_POSIX_THREADS) && \ defined(MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD) && \ defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) && \ defined(MHD_thread_handle_get_native_ptr_) union _MHD_thread_handle_ID_ { MHD_thread_handle_ handle; /**< To be used in other threads */ MHD_thread_ID_ ID; /**< To be used in the thread itself */ }; typedef union _MHD_thread_handle_ID_ MHD_thread_handle_ID_; # define MHD_THREAD_HANDLE_ID_IS_UNION 1 #else /* !MHD_USE_POSIX_THREADS || !MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD || !MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ || !MHD_THREAD_ID_NATIVE_VALUE_INVALID_ || !MHD_thread_handle_get_native_ptr_ */ struct _MHD_thread_handle_ID_ { MHD_thread_handle_ handle; /**< To be used in other threads */ MHD_thread_ID_ ID; /**< To be used in the thread itself */ }; typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_; #endif /* !MHD_USE_POSIX_THREADS || !MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD || !MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ || !MHD_THREAD_ID_NATIVE_VALUE_INVALID_ || !MHD_thread_handle_get_native_ptr_ */ /** * Set MHD_thread_handle_ID_ to invalid value */ #define MHD_thread_handle_ID_set_invalid_(hndl_id_ptr) \ (MHD_thread_handle_set_invalid_(&((hndl_id_ptr)->handle)), \ MHD_thread_ID_set_invalid_(&((hndl_id_ptr)->ID))) /** * Check whether thread handle is valid. * To be used in threads other then the thread specified by @a hndl_id. */ #define MHD_thread_handle_ID_is_valid_handle_(hndl_id) \ MHD_thread_handle_is_valid_((hndl_id).handle) /** * Set native handle in variable pointed by @a hndl_id_ptr * to @a native_val value */ #define MHD_thread_handle_ID_set_native_handle_(hndl_id_ptr,native_val) \ MHD_thread_handle_set_native_(&((hndl_id_ptr)->handle),native_val) #if defined(MHD_thread_handle_get_native_ptr_) /** * Get pointer to native handle stored the variable pointed by @a hndl_id_ptr * @note This macro could not available if direct manipulation of * the native handle is not possible */ # define MHD_thread_handle_ID_get_native_handle_ptr_(hndl_id_ptr) \ MHD_thread_handle_get_native_ptr_(&((hndl_id_ptr)->handle)) #endif /* MHD_thread_handle_get_native_ptr_ */ /** * Get native thread handle from MHD_thread_handle_ID_ variable. */ #define MHD_thread_handle_ID_get_native_handle_(hndl_id) \ MHD_thread_handle_get_native_((hndl_id).handle) /** * Check whether thread ID is valid. * To be used in the thread itself. */ #define MHD_thread_handle_ID_is_valid_ID_(hndl_id) \ MHD_thread_ID_is_valid_((hndl_id).ID) #if defined(MHD_THREAD_HANDLE_ID_IS_UNION) # if defined(MHD_USE_W32_THREADS) # error MHD_thread_handle_ID_ cannot be a union with W32 threads # endif /* MHD_USE_W32_THREADS */ /** * Set current thread ID in the variable pointed by @a hndl_id_ptr */ # define MHD_thread_handle_ID_set_current_thread_ID_(hndl_id_ptr) (void) 0 #else /* ! MHD_THREAD_HANDLE_ID_IS_UNION */ /** * Set current thread ID in the variable pointed by @a hndl_id_ptr */ # define MHD_thread_handle_ID_set_current_thread_ID_(hndl_id_ptr) \ MHD_thread_ID_set_current_thread_(&((hndl_id_ptr)->ID)) #endif /* ! MHD_THREAD_HANDLE_ID_IS_UNION */ /** * Check whether provided thread ID matches current thread. * @param ID thread ID to match * @return nonzero on match, zero otherwise */ #define MHD_thread_handle_ID_is_current_thread_(hndl_id) \ MHD_thread_ID_is_current_thread_((hndl_id).ID) /** * Wait until specified thread is ended and free thread handle on success. * @param hndl_id_ handle with ID to watch * @return nonzero on success, zero otherwise */ #define MHD_thread_handle_ID_join_thread_(hndl_id) \ MHD_join_thread_(MHD_thread_handle_ID_get_native_handle_(hndl_id)) #if defined(MHD_USE_POSIX_THREADS) # define MHD_THRD_RTRN_TYPE_ void* # define MHD_THRD_CALL_SPEC_ #elif defined(MHD_USE_W32_THREADS) # define MHD_THRD_RTRN_TYPE_ unsigned # define MHD_THRD_CALL_SPEC_ __stdcall #endif /** * Signature of main function for a thread. * * @param cls closure argument for the function * @return termination code from the thread */ typedef MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ *MHD_THREAD_START_ROUTINE_)(void *cls); /** * Create a thread and set the attributes according to our options. * * If thread is created, thread handle must be freed by MHD_join_thread_(). * * @param handle_id handle to initialise * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_thread_ (MHD_thread_handle_ID_ *handle_id, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg); #ifndef MHD_USE_THREAD_NAME_ #define MHD_create_named_thread_(t,n,s,r,a) MHD_create_thread_ ((t),(s),(r),(a)) #else /* MHD_USE_THREAD_NAME_ */ /** * Create a named thread and set the attributes according to our options. * * @param handle_id handle to initialise * @param thread_name name for new thread * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise */ int MHD_create_named_thread_ (MHD_thread_handle_ID_ *handle_id, const char *thread_name, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg); #endif /* MHD_USE_THREAD_NAME_ */ #endif /* ! MHD_THREADS_H */ libmicrohttpd-1.0.2/src/microhttpd/mhd_str.h0000644000175000017500000007403315035214301016055 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str.h * @brief Header for string manipulating helpers * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_STR_H #define MHD_STR_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_str_types.h" #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #ifdef MHD_FAVOR_SMALL_CODE #include "mhd_limits.h" #endif /* MHD_FAVOR_SMALL_CODE */ /* * Block of functions/macros that use US-ASCII charset as required by HTTP * standards. Not affected by current locale settings. */ #ifndef MHD_FAVOR_SMALL_CODE /** * Check two strings for equality, ignoring case of US-ASCII letters. * * @param str1 first string to compare * @param str2 second string to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_ (const char *str1, const char *str2); #else /* MHD_FAVOR_SMALL_CODE */ /* Reuse MHD_str_equal_caseless_n_() to reduce size */ #define MHD_str_equal_caseless_(s1,s2) MHD_str_equal_caseless_n_ ((s1),(s2), \ SIZE_MAX) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a maxlen characters. * Compares up to first terminating null character, but not more than * first @a maxlen characters. * @param str1 first string to compare * @param str2 second string to compare * @param maxlen maximum number of characters to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_n_ (const char *const str1, const char *const str2, size_t maxlen); /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a len bytes. * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param str1 first string to compare * @param str2 second string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ bool MHD_str_equal_caseless_bin_n_ (const char *const str1, const char *const str2, size_t len); /** * Check whether string is equal statically allocated another string, * ignoring case of US-ASCII letters and checking not more than @a len bytes. * * If strings have different sizes (lengths) then macro returns boolean false * without checking the content. * * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param a the statically allocated string to compare * @param s the string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ #define MHD_str_equal_caseless_s_bin_n_(a,s,l) \ ((MHD_STATICSTR_LEN_(a) == (l)) \ && MHD_str_equal_caseless_bin_n_(a,s,l)) /** * Check whether @a str has case-insensitive @a token. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end (of string) or comma * contains only case-insensitive token and optional spaces and tabs. * @warning token must not contain null-characters except optional * terminating null-character. * @param str the string to check * @param token the token to find * @param token_len length of token, not including optional terminating * null-character. * @return non-zero if two strings are equal, zero otherwise. */ bool MHD_str_has_token_caseless_ (const char *str, const char *const token, size_t token_len); /** * Check whether @a str has case-insensitive static @a tkn. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end of string or comma * contains only case-insensitive token and optional spaces and tabs. * @warning tkn must be static string * @param str the string to check * @param tkn the static string of token to find * @return non-zero if two strings are equal, zero otherwise. */ #define MHD_str_has_s_token_caseless_(str,tkn) \ MHD_str_has_token_caseless_ ((str),(tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Remove case-insensitive @a token from the @a str and put result * to the output @a buf. * * Tokens in @a str could be surrounded by spaces and tabs and delimited by * comma. The token match succeed if substring between start, end (of string) * or comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The output string is normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. * * @param str the string to process * @param str_len the length of the @a str, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @param[out] buf the output buffer, not null-terminated. * @param[in,out] buf_size pointer to the size variable, at input it * is the size of allocated buffer, at output * it is the size of the resulting string (can * be up to 50% larger than input) or negative value * if there is not enough space for the result * @return 'true' if token has been removed, * 'false' otherwise. */ bool MHD_str_remove_token_caseless_ (const char *str, size_t str_len, const char *const token, const size_t token_len, char *buf, ssize_t *buf_size); /** * Perform in-place case-insensitive removal of @a tokens from the @a str. * * Token could be surrounded by spaces and tabs and delimited by comma. * The token match succeed if substring between start, end (of the string), or * comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The input string must be normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. The string is updated in-place. * * Behavior is undefined is the input string in not normalised. * * @param[in,out] str the string to update * @param[in,out] str_len the length of the @a str, not including optional * terminating null-character, not null-terminated * @param tokens the token to find * @param tokens_len the length of @a tokens, not including optional * terminating null-character. * @return 'true' if any token has been removed, * 'false' otherwise. */ bool MHD_str_remove_tokens_caseless_ (char *str, size_t *str_len, const char *const tokens, const size_t tokens_len); #ifndef MHD_FAVOR_SMALL_CODE /* Use individual function for each case to improve speed */ /** * Convert decimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_ (const char *str, uint64_t *out_val); /** * Convert not more then @a maxlen decimal US-ASCII digits in string to * number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val); /** * Convert hexadecimal US-ASCII digits in string to number in uint32_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_ (const char *str, uint32_t *out_val); /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint32_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_n_ (const char *str, size_t maxlen, uint32_t *out_val); /** * Convert hexadecimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_ (const char *str, uint64_t *out_val); /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val); #else /* MHD_FAVOR_SMALL_CODE */ /* Use one universal function and macros to reduce size */ /** * Generic function for converting not more then @a maxlen * hexadecimal or decimal US-ASCII digits in string to number. * Conversion stopped at first non-digit character or after @a maxlen * digits. * To be used only within macro. * * @param str the string to convert * @param maxlen the maximum number of characters to process * @param out_val the pointer to variable to store result of conversion * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8 * @param max_val the maximum decoded number * @param base the numeric base, 10 or 16 * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then @a max_val, @a val_size is not 4/8 or @a out_val is NULL */ size_t MHD_str_to_uvalue_n_ (const char *str, size_t maxlen, void *out_val, size_t val_size, uint64_t max_val, unsigned int base); #define MHD_str_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint64_t), \ UINT64_MAX,10) #define MHD_str_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint64_t), \ UINT64_MAX,10) #define MHD_strx_to_sizet_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(size_t),SIZE_MAX, \ 16) #define MHD_strx_to_sizet_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(size_t), \ SIZE_MAX,16) #define MHD_strx_to_uint32_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint32_t), \ UINT32_MAX,16) #define MHD_strx_to_uint32_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint32_t), \ UINT32_MAX,16) #define MHD_strx_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint64_t), \ UINT64_MAX,16) #define MHD_strx_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint64_t), \ UINT64_MAX,16) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert uint32_t value to hexdecimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint32_to_strx (uint32_t val, char *buf, size_t buf_size); #ifndef MHD_FAVOR_SMALL_CODE /** * Convert uint16_t value to decimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint16_to_str (uint16_t val, char *buf, size_t buf_size); #else /* MHD_FAVOR_SMALL_CODE */ #define MHD_uint16_to_str(v,b,s) MHD_uint64_to_str(v,b,s) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert uint64_t value to decimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint64_to_str (uint64_t val, char *buf, size_t buf_size); /** * Convert uint16_t value to decimal US-ASCII string padded with * zeros on the left side. * * @note: result is NOT zero-terminated. * @param val the value to convert * @param min_digits the minimal number of digits to print, * output padded with zeros on the left side, * 'zero' value is interpreted as 'one', * valid values are 3, 2, 1, 0 * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint8_to_str_pad (uint8_t val, uint8_t min_digits, char *buf, size_t buf_size); /** * Convert @a size bytes from input binary data to lower case * hexadecimal digits. * Result is NOT zero-terminated * @param bin the pointer to the binary data to convert * @param size the size in bytes of the binary data to convert * @param[out] hex the output buffer, should be at least 2 * @a size * @return The number of characters written to the output buffer. */ size_t MHD_bin_to_hex (const void *bin, size_t size, char *hex); /** * Convert @a size bytes from input binary data to lower case * hexadecimal digits, zero-terminate the result. * @param bin the pointer to the binary data to convert * @param size the size in bytes of the binary data to convert * @param[out] hex the output buffer, should be at least 2 * @a size + 1 * @return The number of characters written to the output buffer, * not including terminating zero. */ size_t MHD_bin_to_hex_z (const void *bin, size_t size, char *hex); /** * Convert hexadecimal digits to binary data. * * The input decoded byte-by-byte (each byte is two hexadecimal digits). * If length is an odd number, extra leading zero is assumed. * * @param hex the input string with hexadecimal digits * @param len the length of the input string * @param[out] bin the output buffer, must be at least len/2 bytes long (or * len/2 + 1 if @a len is not even number) * @return the number of bytes written to the output buffer, * zero if found any character which is not hexadecimal digits */ size_t MHD_hex_to_bin (const char *hex, size_t len, void *bin); /** * Decode string with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying all other characters without extra * processing. * * @param pct_encoded the input string to be decoded * @param pct_encoded_len the length of the @a pct_encoded * @param[out] decoded the output buffer, NOT zero-terminated, can point * to the same buffer as @a pct_encoded * @param buf_size the size of the output buffer * @return the number of characters written to the output buffer or * zero if any percent-encoded characters is broken ('%' followed * by less than two hexadecimal digits) or output buffer is too * small to hold the result */ size_t MHD_str_pct_decode_strict_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size); /** * Decode string with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying all other characters without extra * processing. * * Any invalid percent-encoding sequences ('%' symbol not followed by two * valid hexadecimal digits) are copied to the output string without decoding. * * @param pct_encoded the input string to be decoded * @param pct_encoded_len the length of the @a pct_encoded * @param[out] decoded the output buffer, NOT zero-terminated, can point * to the same buffer as @a pct_encoded * @param buf_size the size of the output buffer * @param[out] broken_encoding will be set to true if any '%' symbol is not * followed by two valid hexadecimal digits, * optional, can be NULL * @return the number of characters written to the output buffer or * zero if output buffer is too small to hold the result */ size_t MHD_str_pct_decode_lenient_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size, bool *broken_encoding); /** * Decode string in-place with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying back all other characters without extra * processing. * * @param[in,out] str the string to be updated in-place, must be zero-terminated * on input, the output is zero-terminated; the string is * truncated to zero length if broken encoding is found * @return the number of character in decoded string */ size_t MHD_str_pct_decode_in_place_strict_ (char *str); /** * Decode string in-place with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying back all other characters without extra * processing. * * Any invalid percent-encoding sequences ('%' symbol not followed by two * valid hexadecimal digits) are copied to the output string without decoding. * * @param[in,out] str the string to be updated in-place, must be zero-terminated * on input, the output is zero-terminated * @param[out] broken_encoding will be set to true if any '%' symbol is not * followed by two valid hexadecimal digits, * optional, can be NULL * @return the number of character in decoded string */ size_t MHD_str_pct_decode_in_place_lenient_ (char *str, bool *broken_encoding); #ifdef DAUTH_SUPPORT /** * Check two strings for equality, "unquoting" the first string from quoted * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * Null-termination for input strings is not required, binary zeros compared * like other characters. * * @param quoted the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param unquoted the unquoted string to compare, does not need to be * zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are equal after unquoting of the * first string. */ bool MHD_str_equal_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len); /** * Check whether the string after "unquoting" equals static string. * * Null-termination for input string is not required, binary zeros compared * like other characters. * * @param q the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param l the length in chars of the @a q string * @param u the unquoted static string to compare * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are equal after unquoting of the * first string. */ #define MHD_str_equal_quoted_s_bin_n(q,l,u) \ MHD_str_equal_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u)) /** * Check two strings for equality, "unquoting" the first string from quoted * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings and * ignoring case of US-ASCII letters. * * Null-termination for input strings is not required, binary zeros compared * like other characters. * * @param quoted the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param unquoted the unquoted string to compare, does not need to be * zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are caseless equal after unquoting of the * first string. */ bool MHD_str_equal_caseless_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len); /** * Check whether the string after "unquoting" equals static string, ignoring * case of US-ASCII letters. * * Null-termination for input string is not required, binary zeros compared * like other characters. * * @param q the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param l the length in chars of the @a q string * @param u the unquoted static string to compare * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are caseless equal after unquoting of the * first string. */ #define MHD_str_equal_caseless_quoted_s_bin_n(q,l,u) \ MHD_str_equal_caseless_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u)) /** * Convert string from quoted to unquoted form as specified by * RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * @param quoted the quoted string, must NOT include leading and closing * DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param[out] result the pointer to the buffer to put the result, must * be at least @a size character long. May be modified even * if @a quoted is invalid sequence. The result is NOT * zero-terminated. * @return The number of characters written to the output buffer, * zero if last backslash is not followed by any character (or * @a quoted_len is zero). */ size_t MHD_str_unquote (const char *quoted, size_t quoted_len, char *result); #endif /* DAUTH_SUPPORT */ #if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT) /** * Convert string from unquoted to quoted form as specified by * RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * @param unquoted the unquoted string, does not need to be zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @param[out] result the pointer to the buffer to put the result. May be * modified even if function failed due to insufficient * space. The result is NOT zero-terminated and does not * have opening and closing DQUOTE chars. * @param buf_size the size of the allocated memory for @a result * @return The number of copied characters, can be up to two times more than * @a unquoted_len, zero if @a unquoted_len is zero or if quoted * string is larger than @a buf_size. */ size_t MHD_str_quote (const char *unquoted, size_t unquoted_len, char *result, size_t buf_size); #endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT /** * Returns the maximum possible size of the Base64 decoded data. * The real recoded size could be up to two bytes smaller. * @param enc_size the size of encoded data, in characters * @return the maximum possible size of the decoded data, in bytes, if * @a enc_size is valid (properly padded), * undefined value smaller then @a enc_size if @a enc_size is not valid */ #define MHD_base64_max_dec_size_(enc_size) (((enc_size) / 4) * 3) /** * Convert Base64 encoded string to binary data. * @param base64 the input string with Base64 encoded data, could be NOT zero * terminated * @param base64_len the number of characters to decode in @a base64 string, * valid number must be a multiple of four * @param[out] bin the pointer to the output buffer, the buffer may be altered * even if decoding failed * @param bin_size the size of the @a bin buffer in bytes, if the size is * at least @a base64_len / 4 * 3 then result will always * fit, regardless of the amount of the padding characters * @return 0 if @a base64_len is zero, or input string has wrong data (not * valid Base64 sequence), or @a bin_size is too small; * non-zero number of bytes written to the @a bin, the number must be * (base64_len / 4 * 3 - 2), (base64_len / 4 * 3 - 1) or * (base64_len / 4 * 3), depending on the number of padding characters. */ size_t MHD_base64_to_bin_n (const char *base64, size_t base64_len, void *bin, size_t bin_size); #endif /* BAUTH_SUPPORT */ #endif /* MHD_STR_H */ libmicrohttpd-1.0.2/src/microhttpd/test_str_tokens_remove.c0000644000175000017500000003311014760713574021232 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for MHD_str_remove_tokens_caseless_() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" static int expect_result_n (const char *str, size_t str_len, const char *tokens, size_t tokens_len, const char *expected, size_t expected_len, const bool expected_removed) { char buf_in[1024]; char buf_tokens[256]; bool res; size_t result_len; mhd_assert (sizeof(buf_in) > str_len + 2); mhd_assert (sizeof(buf_tokens) > tokens_len + 2); memset (buf_tokens, '#', sizeof(buf_tokens)); memcpy (buf_tokens, tokens, tokens_len); /* Copy without zero-termination */ memset (buf_in, '$', sizeof(buf_in)); memcpy (buf_in, str, str_len); /* Copy without zero-termination */ result_len = str_len; res = MHD_str_remove_tokens_caseless_ (buf_in, &result_len, buf_tokens, tokens_len); if ( (expected_removed != res) || (expected_len != result_len) || ((0 != result_len) && (0 != memcmp (expected, buf_in, result_len))) || ('$' != buf_in[str_len])) { fprintf (stderr, "MHD_str_remove_tokens_caseless_() FAILED:\n" "\tRESULT: " "\tMHD_str_remove_token_caseless_(\"%s\"->\"%.*s\", &(%lu->%lu)," " \"%.*s\", %lu) returned %s\n", str, (int) result_len, buf_in, (unsigned long) str_len, (unsigned long) result_len, (int) tokens_len, buf_tokens, (unsigned long) tokens_len, res ? "true" : "false"); fprintf (stderr, "\tEXPECTED: " "\tMHD_str_remove_token_caseless_(\"%s\"->\"%s\", &(%lu->%lu)," " \"%.*s\", %lu) returned %s\n", str, expected, (unsigned long) str_len, (unsigned long) expected_len, (int) tokens_len, buf_tokens, (unsigned long) tokens_len, expected_removed ? "true" : "false"); return 1; } return 0; } #define expect_result(s,t,e,found) \ expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \ (t),MHD_STATICSTR_LEN_ (t), \ (e),MHD_STATICSTR_LEN_ (e), found) static int check_result (void) { int errcount = 0; errcount += expect_result ("string", "string", "", true); errcount += expect_result ("String", "string", "", true); errcount += expect_result ("string", "String", "", true); errcount += expect_result ("strinG", "String", "", true); errcount += expect_result ("strinG", "String\t", "", true); errcount += expect_result ("strinG", "\tString", "", true); errcount += expect_result ("tOkEn", " \t toKEN ", "", true); errcount += expect_result ("not-token, tOkEn", "token", "not-token", true); errcount += expect_result ("not-token1, tOkEn1, token", "token1", "not-token1, token", true); errcount += expect_result ("token, tOkEn1", "token1", "token", true); errcount += expect_result ("not-token, tOkEn", " \t toKEN", "not-token", true); errcount += expect_result ("not-token, tOkEn, more-token", "toKEN\t", "not-token, more-token", true); errcount += expect_result ("not-token, tOkEn, more-token", "\t toKEN,,,,,", "not-token, more-token", true); errcount += expect_result ("a, b, c, d", ",,,,,a", "b, c, d", true); errcount += expect_result ("a, b, c, d", "a,,,,,,", "b, c, d", true); errcount += expect_result ("a, b, c, d", ",,,,a,,,,,,", "b, c, d", true); errcount += expect_result ("a, b, c, d", "\t \t,,,,a,, , ,,,\t", "b, c, d", true); errcount += expect_result ("a, b, c, d", "b, c, d", "a", true); errcount += expect_result ("a, b, c, d", "a, b, c, d", "", true); errcount += expect_result ("a, b, c, d", "d, c, b, a", "", true); errcount += expect_result ("a, b, c, d", "b, d, a, c", "", true); errcount += expect_result ("a, b, c, d, e", "b, d, a, c", "e", true); errcount += expect_result ("e, a, b, c, d", "b, d, a, c", "e", true); errcount += expect_result ("e, a, b, c, d, e", "b, d, a, c", "e, e", true); errcount += expect_result ("a, b, c, d", "b,c,d", "a", true); errcount += expect_result ("a, b, c, d", "a,b,c,d", "", true); errcount += expect_result ("a, b, c, d", "d,c,b,a", "", true); errcount += expect_result ("a, b, c, d", "b,d,a,c", "", true); errcount += expect_result ("a, b, c, d, e", "b,d,a,c", "e", true); errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true); errcount += expect_result ("e, a, b, c, d, e", "b,d,a,c", "e, e", true); errcount += expect_result ("a, b, c, d", "d,,,,,,,,,c,b,a", "", true); errcount += expect_result ("a, b, c, d", "b,d,a,c,,,,,,,,,,", "", true); errcount += expect_result ("a, b, c, d, e", ",,,,\t,,,,b,d,a,c,\t", "e", true); errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true); errcount += expect_result ("token, a, b, c, d", "token", "a, b, c, d", true); errcount += expect_result ("token1, a, b, c, d", "token1", "a, b, c, d", true); errcount += expect_result ("token12, a, b, c, d", "token12", "a, b, c, d", true); errcount += expect_result ("token123, a, b, c, d", "token123", "a, b, c, d", true); errcount += expect_result ("token1234, a, b, c, d", "token1234", "a, b, c, d", true); errcount += expect_result ("token12345, a, b, c, d", "token12345", "a, b, c, d", true); errcount += expect_result ("token123456, a, b, c, d", "token123456", "a, b, c, d", true); errcount += expect_result ("token1234567, a, b, c, d", "token1234567", "a, b, c, d", true); errcount += expect_result ("token12345678, a, b, c, d", "token12345678", "a, b, c, d", true); errcount += expect_result ("", "a", "", false); errcount += expect_result ("", "", "", false); errcount += expect_result ("a, b, c, d", "bb, dd, aa, cc", "a, b, c, d", false); errcount += expect_result ("a, b, c, d, e", "bb, dd, aa, cc", "a, b, c, d, e", false); errcount += expect_result ("e, a, b, c, d", "bb, dd, aa, cc", "e, a, b, c, d", false); errcount += expect_result ("e, a, b, c, d, e", "bb, dd, aa, cc", "e, a, b, c, d, e", false); errcount += expect_result ("aa, bb, cc, dd", "b, d, a, c", "aa, bb, cc, dd", false); errcount += expect_result ("aa, bb, cc, dd, ee", "b, d, a, c", "aa, bb, cc, dd, ee", false); errcount += expect_result ("ee, aa, bb, cc, dd", "b, d, a, c", "ee, aa, bb, cc, dd", false); errcount += expect_result ("ee, aa, bb, cc, dd, ee", "b, d, a, c", "ee, aa, bb, cc, dd, ee", false); errcount += expect_result ("TESt", ",,,,,,test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,\t,test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,,test, ,,,", "", true); errcount += expect_result ("TESt", ",,,,,, test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not,,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not ,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test", "", true); errcount += expect_result ("TESt", ",,,,,, test ", "", true); errcount += expect_result ("TESt", "no-test,,,,,, test ", "", true); errcount += expect_result ("the-token, a, the-token, b, the-token, " \ "the-token, c, the-token", "the-token", "a, b, c", true); errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \ "the-token, dd, the-token", "the-token", "aa, bb, cc, dd", true); errcount += expect_result ("the-token, a, the-token, b, the-token, " \ "the-token, c, the-token, e", "the-token", "a, b, c, e", true); errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \ "the-token, dd, the-token, ee", "the-token", "aa, bb, cc, dd, ee", true); errcount += expect_result ("the-token, the-token, the-token, " \ "the-token, the-token", "the-token", "", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", "c,a,b", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", "ww,zz,yy", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", " c,\t a,b,,,", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", ",,,,ww,\t zz, yy", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", ",,,,c,\t a,b", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", " ww,\t zz,yy,,,,", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("close, 2", "close", "2", true); errcount += expect_result ("close, 22", "close", "22", true); errcount += expect_result ("close, nothing", "close", "nothing", true); errcount += expect_result ("close, 2", "2", "close", true); errcount += expect_result ("close", "close", "", true); errcount += expect_result ("close, nothing", "close, token", "nothing", true); errcount += expect_result ("close, nothing", "nothing, token", "close", true); errcount += expect_result ("close, 2", "close, 10, 12, 22, nothing", "2", true); errcount += expect_result ("strin", "string", "strin", false); errcount += expect_result ("Stringer", "string", "Stringer", false); errcount += expect_result ("sstring", "String", "sstring", false); errcount += expect_result ("string", "Strin", "string", false); errcount += expect_result ("String", "\t(-strinG", "String", false); errcount += expect_result ("String", ")strinG\t ", "String", false); errcount += expect_result ("not-token, tOkEner", "toKEN", "not-token, tOkEner", false); errcount += expect_result ("not-token, tOkEns, more-token", "toKEN", "not-token, tOkEns, more-token", false); errcount += expect_result ("tests, quest", "TESt", "tests, quest", false); errcount += expect_result ("testÑ‹", "TESt", "testÑ‹", false); errcount += expect_result ("test-not, Ñ…test", "TESt", "test-not, Ñ…test", false); errcount += expect_result ("testing, test not, test2", "TESt", "testing, test not, test2", false); errcount += expect_result ("", ",,,,,,,,,,,,,,,,,,,the-token", "", false); errcount += expect_result ("a1, b1, c1, d1, e1, f1, g1", "", "a1, b1, c1, d1, e1, f1, g1", false); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_result (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/test_postprocessor_amp.c0000644000175000017500000001175714760713574021261 00000000000000#include "platform.h" #include "microhttpd.h" #include "internal.h" #include #include #include static uint64_t num_errors; static enum MHD_Result check_post (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *content_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) content_encoding; (void) data; (void) off; (void) size; /* Unused. Silent compiler warning. */ if ((0 != strcmp (key, "a")) && (0 != strcmp (key, "b"))) { printf ("ERROR: got unexpected '%s'\n", key); num_errors++; } return MHD_YES; } int main (int argc, char *const *argv) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; const char *post = "a=xx+xx+xxx+xxxxx+xxxx+xxxxxxxx+xxx+xxxxxx+xxx+xxx+xxxxxxx+xxxxx%0A+++" "++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%0A+++++++--%3E%0A++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%" "25%22%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%2" "2+xxxxx%3D%22xxxxx%22%3E%0A+++++++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%" "25%22%3E%0A+++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++++++++++++" "++%3Cxx+xxxxx%3D%22xxxx%22%3E%0A+++++++++++++++++++++++++++++++%3Cx+xx" "xxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxxxx%3A%3C%2Fx%3E%0A%0A+++++++++++++" "++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxx%3A%3C%2F" "x%3E%0A%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3A" "xxxxx%3B+xxxx-xxxxxx%3A+xxxx%3B%22%3Exxxxx+xxxxx%3A%3C%2Fx%3E%0A++++++" "+++++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++++++++++%3C%2Fxx%3E%" "0A+++++++++++++++++++%3C%2Fxxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++" "++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3" "E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxx" "xx%22%3Exxxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A++++++++++" "+%3C%2Fxx%3E%0A++++++++++++++++++++++++++%3Cxx%3E%0A++++++++++++++++++" "+%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3" "B+%3Cxxxx%0A+++++++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3" "Exxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++++++%3C%2Fxx%3E%0A++++++++++++++" "+%3C%2Fxx%3E%0A++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+x" "xxxx%3D%22xxxx-xxxxx%3A+xxxxx%3Bxxxx-xxxxxx%3A+xxxx%3B+xxxxx%3A+xxxx%2" "2%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxx" "xxxxx%22%3Exxxx.xx%3C%2Fxxxx%3E%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A" "+++++++%3C%2Fxxxxx%3E%0A+++++++%3C%21--%0A+++++++xxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++x" "xx+xx+xxxxx+xxxxxxx+xxxxxxx%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++--%3E%0A+++%3" "C%2Fxxx%3E%0A%0A%0A%0A+++%3Cxxx+xxxxx%3D%22xxxxxxxxx%22+xx%3D%22xxxxxx" "xxx%22%3E%3C%2Fxxx%3E%0A%0A+++%3Cxxx+xx%3D%22xxxx%22+xxxxx%3D%22xxxx%2" "2%3E%0A+++++++%3Cxxxxx+xxxxx%3D%22xxxxxxxxx%22%3E%0A+++++++++++%3Cxx%3" "E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xx" "xxx%3D%22xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxx" "x%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx" "%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xx%3D%22xxxxxxxxxxxxx" "xxxx%22+xxxxx%3D%22xxxxxxxxxxxxxxxxx%22%3E%3C%2Fxx%3E%0A++++++++++++++" "+%3Cxx+xx%3D%22xxxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxxx%22%3E%0A+++" "++++++++++++++++%3Cxxx+xx%3D%22xxxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++" "++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++++++%3Cxx%3E%0A+++++" "++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xxxxx%3D%22" "xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxx%22%3E%3" "C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++" "++++%3C%2Fxxxxx%3E%0A+++%3C%2Fxxx%3E%0A%3C%2Fxxx%3E%0A%0A%3Cxxx+xx%3D%" "22xxxxxx%22%3E%3C%2Fxxx%3E%0A%0A%3C%2Fxxxx%3E%0A%3C%2Fxxxx%3E+&b=value"; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ num_errors = 0; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 4096, &check_post, NULL); if (NULL == pp) return 1; if (MHD_YES != MHD_post_process (pp, post, strlen (post))) num_errors++; MHD_destroy_post_processor (pp); return num_errors == 0 ? 0 : 2; } libmicrohttpd-1.0.2/src/microhttpd/Makefile.am0000644000175000017500000004455215035214301016303 00000000000000# This Makefile.am is in the public domain AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) $(HIDDEN_VISIBILITY_CFLAGS) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) lib_LTLIBRARIES = \ libmicrohttpd.la noinst_DATA = MOSTLYCLEANFILES = AM_V_LIB = $(am__v_LIB_@AM_V@) am__v_LIB_ = $(am__v_LIB_@AM_DEFAULT_V@) am__v_LIB_0 = @echo " LIB " $@; am__v_LIB_1 = if W32_SHARED_LIB_EXP AM_V_DLLTOOL = $(am__v_DLLTOOL_@AM_V@) am__v_DLLTOOL_ = $(am__v_DLLTOOL_@AM_DEFAULT_V@) am__v_DLLTOOL_0 = @echo " DLLTOOL " $@; am__v_DLLTOOL_1 = W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp $(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la $(AM_V_at)test -f $@ && touch $@ || \ ( rm -f libmicrohttpd.la ; $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la && touch $@ ) if USE_EXPORT_FILE noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.exp $(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib $(AM_V_at)test -f $@ && touch $@ || \ ( rm -f $(lt_cv_objdir)/libmicrohttpd.lib ; $(MAKE) $(AM_MAKEFLAGS) $(lt_cv_objdir)/libmicrohttpd.lib && touch $@ ) endif if USE_MS_LIB_TOOL $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) $(AM_V_LIB) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(MS_LIB_TOOL) -nologo -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -ignore:4221 else if USE_EXPORT_FILE $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp else $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib endif endif else W32_MHD_LIB_LDFLAGS = endif if W32_STATIC_LIB noinst_DATA += $(lt_cv_objdir)/libmicrohttpd-static.lib MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd-static.lib $(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) if USE_MS_LIB_TOOL $(AM_V_LIB) $(MS_LIB_TOOL) -nologo -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o) else $(AM_V_at)cp $(lt_cv_objdir)/libmicrohttpd.a $@ endif endif libmicrohttpd_la_SOURCES = \ connection.c connection.h \ reason_phrase.c \ daemon.c \ internal.c internal.h \ memorypool.c memorypool.h \ mhd_mono_clock.c mhd_mono_clock.h \ mhd_limits.h \ sysfdsetsize.h \ mhd_str.c mhd_str.h mhd_str_types.h\ mhd_send.h mhd_send.c \ mhd_assert.h \ mhd_sockets.c mhd_sockets.h \ mhd_itc.c mhd_itc.h mhd_itc_types.h \ mhd_compat.c mhd_compat.h \ mhd_panic.c mhd_panic.h \ response.c response.h if USE_POSIX_THREADS libmicrohttpd_la_SOURCES += \ mhd_threads.c mhd_threads.h \ mhd_locks.h endif if USE_W32_THREADS libmicrohttpd_la_SOURCES += \ mhd_threads.c mhd_threads.h \ mhd_locks.h endif if NEED_SYS_FD_SET_SIZE_VALUE libmicrohttpd_la_SOURCES += \ sysfdsetsize.c endif libmicrohttpd_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS) libmicrohttpd_la_LDFLAGS = \ $(AM_LDFLAGS) $(MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -export-dynamic -no-undefined \ -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@ libmicrohttpd_la_LIBADD = \ $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS) AM_V_RC = $(am__v_RC_@AM_V@) am__v_RC_ = $(am__v_RC_@AM_DEFAULT_V@) am__v_RC_0 = @echo " RC " $@; am__v_RC_1 = # General rule is not required, but keep it just in case # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. .rc.lo: $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $< -o $@ # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. libmicrohttpd_la-microhttpd_dll_res.lo: $(builddir)/microhttpd_dll_res.rc $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $(builddir)/microhttpd_dll_res.rc -o $@ if HAVE_W32 MHD_DLL_RES_LO = libmicrohttpd_la-microhttpd_dll_res.lo else MHD_DLL_RES_LO = endif EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO) libmicrohttpd_la_LIBADD += $(MHD_DLL_RES_LO) if USE_COVERAGE AM_CFLAGS += --coverage endif if !MHD_USE_SYS_TSEARCH libmicrohttpd_la_SOURCES += \ tsearch.c tsearch.h endif if HAVE_POSTPROCESSOR libmicrohttpd_la_SOURCES += \ postprocessor.c postprocessor.h endif if HAVE_ANYAUTH libmicrohttpd_la_SOURCES += \ gen_auth.c gen_auth.h endif if ENABLE_DAUTH libmicrohttpd_la_SOURCES += \ digestauth.c digestauth.h \ mhd_bithelpers.h mhd_byteorder.h mhd_align.h if ENABLE_MD5 libmicrohttpd_la_SOURCES += \ mhd_md5_wrap.h if ! ENABLE_MD5_EXT libmicrohttpd_la_SOURCES += \ md5.c md5.h else libmicrohttpd_la_SOURCES += \ md5_ext.c md5_ext.h endif endif if ENABLE_SHA256 libmicrohttpd_la_SOURCES += \ mhd_sha256_wrap.h if ! ENABLE_SHA256_EXT libmicrohttpd_la_SOURCES += \ sha256.c sha256.h else libmicrohttpd_la_SOURCES += \ sha256_ext.c sha256_ext.h endif endif if ENABLE_SHA512_256 libmicrohttpd_la_SOURCES += \ sha512_256.c sha512_256.h endif endif if ENABLE_BAUTH libmicrohttpd_la_SOURCES += \ basicauth.c basicauth.h endif if ENABLE_HTTPS libmicrohttpd_la_SOURCES += \ connection_https.c connection_https.h endif check_PROGRAMS = \ test_str_compare \ test_str_to_value \ test_str_from_value \ test_str_token \ test_str_token_remove \ test_str_tokens_remove \ test_str_pct \ test_str_bin_hex \ test_http_reasons \ test_sha1 \ test_start_stop \ test_daemon \ test_response_entries \ test_postprocessor_md \ test_client_put_shutdown \ test_client_put_close \ test_client_put_hard_close \ test_client_put_steps_shutdown \ test_client_put_steps_close \ test_client_put_steps_hard_close \ test_client_put_chunked_shutdown \ test_client_put_chunked_close \ test_client_put_chunked_hard_close \ test_client_put_chunked_steps_shutdown \ test_client_put_chunked_steps_close \ test_client_put_chunked_steps_hard_close \ test_options \ test_mhd_version \ test_set_panic if ENABLE_MD5 check_PROGRAMS += \ test_md5 endif if ENABLE_SHA256 check_PROGRAMS += \ test_sha256 endif if ENABLE_SHA512_256 check_PROGRAMS += \ test_sha512_256 endif if HAVE_POSIX_THREADS if ENABLE_UPGRADE if USE_THREADS check_PROGRAMS += test_upgrade test_upgrade_large test_upgrade_vlarge if ENABLE_HTTPS if USE_UPGRADE_TLS_TESTS check_PROGRAMS += test_upgrade_tls test_upgrade_large_tls test_upgrade_vlarge_tls endif endif endif endif endif if HAVE_POSTPROCESSOR check_PROGRAMS += \ test_postprocessor \ test_postprocessor_large \ test_postprocessor_amp endif # Do not test trigger of select by shutdown of listen socket # on Cygwin as this ability is deliberately ignored on Cygwin # to improve compatibility with core OS. if !CYGWIN_TARGET if HAVE_POSIX_THREADS if HAVE_LISTEN_SHUTDOWN check_PROGRAMS += \ test_shutdown_select \ test_shutdown_poll else check_PROGRAMS += \ test_shutdown_select_ignore \ test_shutdown_poll_ignore endif endif endif if HAVE_ANYAUTH if HAVE_MESSAGES check_PROGRAMS += \ test_auth_parse endif endif if ENABLE_DAUTH check_PROGRAMS += \ test_str_quote \ test_dauth_userdigest \ test_dauth_userhash endif if ENABLE_BAUTH check_PROGRAMS += \ test_str_base64 endif if HEAVY_TESTS if TESTS_STRESS_OS check_PROGRAMS += \ test_client_put_hard_close_stress_os \ test_client_put_steps_hard_close_stress_os \ test_client_put_chunked_steps_hard_close_stress_os endif endif TESTS = $(check_PROGRAMS) update-po-POTFILES.in: $(top_srcdir)/po/POTFILES.in $(top_srcdir)/po/POTFILES.in: $(srcdir)/Makefile.am @echo "Creating $@" @echo src/include/microhttpd.h > "$@" && \ for src in $(am__libmicrohttpd_la_SOURCES_DIST) ; do \ echo "$(subdir)/$$src" >> "$@" ; \ done test_start_stop_SOURCES = \ test_start_stop.c test_start_stop_LDADD = \ libmicrohttpd.la test_daemon_SOURCES = \ test_daemon.c test_daemon_LDADD = \ $(builddir)/libmicrohttpd.la test_response_entries_SOURCES = \ test_response_entries.c test_response_entries_LDADD = \ libmicrohttpd.la test_upgrade_SOURCES = \ test_upgrade.c test_helpers.h mhd_sockets.h test_upgrade_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_upgrade_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_upgrade_LDFLAGS = \ $(MHD_TLS_LIB_LDFLAGS) test_upgrade_LDADD = \ $(builddir)/libmicrohttpd.la \ $(MHD_TLS_LIBDEPS) \ $(PTHREAD_LIBS) test_upgrade_large_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_LDADD = \ $(test_upgrade_LDADD) test_upgrade_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_large_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_tls_LDADD = \ $(test_upgrade_LDADD) test_postprocessor_SOURCES = \ test_postprocessor.c test_postprocessor_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_amp_SOURCES = \ test_postprocessor_amp.c test_postprocessor_amp_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_amp_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_amp_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_large_SOURCES = \ test_postprocessor_large.c test_postprocessor_large_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_large_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_large_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_md_SOURCES = \ test_postprocessor_md.c postprocessor.h postprocessor.c \ internal.h internal.c mhd_str.h mhd_str.c \ mhd_panic.h mhd_panic.c test_postprocessor_md_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_shutdown_select_SOURCES = \ test_shutdown_select.c test_shutdown_select_CFLAGS = $(AM_CFLAGS) test_shutdown_select_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_select_CFLAGS += \ $(PTHREAD_CFLAGS) test_shutdown_select_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_poll_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_CFLAGS = $(AM_CFLAGS) test_shutdown_poll_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_poll_CFLAGS += \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_shutdown_poll_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_select_ignore_SOURCES = \ test_shutdown_select.c test_shutdown_select_ignore_CFLAGS = $(AM_CFLAGS) test_shutdown_select_ignore_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_select_ignore_CFLAGS += \ $(PTHREAD_CFLAGS) test_shutdown_select_ignore_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_poll_ignore_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_ignore_CFLAGS = $(AM_CFLAGS) test_shutdown_poll_ignore_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_poll_ignore_CFLAGS += \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_shutdown_poll_ignore_LDADD += \ $(PTHREAD_LIBS) endif test_str_compare_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_to_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_from_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_token_SOURCES = \ test_str_token.c mhd_str.c mhd_str.h test_str_token_remove_SOURCES = \ test_str_token_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_str_tokens_remove_SOURCES = \ test_str_tokens_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_http_reasons_SOURCES = \ test_http_reasons.c \ reason_phrase.c mhd_str.c mhd_str.h test_md5_SOURCES = \ test_md5.c test_helpers.h mhd_md5_wrap.h ../include/mhd_options.h if ! ENABLE_MD5_EXT test_md5_SOURCES += \ md5.c md5.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_md5_CPPFLAGS = $(AM_CPPFLAGS) test_md5_CFLAGS = $(AM_CFLAGS) test_md5_LDFLAGS = $(AM_LDFLAGS) test_md5_LDADD = $(LDADD) else test_md5_SOURCES += \ md5_ext.c md5_ext.h test_md5_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_md5_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_md5_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) test_md5_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) endif test_sha256_SOURCES = \ test_sha256.c test_helpers.h mhd_sha256_wrap.h ../include/mhd_options.h if ! ENABLE_SHA256_EXT test_sha256_SOURCES += \ sha256.c sha256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha256_CPPFLAGS = $(AM_CPPFLAGS) test_sha256_CFLAGS = $(AM_CFLAGS) test_sha256_LDFLAGS = $(AM_LDFLAGS) test_sha256_LDADD = $(LDADD) else test_sha256_SOURCES += \ sha256_ext.c sha256_ext.h test_sha256_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_sha256_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_sha256_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) test_sha256_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) endif test_sha512_256_SOURCES = \ test_sha512_256.c test_helpers.h \ sha512_256.c sha512_256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha1_SOURCES = \ test_sha1.c test_helpers.h \ sha1.c sha1.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_auth_parse_SOURCES = \ test_auth_parse.c gen_auth.c gen_auth.h mhd_str.h mhd_str.c mhd_assert.h test_auth_parse_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_str_quote_SOURCES = \ test_str_quote.c mhd_str.h mhd_str.c mhd_assert.h test_str_base64_SOURCES = \ test_str_base64.c mhd_str.h mhd_str.c mhd_assert.h test_str_pct_SOURCES = \ test_str_pct.c mhd_str.h mhd_str.c mhd_assert.h test_str_bin_hex_SOURCES = \ test_str_bin_hex.c mhd_str.h mhd_str.c mhd_assert.h test_options_SOURCES = \ test_options.c test_options_LDADD = \ $(builddir)/libmicrohttpd.la test_client_put_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_shutdown_LDADD = \ libmicrohttpd.la test_client_put_close_SOURCES = \ test_client_put_stop.c test_client_put_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_hard_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_stress_os_SOURCES = \ $(test_client_put_hard_close_SOURCES) test_client_put_hard_close_stress_os_LDADD = \ $(test_client_put_hard_close_LDADD) test_client_put_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_steps_hard_close_SOURCES) test_client_put_steps_hard_close_stress_os_LDADD = \ $(test_client_put_steps_hard_close_LDADD) test_client_put_chunked_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_chunked_steps_hard_close_SOURCES) test_client_put_chunked_steps_hard_close_stress_os_LDADD = \ $(test_client_put_chunked_steps_hard_close_LDADD) test_set_panic_SOURCES = \ test_set_panic.c test_set_panic_LDADD = \ libmicrohttpd.la test_dauth_userdigest_SOURCES = \ test_dauth_userdigest.c test_dauth_userdigest_LDADD = \ libmicrohttpd.la test_dauth_userhash_SOURCES = \ test_dauth_userhash.c test_dauth_userhash_LDADD = \ libmicrohttpd.la test_mhd_version_SOURCES = \ test_mhd_version.c test_mhd_version_LDADD = \ libmicrohttpd.la .PHONY: update-po-POTFILES.in libmicrohttpd-1.0.2/src/microhttpd/test_http_reasons.c0000644000175000017500000001161114760713574020175 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_http_reasons.c * @brief Unit tests for MHD_get_reason_phrase_for() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "microhttpd.h" #include "mhd_str.h" static const char *const r_unknown = "unknown"; /* Return zero when no error is detected */ static int expect_result (unsigned int code, const char *expected) { const char *const reason = MHD_get_reason_phrase_for (code); const size_t len = MHD_get_reason_phrase_len_for (code); size_t exp_len; if (! MHD_str_equal_caseless_ (reason, expected)) { fprintf (stderr, "Incorrect reason returned for code %u:\n Returned: \"%s\" \tExpected: \"%s\"\n", code, reason, expected); return 1; } if (r_unknown == expected) exp_len = 0; else exp_len = strlen (expected); if (exp_len != len) { fprintf (stderr, "Incorrect reason length returned for code %u:\n Returned: \"%u\" \tExpected: \"%u\"\n", code, (unsigned) len, (unsigned) exp_len); return 1; } return 0; } static int expect_absent (unsigned int code) { return expect_result (code, r_unknown); } static int test_absent_codes (void) { int errcount = 0; errcount += expect_absent (0); errcount += expect_absent (1); errcount += expect_absent (50); errcount += expect_absent (99); errcount += expect_absent (600); errcount += expect_absent (601); errcount += expect_absent (900); errcount += expect_absent (10000); return errcount; } static int test_1xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_CONTINUE, "continue"); errcount += expect_result (MHD_HTTP_PROCESSING, "processing"); errcount += expect_absent (110); errcount += expect_absent (190); return errcount; } static int test_2xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_OK, "ok"); errcount += expect_result (MHD_HTTP_ALREADY_REPORTED, "already reported"); errcount += expect_absent (217); errcount += expect_result (MHD_HTTP_IM_USED, "im used"); errcount += expect_absent (230); errcount += expect_absent (295); return errcount; } static int test_3xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_MULTIPLE_CHOICES, "multiple choices"); errcount += expect_result (MHD_HTTP_SEE_OTHER, "see other"); errcount += expect_result (MHD_HTTP_PERMANENT_REDIRECT, "permanent redirect"); errcount += expect_absent (311); errcount += expect_absent (399); return errcount; } static int test_4xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_BAD_REQUEST, "bad request"); errcount += expect_result (MHD_HTTP_NOT_FOUND, "not found"); errcount += expect_result (MHD_HTTP_URI_TOO_LONG, "uri too long"); errcount += expect_result (MHD_HTTP_EXPECTATION_FAILED, "expectation failed"); errcount += expect_result (MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, "request header fields too large"); errcount += expect_absent (441); errcount += expect_result (MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS, "unavailable for legal reasons"); errcount += expect_absent (470); errcount += expect_absent (493); return errcount; } static int test_5xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_INTERNAL_SERVER_ERROR, "internal server error"); errcount += expect_result (MHD_HTTP_BAD_GATEWAY, "bad gateway"); errcount += expect_result (MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, "http version not supported"); errcount += expect_result (MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED, "network authentication required"); errcount += expect_absent (520); errcount += expect_absent (597); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += test_absent_codes (); errcount += test_1xx (); errcount += test_2xx (); errcount += test_3xx (); errcount += test_4xx (); errcount += test_5xx (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.2/src/microhttpd/sha1.h0000644000175000017500000000527014760713577015275 00000000000000/* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.h * @brief Calculation of SHA-1 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA1_H #define MHD_SHA1_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * SHA-1 digest is kept internally as 5 32-bit words. */ #define _SHA1_DIGEST_LENGTH 5 /** * Number of bits in single SHA-1 word */ #define SHA1_WORD_SIZE_BITS 32 /** * Number of bytes in single SHA-1 word */ #define SHA1_BYTES_IN_WORD (SHA1_WORD_SIZE_BITS / 8) /** * Size of SHA-1 digest in bytes */ #define SHA1_DIGEST_SIZE (_SHA1_DIGEST_LENGTH * SHA1_BYTES_IN_WORD) /** * Size of SHA-1 digest string in chars including termination NUL */ #define SHA1_DIGEST_STRING_SIZE ((SHA1_DIGEST_SIZE) * 2 + 1) /** * Size of single processing block in bits */ #define SHA1_BLOCK_SIZE_BITS 512 /** * Size of single processing block in bytes */ #define SHA1_BLOCK_SIZE (SHA1_BLOCK_SIZE_BITS / 8) struct sha1_ctx { uint32_t H[_SHA1_DIGEST_LENGTH]; /**< Intermediate hash value / digest at end of calculation */ uint8_t buffer[SHA1_BLOCK_SIZE]; /**< SHA256 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for SHA-1 calculation. * * @param ctx_ must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_); /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length); /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]); #endif /* MHD_SHA1_H */ libmicrohttpd-1.0.2/src/Makefile.am0000644000175000017500000000070415035214363014125 00000000000000# This Makefile.am is in the public domain SUBDIRS = include microhttpd . if RUN_LIBCURL_TESTS SUBDIRS += testcurl if RUN_ZZUF_TESTS SUBDIRS += testzzuf endif endif # Finally (last!) also build experimental lib... if HAVE_EXPERIMENTAL SUBDIRS += microhttpd_ws endif if BUILD_EXAMPLES SUBDIRS += examples endif if BUILD_TOOLS SUBDIRS += tools endif EXTRA_DIST = \ datadir/cert-and-key.pem \ datadir/cert-and-key-for-wireshark.pem .NOTPARALLEL: libmicrohttpd-1.0.2/doc/0000755000175000017500000000000015035216653012132 500000000000000libmicrohttpd-1.0.2/doc/libmicrohttpd.30000644000175000017500000000312014674632555015011 00000000000000.Dd June 21, 2013 .Dt LIBMICROHTTPD 3 .Os .Sh NAME .Nm libmicrohttpd .Nd library for embedding HTTP servers .Sh LIBRARY .ds doc-str-Lb-libmicrohttpd library for embedding HTTP servers (libmicrohttpd) .Lb libmicrohttpd .Sh SYNOPSIS .In microhttpd.h .Sh DESCRIPTION GNU libmicrohttpd (short MHD) allows applications to easily integrate the functionality of a simple HTTP server. MHD is a GNU package. .sp The details of the API are described in comments in the header file, a detailed reference documentation in Texinfo, a tutorial, and in brief on the MHD webpage. .Sh LEGAL NOTICE libmicrohttpd is released under both the LGPL Version 2.1 or higher and the GNU GPL with eCos extension. For details on both licenses please read the respective appendix in the Texinfo manual. .Sh FILES .Bl -tag -width /etc/ttys -compact .It Pa microhttpd.h libmicrohttpd include file .It Pa libmicrohttpd.so libmicrohttpd library .El .Sh SEE ALSO .Xr curl 1 , .Xr libcurl 3 , info libmicrohttpd .Sh AUTHORS GNU .Nm was originally designed by .An -nosplit .An Christian Grothoff Aq Mt christian@grothoff.org and .An Chris GauthierDickey Aq Mt chrisg@cs.du.edu Ns . The original implementation was done by .An Daniel Pittman Aq Mt depittman@gmail.com and Christian Grothoff. SSL/TLS support was added by Sagie Amir using code from GnuTLS. See the AUTHORS file in the distribution for a more detailed list of contributors. .Sh AVAILABILITY You can obtain the latest version from .Lk https://www.gnu.org/software/libmicrohttpd/ Ns . .Sh BUGS Report bugs by using .Lk https://bugs.gnunet.org/set_project.php?project_id=10 "Mantis" Ns . libmicrohttpd-1.0.2/doc/libmicrohttpd-tutorial.info0000644000175000017500000063057714674636000017456 00000000000000This is libmicrohttpd-tutorial.info, produced by makeinfo version 6.8 from libmicrohttpd-tutorial.texi. This tutorial documents GNU libmicrohttpd version 0.9.48, last updated 2 April 2016. Copyright (c) 2008 Sebastian Gerhardt. Copyright (c) 2010, 2011, 2012, 2013, 2016, 2021 Christian Grothoff. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION Software libraries START-INFO-DIR-ENTRY * libmicrohttpdtutorial: (libmicrohttpd-tutorial). A tutorial for GNU libmicrohttpd. END-INFO-DIR-ENTRY  File: libmicrohttpd-tutorial.info, Node: Top, Next: Introduction, Up: (dir) A Tutorial for GNU libmicrohttpd ******************************** This tutorial documents GNU libmicrohttpd version 0.9.48, last updated 2 April 2016. Copyright (c) 2008 Sebastian Gerhardt. Copyright (c) 2010, 2011, 2012, 2013, 2016, 2021 Christian Grothoff. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". * Menu: * Introduction:: * Hello browser example:: * Exploring requests:: * Response headers:: * Supporting basic authentication:: * Processing POST data:: * Improved processing of POST data:: * Session management:: * Adding a layer of security:: * Websockets:: * Bibliography:: * License text:: * Example programs::  File: libmicrohttpd-tutorial.info, Node: Introduction, Next: Hello browser example, Prev: Top, Up: Top 1 Introduction ************** This tutorial is for developers who want to learn how they can add HTTP serving capabilities to their applications with the _GNU libmicrohttpd_ library, abbreviated _MHD_. The reader will learn how to implement basic HTTP functions from simple executable sample programs that implement various features. The text is supposed to be a supplement to the API reference manual of _GNU libmicrohttpd_ and for that reason does not explain many of the parameters. Therefore, the reader should always consult the manual to find the exact meaning of the functions used in the tutorial. Furthermore, the reader is encouraged to study the relevant _RFCs_, which document the HTTP standard. _GNU libmicrohttpd_ is assumed to be already installed. This tutorial is written for version 0.9.48. At the time being, this tutorial has only been tested on _GNU/Linux_ machines even though efforts were made not to rely on anything that would prevent the samples from being built on similar systems. 1.1 History =========== This tutorial was originally written by Sebastian Gerhardt for MHD 0.4.0. It was slightly polished and updated to MHD 0.9.0 by Christian Grothoff.  File: libmicrohttpd-tutorial.info, Node: Hello browser example, Next: Exploring requests, Prev: Introduction, Up: Top 2 Hello browser example *********************** The most basic task for a HTTP server is to deliver a static text message to any client connecting to it. Given that this is also easy to implement, it is an excellent problem to start with. For now, the particular URI the client asks for shall have no effect on the message that will be returned. In addition, the server shall end the connection after the message has been sent so that the client will know there is nothing more to expect. The C program 'hellobrowser.c', which is to be found in the examples section, does just that. If you are very eager, you can compile and start it right away but it is advisable to type the lines in by yourself as they will be discussed and explained in detail. After the necessary includes and the definition of the port which our server should listen on #include #include #include #include #define PORT 8888 the desired behaviour of our server when HTTP request arrive has to be implemented. We already have agreed that it should not care about the particular details of the request, such as who is requesting what. The server will respond merely with the same small HTML page to every request. The function we are going to write now will be called by _GNU libmicrohttpd_ every time an appropriate request comes in. While the name of this callback function is arbitrary, its parameter list has to follow a certain layout. So please, ignore the lot of parameters for now, they will be explained at the point they are needed. We have to use only one of them, 'struct MHD_Connection *connection', for the minimalistic functionality we want to achieve at the moment. This parameter is set by the _libmicrohttpd_ daemon and holds the necessary information to relate the call with a certain connection. Keep in mind that a server might have to satisfy hundreds of concurrent connections and we have to make sure that the correct data is sent to the destined client. Therefore, this variable is a means to refer to a particular connection if we ask the daemon to sent the reply. Talking about the reply, it is defined as a string right after the function header int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; HTTP is a rather strict protocol and the client would certainly consider it "inappropriate" if we just sent the answer string "as is". Instead, it has to be wrapped with additional information stored in so-called headers and footers. Most of the work in this area is done by the library for us--we just have to ask. Our reply string packed in the necessary layers will be called a "response". To obtain such a response we hand our data (the reply-string) and its size over to the 'MHD_create_response_from_buffer' function. The last two parameters basically tell _MHD_ that we do not want it to dispose the message data for us when it has been sent and there also needs no internal copy to be done because the _constant_ string won't change anyway. struct MHD_Response *response; int ret; response = MHD_create_response_from_buffer (strlen (page), (void*) page, MHD_RESPMEM_PERSISTENT); Now that the the response has been laced up, it is ready for delivery and can be queued for sending. This is done by passing it to another _GNU libmicrohttpd_ function. As all our work was done in the scope of one function, the recipient is without doubt the one associated with the local variable 'connection' and consequently this variable is given to the queue function. Every HTTP response is accompanied by a status code, here "OK", so that the client knows this response is the intended result of his request and not due to some error or malfunction. Finally, the packet is destroyed and the return value from the queue returned, already being set at this point to either MHD_YES or MHD_NO in case of success or failure. ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } With the primary task of our server implemented, we can start the actual server daemon which will listen on 'PORT' for connections. This is done in the main function. int main () { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; The first parameter is one of three possible modes of operation. Here we want the daemon to run in a separate thread and to manage all incoming connections in the same thread. This means that while producing the response for one connection, the other connections will be put on hold. In this example, where the reply is already known and therefore the request is served quickly, this poses no problem. We will allow all clients to connect regardless of their name or location, therefore we do not check them on connection and set the third and fourth parameter to NULL. Parameter five is the address of the function we want to be called whenever a new connection has been established. Our 'answer_to_connection' knows best what the client wants and needs no additional information (which could be passed via the next parameter) so the next (sixth) parameter is NULL. Likewise, we do not need to pass extra options to the daemon so we just write the MHD_OPTION_END as the last parameter. As the server daemon runs in the background in its own thread, the execution flow in our main function will continue right after the call. Because of this, we must delay the execution flow in the main thread or else the program will terminate prematurely. We let it pause in a processing-time friendly manner by waiting for the enter key to be pressed. In the end, we stop the daemon so it can do its cleanup tasks. getchar (); MHD_stop_daemon (daemon); return 0; } The first example is now complete. Compile it with cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd with the two paths set accordingly and run it. Now open your favorite Internet browser and go to the address 'http://localhost:8888/', provided that 8888 is the port you chose. If everything works as expected, the browser will present the message of the static HTML page it got from our minimal server. Remarks ======= To keep this first example as small as possible, some drastic shortcuts were taken and are to be discussed now. Firstly, there is no distinction made between the kinds of requests a client could send. We implied that the client sends a GET request, that means, that he actually asked for some data. Even when it is not intended to accept POST requests, a good server should at least recognize that this request does not constitute a legal request and answer with an error code. This can be easily implemented by checking if the parameter 'method' equals the string "GET" and returning a 'MHD_NO' if not so. Secondly, the above practice of queuing a response upon the first call of the callback function brings with it some limitations. This is because the content of the message body will not be received if a response is queued in the first iteration. Furthermore, the connection will be closed right after the response has been transferred then. This is typically not what you want as it disables HTTP pipelining. The correct approach is to simply not queue a message on the first callback unless there is an error. The 'void**' argument to the callback provides a location for storing information about the history of the connection; for the first call, the pointer will point to NULL. A simplistic way to differentiate the first call from others is to check if the pointer is NULL and set it to a non-NULL value during the first call. Both of these issues you will find addressed in the official 'minimal_example.c' residing in the 'src/examples' directory of the _MHD_ package. The source code of this program should look very familiar to you by now and easy to understand. For our example, we create the response from a static (persistent) buffer in memory and thus pass 'MHD_RESPMEM_PERSISTENT' to the response construction function. In the usual case, responses are not transmitted immediately after being queued. For example, there might be other data on the system that needs to be sent with a higher priority. Nevertheless, the queue function will return successfully--raising the problem that the data we have pointed to may be invalid by the time it is about being sent. This is not an issue here because we can expect the 'page' string, which is a constant _string literal_ here, to be static. That means it will be present and unchanged for as long as the program runs. For dynamic data, one could choose to either have _MHD_ free the memory 'page' points to itself when it is not longer needed (by passing 'MHD_RESPMEM_MUST_FREE') or, alternatively, have the library to make and manage its own copy of it (by passing 'MHD_RESPMEM_MUST_COPY'). Naturally, this last option is the most expensive. Exercises ========= * While the server is running, use a program like 'telnet' or 'netcat' to connect to it. Try to form a valid HTTP 1.1 request yourself like GET /dontcare HTTP/1.1 Host: itsme and see what the server returns to you. * Also, try other requests, like POST, and see how our server does not mind and why. How far in malforming a request can you go before the builtin functionality of _MHD_ intervenes and an altered response is sent? Make sure you read about the status codes in the _RFC_. * Add the option 'MHD_USE_PEDANTIC_CHECKS' to the start function of the daemon in 'main'. Mind the special format of the parameter list here which is described in the manual. How indulgent is the server now to your input? * Let the main function take a string as the first command line argument and pass 'argv[1]' to the 'MHD_start_daemon' function as the sixth parameter. The address of this string will be passed to the callback function via the 'cls' variable. Decorate the text given at the command line when the server is started with proper HTML tags and send it as the response instead of the former static string. * _Demanding:_ Write a separate function returning a string containing some useful information, for example, the time. Pass the function's address as the sixth parameter and evaluate this function on every request anew in 'answer_to_connection'. Remember to free the memory of the string every time after satisfying the request.  File: libmicrohttpd-tutorial.info, Node: Exploring requests, Next: Response headers, Prev: Hello browser example, Up: Top 3 Exploring requests ******************** This chapter will deal with the information which the client sends to the server at every request. We are going to examine the most useful fields of such an request and print them out in a readable manner. This could be useful for logging facilities. The starting point is the _hellobrowser_ program with the former response removed. This time, we just want to collect information in the callback function, thus we will just return MHD_NO after we have probed the request. This way, the connection is closed without much ado by the server. static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { ... return MHD_NO; } The ellipsis marks the position where the following instructions shall be inserted. We begin with the most obvious information available to the server, the request line. You should already have noted that a request consists of a command (or "HTTP method") and a URI (e.g. a filename). It also contains a string for the version of the protocol which can be found in 'version'. To call it a "new request" is justified because we return only 'MHD_NO', thus ensuring the function will not be called again for this connection. printf ("New %s request for %s using version %s\n", method, url, version); The rest of the information is a bit more hidden. Nevertheless, there is lot of it sent from common Internet browsers. It is stored in "key-value" pairs and we want to list what we find in the header. As there is no mandatory set of keys a client has to send, each key-value pair is printed out one by one until there are no more left. We do this by writing a separate function which will be called for each pair just like the above function is called for each HTTP request. It can then print out the content of this pair. int print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { printf ("%s: %s\n", key, value); return MHD_YES; } To start the iteration process that calls our new function for every key, the line MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL); needs to be inserted in the connection callback function too. The second parameter tells the function that we are only interested in keys from the general HTTP header of the request. Our iterating function 'print_out_key' does not rely on any additional information to fulfill its duties so the last parameter can be NULL. All in all, this constitutes the complete 'logging.c' program for this chapter which can be found in the 'examples' section. Connecting with any modern Internet browser should yield a handful of keys. You should try to interpret them with the aid of _RFC 2616_. Especially worth mentioning is the "Host" key which is often used to serve several different websites hosted under one single IP address but reachable by different domain names (this is called virtual hosting). Conclusion ========== The introduced capabilities to itemize the content of a simple GET request--especially the URI--should already allow the server to satisfy clients' requests for small specific resources (e.g. files) or even induce alteration of server state. However, the latter is not recommended as the GET method (including its header data) is by convention considered a "safe" operation, which should not change the server's state in a significant way. By convention, GET operations can thus be performed by crawlers and other automatic software. Naturally actions like searching for a passed string are fine. Of course, no transmission can occur while the return value is still set to 'MHD_NO' in the callback function. Exercises ========= * By parsing the 'url' string and delivering responses accordingly, implement a small server for "virtual" files. When asked for '/index.htm{l}', let the response consist of a HTML page containing a link to '/another.html' page which is also to be created "on the fly" in case of being requested. If neither of these two pages are requested, 'MHD_HTTP_NOT_FOUND' shall be returned accompanied by an informative message. * A very interesting information has still been ignored by our logger--the client's IP address. Implement a callback function static int on_client_connect (void *cls, const struct sockaddr *addr, socklen_t addrlen) that prints out the IP address in an appropriate format. You might want to use the POSIX function 'inet_ntoa' but bear in mind that 'addr' is actually just a structure containing other substructures and is _not_ the variable this function expects. Make sure to return 'MHD_YES' so that the library knows the client is allowed to connect (and to then process the request). If one wanted to limit access basing on IP addresses, this would be the place to do it. The address of your 'on_client_connect' function must be passed as the third parameter to the 'MHD_start_daemon' call.  File: libmicrohttpd-tutorial.info, Node: Response headers, Next: Supporting basic authentication, Prev: Exploring requests, Up: Top 4 Response headers ****************** Now that we are able to inspect the incoming request in great detail, this chapter discusses the means to enrich the outgoing responses likewise. As you have learned in the _Hello, Browser_ chapter, some obligatory header fields are added and set automatically for simple responses by the library itself but if more advanced features are desired, additional fields have to be created. One of the possible fields is the content type field and an example will be developed around it. This will lead to an application capable of correctly serving different types of files. When we responded with HTML page packed in the static string previously, the client had no choice but guessing about how to handle the response, because the server had not told him. What if we had sent a picture or a sound file? Would the message have been understood or merely been displayed as an endless stream of random characters in the browser? This is what the mime content types are for. The header of the response is extended by certain information about how the data is to be interpreted. To introduce the concept, a picture of the format _PNG_ will be sent to the client and labeled accordingly with 'image/png'. Once again, we can base the new example on the 'hellobrowser' program. #define FILENAME "picture.png" #define MIMETYPE "image/png" static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { unsigned char *buffer = NULL; struct MHD_Response *response; We want the program to open the file for reading and determine its size: int fd; int ret; struct stat sbuf; if (0 != strcmp (method, "GET")) return MHD_NO; if ( (-1 == (fd = open (FILENAME, O_RDONLY))) || (0 != fstat (fd, &sbuf)) ) { /* error accessing file */ /* ... (see below) */ } /* ... (see below) */ When dealing with files, there is a lot that could go wrong on the server side and if so, the client should be informed with 'MHD_HTTP_INTERNAL_SERVER_ERROR'. /* error accessing file */ if (fd != -1) close (fd); const char *errorstr = "An internal server error has occurred!\ "; response = MHD_create_response_from_buffer (strlen (errorstr), (void *) errorstr, MHD_RESPMEM_PERSISTENT); if (response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return MHD_YES; } else return MHD_NO; if (!ret) { const char *errorstr = "An internal server error has occurred!\ "; if (buffer) free(buffer); response = MHD_create_response_from_buffer (strlen(errorstr), (void*) errorstr, MHD_RESPMEM_PERSISTENT); if (response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return MHD_YES; } else return MHD_NO; } Note that we nevertheless have to create a response object even for sending a simple error code. Otherwise, the connection would just be closed without comment, leaving the client curious about what has happened. But in the case of success a response will be constructed directly from the file descriptor: /* error accessing file */ /* ... (see above) */ } response = MHD_create_response_from_fd_at_offset (sbuf.st_size, fd, 0); MHD_add_response_header (response, "Content-Type", MIMETYPE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); Note that the response object will take care of closing the file descriptor for us. Up to this point, there was little new. The actual novelty is that we enhance the header with the meta data about the content. Aware of the field's name we want to add, it is as easy as that: MHD_add_response_header(response, "Content-Type", MIMETYPE); We do not have to append a colon expected by the protocol behind the first field--_GNU libhttpdmicro_ will take care of this. The function finishes with the well-known lines ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } The complete program 'responseheaders.c' is in the 'examples' section as usual. Find a _PNG_ file you like and save it to the directory the example is run from under the name 'picture.png'. You should find the image displayed on your browser if everything worked well. Remarks ======= The include file of the _MHD_ library comes with the header types mentioned in _RFC 2616_ already defined as macros. Thus, we could have written 'MHD_HTTP_HEADER_CONTENT_TYPE' instead of '"Content-Type"' as well. However, one is not limited to these standard headers and could add custom response headers without violating the protocol. Whether, and how, the client would react to these custom header is up to the receiver. Likewise, the client is allowed to send custom request headers to the server as well, opening up yet more possibilities how client and server could communicate with each other. The method of creating the response from a file on disk only works for static content. Serving dynamically created responses will be a topic of a future chapter. Exercises ========= * Remember that the original program was written under a few assumptions--a static response using a local file being one of them. In order to simulate a very large or hard to reach file that cannot be provided instantly, postpone the queuing in the callback with the 'sleep' function for 30 seconds _if_ the file '/big.png' is requested (but deliver the same as above). A request for '/picture.png' should provide just the same but without any artificial delays. Now start two instances of your browser (or even use two machines) and see how the second client is put on hold while the first waits for his request on the slow file to be fulfilled. Finally, change the sourcecode to use 'MHD_USE_THREAD_PER_CONNECTION' when the daemon is started and try again. * Did you succeed in implementing the clock exercise yet? This time, let the server save the program's start time 't' and implement a response simulating a countdown that reaches 0 at 't+60'. Returning a message saying on which point the countdown is, the response should ultimately be to reply "Done" if the program has been running long enough, An unofficial, but widely understood, response header line is 'Refresh: DELAY; url=URL' with the uppercase words substituted to tell the client it should request the given resource after the given delay again. Improve your program in that the browser (any modern browser should work) automatically reconnects and asks for the status again every 5 seconds or so. The URL would have to be composed so that it begins with "http://", followed by the _URI_ the server is reachable from the client's point of view. Maybe you want also to visualize the countdown as a status bar by creating a '' consisting of one row and 'n' columns whose fields contain small images of either a red or a green light.  File: libmicrohttpd-tutorial.info, Node: Supporting basic authentication, Next: Processing POST data, Prev: Response headers, Up: Top 5 Supporting basic authentication ********************************* With the small exception of IP address based access control, requests from all connecting clients where served equally until now. This chapter discusses a first method of client's authentication and its limits. A very simple approach feasible with the means already discussed would be to expect the password in the _URI_ string before granting access to the secured areas. The password could be separated from the actual resource identifier by a certain character, thus the request line might look like GET /picture.png?mypassword In the rare situation where the client is customized enough and the connection occurs through secured lines (e.g., a embedded device directly attached to another via wire) and where the ability to embed a password in the URI or to pass on a URI with a password are desired, this can be a reasonable choice. But when it is assumed that the user connecting does so with an ordinary Internet browser, this implementation brings some problems about. For example, the URI including the password stays in the address field or at least in the history of the browser for anybody near enough to see. It will also be inconvenient to add the password manually to any new URI when the browser does not know how to compose this automatically. At least the convenience issue can be addressed by employing the simplest built-in password facilities of HTTP compliant browsers, hence we want to start there. It will, however, turn out to have still severe weaknesses in terms of security which need consideration. Before we will start implementing _Basic Authentication_ as described in _RFC 2617_, we will also abandon the simplistic and generally problematic practice of responding every request the first time our callback is called for a given connection. Queuing a response upon the first request is akin to generating an error response (even if it is a "200 OK" reply!). The reason is that MHD usually calls the callback in three phases: 1. First, to initially tell the application about the connection and inquire whether it is OK to proceed. This call typically happens before the client could upload the request body, and can be used to tell the client to not proceed with the upload (if the client requested "Expect: 100 Continue"). Applications may queue a reply at this point, but it will force the connection to be closed and thus prevent keep-alive / pipelining, which is generally a bad idea. Applications wanting to proceed with the request throughout the other phases should just return "MHD_YES" and not queue any response. Note that when an application suspends a connection in this callback, the phase does not advance and the application will be called again in this first phase. 2. Next, to tell the application about upload data provided by the client. In this phase, the application may not queue replies, and trying to do so will result in MHD returning an error code from 'MHD_queue_response'. If there is no upload data, this phase is skipped. 3. Finally, to obtain a regular response from the application. This can be almost any type of response, including ones indicating failures. The one exception is a "100 Continue" response, which applications must never generate: MHD generates that response automatically when necessary in the first phase. If the application does not queue a response, MHD may call the callback repeatedly (depending a bit on the threading model, the application should suspend the connection). But how can we tell whether the callback has been called before for the particular request? Initially, the pointer this parameter references is set by _MHD_ in the callback. But it will also be "remembered" on the next call (for the same request). Thus, we can use the 'req_cls' location to keep track of the request state. For now, we will simply generate no response until the parameter is non-null--implying the callback was called before at least once. We do not need to share information between different calls of the callback, so we can set the parameter to any address that is assured to be not null. The pointer to the 'connection' structure will be pointing to a legal address, so we take this. The first time 'answer_to_connection' is called, we will not even look at the headers. static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (0 != strcmp(method, "GET")) return MHD_NO; if (NULL == *req_cls) {*req_cls = connection; return MHD_YES;} ... /* else respond accordingly */ ... } Note how we lop off the connection on the first condition (no "GET" request), but return asking for more on the other one with 'MHD_YES'. With this minor change, we can proceed to implement the actual authentication process. Request for authentication ========================== Let us assume we had only files not intended to be handed out without the correct username/password, so every "GET" request will be challenged. _RFC 7617_ describes how the server shall ask for authentication by adding a _WWW-Authenticate_ response header with the name of the _realm_ protected. MHD can generate and queue such a failure response for you using the 'MHD_queue_basic_auth_fail_response' API. The only thing you need to do is construct a response with the error page to be shown to the user if he aborts basic authentication. But first, you should check if the proper credentials were already supplied using the 'MHD_basic_auth_get_username_password' call. Your code would then look like this: static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_fail_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_fail_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } See the 'examples' directory for the complete example file. Remarks ======= For a proper server, the conditional statements leading to a return of 'MHD_NO' should yield a response with a more precise status code instead of silently closing the connection. For example, failures of memory allocation are best reported as _internal server error_ and unexpected authentication methods as _400 bad request_. Exercises ========= * Make the server respond to wrong credentials (but otherwise well-formed requests) with the recommended _401 unauthorized_ status code. If the client still does not authenticate correctly within the same connection, close it and store the client's IP address for a certain time. (It is OK to check for expiration not until the main thread wakes up again on the next connection.) If the client fails authenticating three times during this period, add it to another list for which the 'AcceptPolicyCallback' function denies connection (temporally). * With the network utility 'netcat' connect and log the response of a "GET" request as you did in the exercise of the first example, this time to a file. Now stop the server and let _netcat_ listen on the same port the server used to listen on and have it fake being the proper server by giving the file's content as the response (e.g. 'cat log | nc -l -p 8888'). Pretending to think your were connecting to the actual server, browse to the eavesdropper and give the correct credentials. Copy and paste the encoded string you see in 'netcat''s output to some of the Base64 decode tools available online and see how both the user's name and password could be completely restored.  File: libmicrohttpd-tutorial.info, Node: Processing POST data, Next: Improved processing of POST data, Prev: Supporting basic authentication, Up: Top 6 Processing POST data ********************** The previous chapters already have demonstrated a variety of possibilities to send information to the HTTP server, but it is not recommended that the _GET_ method is used to alter the way the server operates. To induce changes on the server, the _POST_ method is preferred over and is much more powerful than _GET_ and will be introduced in this chapter. We are going to write an application that asks for the visitor's name and, after the user has posted it, composes an individual response text. Even though it was not mandatory to use the _POST_ method here, as there is no permanent change caused by the POST, it is an illustrative example on how to share data between different functions for the same connection. Furthermore, the reader should be able to extend it easily. GET request =========== When the first _GET_ request arrives, the server shall respond with a HTML page containing an edit field for the name. const char* askpage = "\ What's your name, Sir?
    \ \ \ "; The 'action' entry is the _URI_ to be called by the browser when posting, and the 'name' will be used later to be sure it is the editbox's content that has been posted. We also prepare the answer page, where the name is to be filled in later, and an error page as the response for anything but proper _GET_ and _POST_ requests: const char* greatingpage="

    Welcome, %s!

    "; const char* errorpage="This doesn't seem to be right."; Whenever we need to send a page, we use an extra function 'int send_page(struct MHD_Connection *connection, const char* page)' for this, which does not contain anything new and whose implementation is therefore not discussed further in the tutorial. POST request ============ Posted data can be of arbitrary and considerable size; for example, if a user uploads a big image to the server. Similar to the case of the header fields, there may also be different streams of posted data, such as one containing the text of an editbox and another the state of a button. Likewise, we will have to register an iterator function that is going to be called maybe several times not only if there are different POSTs but also if one POST has only been received partly yet and needs processing before another chunk can be received. Such an iterator function is called by a _postprocessor_, which must be created upon arriving of the post request. We want the iterator function to read the first post data which is tagged 'name' and to create an individual greeting string based on the template and the name. But in order to pass this string to other functions and still be able to differentiate different connections, we must first define a structure to share the information, holding the most import entries. struct connection_info_struct { int connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; With these information available to the iterator function, it is able to fulfill its task. Once it has composed the greeting string, it returns 'MHD_NO' to inform the post processor that it does not need to be called again. Note that this function does not handle processing of data for the same 'key'. If we were to expect that the name will be posted in several chunks, we had to expand the namestring dynamically as additional parts of it with the same 'key' came in. But in this example, the name is assumed to fit entirely inside one single packet. static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; if (0 == strcmp (key, "name")) { if ((size > 0) && (size <= MAXNAMESIZE)) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (!answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, greatingpage, data); con_info->answerstring = answerstring; } else con_info->answerstring = NULL; return MHD_NO; } return MHD_YES; } Once a connection has been established, it can be terminated for many reasons. As these reasons include unexpected events, we have to register another function that cleans up any resources that might have been allocated for that connection by us, namely the post processor and the greetings string. This cleanup function must take into account that it will also be called for finished requests other than _POST_ requests. void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } _GNU libmicrohttpd_ is informed that it shall call the above function when the daemon is started in the main function. ... daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); ... Request handling ================ With all other functions prepared, we can now discuss the actual request handling. On the first iteration for a new request, we start by allocating a new instance of a 'struct connection_info_struct' structure, which will store all necessary information for later iterations and other functions. static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if(NULL == *req_cls) { struct connection_info_struct *con_info; con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; If the new request is a _POST_, the postprocessor must be created now. In addition, the type of the request is stored for convenience. if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else con_info->connectiontype = GET; The address of our structure will both serve as the indicator for successive iterations and to remember the particular details about the connection. *req_cls = (void*) con_info; return MHD_YES; } The rest of the function will not be executed on the first iteration. A _GET_ request is easily satisfied by sending the question form. if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } In case of _POST_, we invoke the post processor for as long as data keeps incoming, setting '*upload_data_size' to zero in order to indicate that we have processed--or at least have considered--all of it. if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (*upload_data_size != 0) { MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } Finally, if they are neither _GET_ nor _POST_ requests, the error page is returned. return send_page(connection, errorpage); } These were the important parts of the program 'simplepost.c'.  File: libmicrohttpd-tutorial.info, Node: Improved processing of POST data, Next: Session management, Prev: Processing POST data, Up: Top 7 Improved processing of POST data ********************************** The previous chapter introduced a way to upload data to the server, but the developed example program has some shortcomings, such as not being able to handle larger chunks of data. In this chapter, we are going to discuss a more advanced server program that allows clients to upload a file in order to have it stored on the server's filesystem. The server shall also watch and limit the number of clients concurrently uploading, responding with a proper busy message if necessary. Prepared answers ================ We choose to operate the server with the 'SELECT_INTERNALLY' method. This makes it easier to synchronize the global states at the cost of possible delays for other connections if the processing of a request is too slow. One of these variables that needs to be shared for all connections is the total number of clients that are uploading. #define MAXCLIENTS 2 static unsigned int nr_of_uploading_clients = 0; If there are too many clients uploading, we want the server to respond to all requests with a busy message. const char* busypage = "This server is busy, please try again later."; Otherwise, the server will send a _form_ that informs the user of the current number of uploading clients, and ask her to pick a file on her local filesystem which is to be uploaded. const char* askpage = "\n\ Upload a file, please!
    \n\ There are %u clients uploading at the moment.
    \n\ \n\ \n\ \n\ "; If the upload has succeeded, the server will respond with a message saying so. const char* completepage = "The upload has been completed."; We want the server to report internal errors, such as memory shortage or file access problems, adequately. const char* servererrorpage = "An internal server error has occurred."; const char* fileexistspage = "This file already exists."; It would be tolerable to send all these responses undifferentiated with a '200 HTTP_OK' status code but in order to improve the 'HTTP' conformance of our server a bit, we extend the 'send_page' function so that it accepts individual status codes. static int send_page (struct MHD_Connection *connection, const char* page, int status_code) { int ret; struct MHD_Response *response; response = MHD_create_response_from_buffer (strlen (page), (void*) page, MHD_RESPMEM_MUST_COPY); if (!response) return MHD_NO; ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } Note how we ask _MHD_ to make its own copy of the message data. The reason behind this will become clear later. Connection cycle ================ The decision whether the server is busy or not is made right at the beginning of the connection. To do that at this stage is especially important for _POST_ requests because if no response is queued at this point, and 'MHD_YES' returned, _MHD_ will not sent any queued messages until a postprocessor has been created and the post iterator is called at least once. static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (NULL == *req_cls) { struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page(connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); If the server is not busy, the 'connection_info' structure is initialized as usual, with the addition of a filepointer for each connection. con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->fp = 0; if (0 == strcmp (method, "POST")) { ... } else con_info->connectiontype = GET; *req_cls = (void*) con_info; return MHD_YES; } For _POST_ requests, the postprocessor is created and we register a new uploading client. From this point on, there are many possible places for errors to occur that make it necessary to interrupt the uploading process. We need a means of having the proper response message ready at all times. Therefore, the 'connection_info' structure is extended to hold the most current response message so that whenever a response is sent, the client will get the most informative message. Here, the structure is initialized to "no error". if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; con_info->answercode = MHD_HTTP_OK; con_info->answerstring = completepage; } else con_info->connectiontype = GET; If the connection handler is called for the second time, _GET_ requests will be answered with the _form_. We can keep the buffer under function scope, because we asked _MHD_ to make its own copy of it for as long as it is needed. if (0 == strcmp (method, "GET")) { int ret; char buffer[1024]; sprintf (buffer, askpage, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } The rest of the 'answer_to_connection' function is very similar to the 'simplepost.c' example, except the more flexible content of the responses. The _POST_ data is processed until there is none left and the execution falls through to return an error page if the connection constituted no expected request method. if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else return send_page (connection, con_info->answerstring, con_info->answercode); } return send_page(connection, errorpage, MHD_HTTP_BAD_REQUEST); } Storing to data =============== Unlike the 'simplepost.c' example, here it is to be expected that post iterator will be called several times now. This means that for any given connection (there might be several concurrent of them) the posted data has to be written to the correct file. That is why we store a file handle in every 'connection_info', so that the it is preserved between successive iterations. static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; Because the following actions depend heavily on correct file processing, which might be error prone, we default to reporting internal errors in case anything will go wrong. con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; In the "askpage" _form_, we told the client to label its post data with the "file" key. Anything else would be an error. if (0 != strcmp (key, "file")) return MHD_NO; If the iterator is called for the first time, no file will have been opened yet. The 'filename' string contains the name of the file (without any paths) the user selected on his system. We want to take this as the name the file will be stored on the server and make sure no file of that name exists (or is being uploaded) before we create one (note that the code below technically contains a race between the two "fopen" calls, but we will overlook this for portability sake). if (!con_info->fp) { if (NULL != (fp = fopen (filename, "rb")) ) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_NO; } con_info->fp = fopen (filename, "ab"); if (!con_info->fp) return MHD_NO; } Occasionally, the iterator function will be called even when there are 0 new bytes to process. The server only needs to write data to the file if there is some. if (size > 0) { if (!fwrite (data, size, sizeof(char), con_info->fp)) return MHD_NO; } If this point has been reached, everything worked well for this iteration and the response can be set to success again. If the upload has finished, this iterator function will not be called again. con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; return MHD_YES; } The new client was registered when the postprocessor was created. Likewise, we unregister the client on destroying the postprocessor when the request is completed. void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } This is essentially the whole example 'largepost.c'. Remarks ======= Now that the clients are able to create files on the server, security aspects are becoming even more important than before. Aside from proper client authentication, the server should always make sure explicitly that no files will be created outside of a dedicated upload directory. In particular, filenames must be checked to not contain strings like "../".  File: libmicrohttpd-tutorial.info, Node: Session management, Next: Adding a layer of security, Prev: Improved processing of POST data, Up: Top 8 Session management ******************** This chapter discusses how one should manage sessions, that is, share state between multiple HTTP requests from the same user. We use a simple example where the user submits multiple forms and the server is supposed to accumulate state from all of these forms. Naturally, as this is a network protocol, our session mechanism must support having many users with many concurrent sessions at the same time. In order to track users, we use a simple session cookie. A session cookie expires when the user closes the browser. Changing from session cookies to persistent cookies only requires adding an expiration time to the cookie. The server creates a fresh session cookie whenever a request without a cookie is received, or if the supplied session cookie is not known to the server. Looking up the cookie ===================== Since MHD parses the HTTP cookie header for us, looking up an existing cookie is straightforward: const char *value; value = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "KEY"); Here, "KEY" is the name we chose for our session cookie. Setting the cookie header ========================= MHD requires the user to provide the full cookie format string in order to set cookies. In order to generate a unique cookie, our example creates a random 64-character text string to be used as the value of the cookie: char value[128]; char raw_value[65]; for (unsigned int i=0;i openssl genrsa -out server.key 1024 In addition to the key, a certificate describing the server in human readable tokens is also needed. This certificate will be attested with our aforementioned key. In this way, we obtain a self-signed certificate, valid for one year. > openssl req -days 365 -out server.pem -new -x509 -key server.key To avoid unnecessary error messages in the browser, the certificate needs to have a name that matches the _URI_, for example, "localhost" or the domain. If you plan to have a publicly reachable server, you will need to ask a trusted third party, called _Certificate Authority_, or _CA_, to attest the certificate for you. This way, any visitor can make sure the server's identity is real. Whether the server's certificate is signed by us or a third party, once it has been accepted by the client, both sides will be communicating over encrypted channels. From this point on, it is the client's turn to authenticate itself. But this has already been implemented in the basic authentication scheme. Changing the source code ======================== We merely have to extend the server program so that it loads the two files into memory, int main () { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); return 1; } and then we point the _MHD_ daemon to it upon initialization. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } The rest consists of little new besides some additional memory cleanups. getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; } The rather unexciting file loader can be found in the complete example 'tlsauthentication.c'. Remarks ======= * While the standard _HTTP_ port is 80, it is 443 for _HTTPS_. The common internet browsers assume standard _HTTP_ if they are asked to access other ports than these. Therefore, you will have to type 'https://localhost:8888' explicitly when you test the example, or the browser will not know how to handle the answer properly. * The remaining weak point is the question how the server will be trusted initially. Either a _CA_ signs the certificate or the client obtains the key over secure means. Anyway, the clients have to be aware (or configured) that they should not accept certificates of unknown origin. * The introduced method of certificates makes it mandatory to set an expiration date--making it less feasible to hardcode certificates in embedded devices. * The cryptographic facilities consume memory space and computing time. For this reason, websites usually consists both of uncritically _HTTP_ parts and secured _HTTPS_. Client authentication ===================== You can also use MHD to authenticate the client via SSL/TLS certificates (as an alternative to using the password-based Basic or Digest authentication). To do this, you will need to link your application against _gnutls_. Next, when you start the MHD daemon, you must specify the root CA that you're willing to trust: daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem, MHD_OPTION_END); With this, you can then obtain client certificates for each session. In order to obtain the identity of the client, you first need to obtain the raw GnuTLS session handle from _MHD_ using 'MHD_get_connection_info'. #include #include gnutls_session_t tls_session; union MHD_ConnectionInfo *ci; ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_SESSION); tls_session = (gnutls_session_t) ci->tls_session; You can then extract the client certificate: /** * Get the client's certificate * * @param tls_session the TLS session * @return NULL if no valid client certificate could be found, a pointer * to the certificate if found */ static gnutls_x509_crt_t get_client_certificate (gnutls_session_t tls_session) { unsigned int listsize; const gnutls_datum_t * pcert; gnutls_certificate_status_t client_cert_status; gnutls_x509_crt_t client_cert; if (tls_session == NULL) return NULL; if (gnutls_certificate_verify_peers2(tls_session, &client_cert_status)) return NULL; if (0 != client_cert_status) { fprintf (stderr, "Failed client certificate invalid: %d\n", client_cert_status); return NULL; } pcert = gnutls_certificate_get_peers(tls_session, &listsize); if ( (pcert == NULL) || (listsize == 0)) { fprintf (stderr, "Failed to retrieve client certificate chain\n"); return NULL; } if (gnutls_x509_crt_init(&client_cert)) { fprintf (stderr, "Failed to initialize client certificate\n"); return NULL; } /* Note that by passing values between 0 and listsize here, you can get access to the CA's certs */ if (gnutls_x509_crt_import(client_cert, &pcert[0], GNUTLS_X509_FMT_DER)) { fprintf (stderr, "Failed to import client certificate\n"); gnutls_x509_crt_deinit(client_cert); return NULL; } return client_cert; } Using the client certificate, you can then get the client's distinguished name and alternative names: /** * Get the distinguished name from the client's certificate * * @param client_cert the client certificate * @return NULL if no dn or certificate could be found, a pointer * to the dn if found */ char * cert_auth_get_dn(gnutls_x509_crt_t client_cert) { char* buf; size_t lbuf; lbuf = 0; gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf); buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate dn\n"); return NULL; } gnutls_x509_crt_get_dn(client_cert, buf, &lbuf); return buf; } /** * Get the alternative name of specified type from the client's certificate * * @param client_cert the client certificate * @param nametype The requested name type * @param index The position of the alternative name if multiple names are * matching the requested type, 0 for the first matching name * @return NULL if no matching alternative name could be found, a pointer * to the alternative name if found */ char * MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert, int nametype, unsigned int index) { char* buf; size_t lbuf; unsigned int seq; unsigned int subseq; unsigned int type; int result; subseq = 0; for (seq=0;;seq++) { lbuf = 0; result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf, &type, NULL); if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) return NULL; if (nametype != (int) type) continue; if (subseq == index) break; subseq++; } buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate alt name\n"); return NULL; } result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, buf, &lbuf, NULL, NULL); if (result != nametype) { fprintf (stderr, "Unexpected return value from gnutls: %d\n", result); free (buf); return NULL; } return buf; } Finally, you should release the memory associated with the client certificate: gnutls_x509_crt_deinit (client_cert); Using TLS Server Name Indication (SNI) ====================================== SNI enables hosting multiple domains under one IP address with TLS. So SNI is the TLS-equivalent of virtual hosting. To use SNI with MHD, you need at least GnuTLS 3.0. The main change compared to the simple hosting of one domain is that you need to provide a callback instead of the key and certificate. For example, when you start the MHD daemon, you could do this: daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); Here, 'sni_callback' is the name of a function that you will have to implement to retrieve the X.509 certificate for an incoming connection. The callback has type 'gnutls_certificate_retrieve_function2' and is documented in the GnuTLS API for the 'gnutls_certificate_set_retrieve_function2' as follows: -- Function Pointer: int *gnutls_certificate_retrieve_function2 (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) REQ_CA_CERT is only used in X.509 certificates. Contains a list with the CA names that the server considers trusted. Normally we should send a certificate that is signed by one of these CAs. These names are DER encoded. To get a more meaningful value use the function 'gnutls_x509_rdn_get()'. PK_ALGOS contains a list with server’s acceptable signature algorithms. The certificate returned should support the server’s given algorithms. PCERT should contain a single certificate and public or a list of them. PCERT_LENGTH is the size of the previous list. PKEY is the private key. A possible implementation of this callback would look like this: struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; static struct Hosts *hosts; int sni_callback (gnutls_session_t session, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } Note that MHD cannot offer passing a closure or any other additional information to this callback, as the GnuTLS API unfortunately does not permit this at this point. The 'hosts' list can be initialized by loading the private keys and X.509 certificates from disk as follows: static void load_keys(const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit(1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf(stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit(1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); } The code above was largely lifted from GnuTLS. You can find other methods for initializing certificates and keys in the GnuTLS manual and source code.  File: libmicrohttpd-tutorial.info, Node: Websockets, Next: Bibliography, Prev: Adding a layer of security, Up: Top 10 Websockets ************* Websockets are a genuine way to implement push notifications, where the server initiates the communication while the client can be idle. Usually a HTTP communication is half-duplex and always requested by the client, but websockets are full-duplex and only initialized by the client. In the further communication both sites can use the websocket at any time to send data to the other site. To initialize a websocket connection the client sends a special HTTP request to the server and initializes a handshake between client and server which switches from the HTTP protocol to the websocket protocol. Thus both the server as well as the client must support websockets. If proxys are used, they must support websockets too. In this chapter we take a look on server and client, but with a focus on the server with _libmicrohttpd_. Since version 0.9.52 _libmicrohttpd_ supports upgrading requests, which is required for switching from the HTTP protocol. Since version 0.9.74 the library _libmicrohttpd_ws_ has been added to support the websocket protocol. Upgrading connections with libmicrohttpd ======================================== To support websockets we need to enable upgrading of HTTP connections first. This is done by passing the flag 'MHD_ALLOW_UPGRADE' to 'MHD_start_daemon()'. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_ALLOW_UPGRADE | MHD_USE_ERROR_LOG, PORT, NULL, NULL, &access_handler, NULL, MHD_OPTION_END); The next step is to turn a specific request into an upgraded connection. This done in our 'access_handler' by calling 'MHD_create_response_for_upgrade()'. An 'upgrade_handler' will be passed to perform the low-level actions on the socket. _Please note that the socket here is just a regular socket as provided by the operating system. To use it as a websocket, some more steps from the following chapters are required._ static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { /* ... */ /* some code to decide whether to upgrade or not */ /* ... */ /* create the response for upgrade */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); /* ... */ /* additional headers, etc. */ /* ... */ ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); return ret; } In the 'upgrade_handler' we receive the low-level socket, which is used for the communication with the specific client. In addition to the low-level socket we get: * Some data, which has been read too much while _libmicrohttpd_ was switching the protocols. This value is usually empty, because it would mean that the client has sent data before the handshake was complete. * A 'struct MHD_UpgradeResponseHandle' which is used to perform special actions like closing, corking or uncorking the socket. These commands are executed by passing the handle to 'MHD_upgrade_action()'. Depending of the flags specified while calling 'MHD_start_deamon()' our 'upgrade_handler' is either executed in the same thread as our daemon or in a thread specific for each connection. If it is executed in the same thread then 'upgrade_handler' is a blocking call for our webserver and we should finish it as fast as possible (i. e. by creating a thread and passing the information there). If 'MHD_USE_THREAD_PER_CONNECTION' was passed to 'MHD_start_daemon()' then a separate thread is used and thus our 'upgrade_handler' needs not to start a separate thread. An 'upgrade_handler', which is called with a separate thread per connection, could look like this: static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { /* ... */ /* do something with the socket `fd` like `recv()` or `send()` */ /* ... */ /* close the socket when it is not needed anymore */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } This is all you need to know for upgrading connections with _libmicrohttpd_. The next chapters focus on using the websocket protocol with _libmicrohttpd_ws_. Websocket handshake with libmicrohttpd_ws ========================================= To request a websocket connection the client must send the following information with the HTTP request: * A 'GET' request must be sent. * The version of the HTTP protocol must be 1.1 or higher. * A 'Host' header field must be sent * A 'Upgrade' header field containing the keyword "websocket" (case-insensitive). Please note that the client could pass multiple protocols separated by comma. * A 'Connection' header field that includes the token "Upgrade" (case-insensitive). Please note that the client could pass multiple tokens separated by comma. * A 'Sec-WebSocket-Key' header field with a base64-encoded value. The decoded the value is 16 bytes long and has been generated randomly by the client. * A 'Sec-WebSocket-Version' header field with the value "13". Optionally the client can also send the following information: * A 'Origin' header field can be used to determine the source of the client (i. e. the website). * A 'Sec-WebSocket-Protocol' header field can contain a list of supported protocols by the client, which can be sent over the websocket. * A 'Sec-WebSocket-Extensions' header field which may contain extensions to the websocket protocol. The extensions must be registered by IANA. A valid example request from the client could look like this: GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 To complete the handshake the server must respond with some specific response headers: * The HTTP response code '101 Switching Protocols' must be answered. * An 'Upgrade' header field containing the value "websocket" must be sent. * A 'Connection' header field containing the value "Upgrade" must be sent. * A 'Sec-WebSocket-Accept' header field containing a value, which has been calculated from the 'Sec-WebSocket-Key' request header field, must be sent. Optionally the server may send following headers: * A 'Sec-WebSocket-Protocol' header field containing a protocol of the list specified in the corresponding request header field. * A 'Sec-WebSocket-Extension' header field containing all used extensions of the list specified in the corresponding request header field. A valid websocket HTTP response could look like this: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= To upgrade a connection to a websocket the _libmicrohttpd_ws_ provides some helper functions for the 'access_handler' callback function: * 'MHD_websocket_check_http_version()' checks whether the HTTP version is 1.1 or above. * 'MHD_websocket_check_connection_header()' checks whether the value of the 'Connection' request header field contains an "Upgrade" token (case-insensitive). * 'MHD_websocket_check_upgrade_header()' checks whether the value of the 'Upgrade' request header field contains the "websocket" keyword (case-insensitive). * 'MHD_websocket_check_version_header()' checks whether the value of the 'Sec-WebSocket-Version' request header field is "13". * 'MHD_websocket_create_accept_header()' takes the value from the 'Sec-WebSocket-Key' request header and calculates the value for the 'Sec-WebSocket-Accept' response header field. The 'access_handler' example of the previous chapter can now be extended with these helper functions to perform the websocket handshake: static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { static int aptr; struct MHD_Response *response; int ret; (void) cls; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *ptr) { /* do never respond on first call */ *ptr = &aptr; return MHD_YES; } *ptr = NULL; /* reset when done */ if (0 == strcmp (url, "/")) { /* Default page for visiting the server */ struct MHD_Response *response = MHD_create_response_from_buffer ( strlen (PAGE), PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else if (0 == strcmp (url, "/chat")) { char is_valid = 1; const char* value = NULL; char sec_websocket_accept[29]; if (0 != MHD_websocket_check_http_version (version)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (0 != MHD_websocket_check_connection_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE); if (0 != MHD_websocket_check_upgrade_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION); if (0 != MHD_websocket_check_version_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY); if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept)) { is_valid = 0; } if (1 == is_valid) { /* upgrade the connection */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "Upgrade"); MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "websocket"); MHD_add_response_header (response, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT, sec_websocket_accept); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); } else { /* return error page */ struct MHD_Response*response = MHD_create_response_from_buffer ( strlen (PAGE_INVALID_WEBSOCKET_REQUEST), PAGE_INVALID_WEBSOCKET_REQUEST, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); } } else { struct MHD_Response*response = MHD_create_response_from_buffer ( strlen (PAGE_NOT_FOUND), PAGE_NOT_FOUND, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } return ret; } Please note that we skipped the check of the Host header field here, because we don't know the host for this example. Decoding/encoding the websocket protocol with libmicrohttpd_ws ============================================================== Once the websocket connection is established you can receive/send frame data with the low-level socket functions 'recv()' and 'send()'. The frame data which goes over the low-level socket is encoded according to the websocket protocol. To use received payload data, you need to decode the frame data first. To send payload data, you need to encode it into frame data first. _libmicrohttpd_ws_ provides several functions for encoding of payload data and decoding of frame data: * 'MHD_websocket_decode()' decodes received frame data. The payload data may be of any kind, depending upon what the client has sent. So this decode function is used for all kind of frames and returns the frame type along with the payload data. * 'MHD_websocket_encode_text()' encodes text. The text must be encoded with UTF-8. * 'MHD_websocket_encode_binary()' encodes binary data. * 'MHD_websocket_encode_ping()' encodes a ping request to check whether the websocket is still valid and to test latency. * 'MHD_websocket_encode_ping()' encodes a pong response to answer a received ping request. * 'MHD_websocket_encode_close()' encodes a close request. * 'MHD_websocket_free()' frees data returned by the encode/decode functions. Since you could receive or send fragmented data (i. e. due to a too small buffer passed to 'recv') all of these encode/decode functions require a pointer to a 'struct MHD_WebSocketStream' passed as argument. In this structure _libmicrohttpd_ws_ stores information about encoding/decoding of the particular websocket. For each websocket you need a unique 'struct MHD_WebSocketStream' to encode/decode with this library. To create or destroy 'struct MHD_WebSocketStream' we have additional functions: * 'MHD_websocket_stream_init()' allocates and initializes a new 'struct MHD_WebSocketStream'. You can specify some options here to alter the behavior of the websocket stream. * 'MHD_websocket_stream_free()' frees a previously allocated 'struct MHD_WebSocketStream'. With these encode/decode functions we can improve our 'upgrade_handler' callback function from an earlier example to a working websocket: static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { /* make the socket blocking (operating-system-dependent code) */ make_blocking (fd); /* create a websocket stream for this connection */ struct MHD_WebSocketStream* ws; int result = MHD_websocket_stream_init (&ws, 0, 0); if (0 != result) { /* Couldn't create the websocket stream. * So we close the socket and leave */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return; } /* Let's wait for incoming data */ const size_t buf_len = 256; char buf[buf_len]; ssize_t got; while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws)) { got = recv (fd, buf, buf_len, 0); if (0 >= got) { /* the TCP/IP socket has been closed */ break; } /* parse the entire received data */ size_t buf_offset = 0; while (buf_offset < (size_t) got) { size_t new_offset = 0; char *frame_data = NULL; size_t frame_len = 0; int status = MHD_websocket_decode (ws, buf + buf_offset, ((size_t) got) - buf_offset, &new_offset, &frame_data, &frame_len); if (0 > status) { /* an error occurred and the connection must be closed */ if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } break; } else { buf_offset += new_offset; if (0 < status) { /* the frame is complete */ switch (status) { case MHD_WEBSOCKET_STATUS_TEXT_FRAME: /* The client has sent some text. * We will display it and answer with a text frame. */ if (NULL != frame_data) { printf ("Received message: %s\n", frame_data); MHD_websocket_free (ws, frame_data); frame_data = NULL; } result = MHD_websocket_encode_text (ws, "Hello", 5, /* length of "Hello" */ 0, &frame_data, &frame_len, NULL); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_CLOSE_FRAME: /* if we receive a close frame, we will respond with one */ MHD_websocket_free (ws, frame_data); frame_data = NULL; result = MHD_websocket_encode_close (ws, 0, NULL, 0, &frame_data, &frame_len); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_PING_FRAME: /* if we receive a ping frame, we will respond */ /* with the corresponding pong frame */ { char *pong = NULL; size_t pong_len = 0; result = MHD_websocket_encode_pong (ws, frame_data, frame_len, &pong, &pong_len); if (0 == result) { send_all (fd, pong, pong_len); } MHD_websocket_free (ws, pong); } break; default: /* Other frame types are ignored * in this minimal example. * This is valid, because they become * automatically skipped if we receive them unexpectedly */ break; } } if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } } } } /* free the websocket stream */ MHD_websocket_stream_free (ws); /* close the socket when it is not needed anymore */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } /* This helper function is used for the case that * we need to resend some data */ static void send_all (MHD_socket fd, const char *buf, size_t len) { ssize_t ret; size_t off; for (off = 0; off < len; off += ret) { ret = send (fd, &buf[off], (int) (len - off), 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } } /* This helper function contains operating-system-dependent code and * is used to make a socket blocking. */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) return; if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; ioctlsocket (fd, FIONBIO, &flags); #endif /* MHD_WINSOCK_SOCKETS */ } Please note that the websocket in this example is only half-duplex. It waits until the blocking 'recv()' call returns and only does then something. In this example all frame types are decoded by _libmicrohttpd_ws_, but we only do something when a text, ping or close frame is received. Binary and pong frames are ignored in our code. This is legit, because the server is only required to implement at least support for ping frame or close frame (the other frame types could be skipped in theory, because they don't require an answer). The pong frame doesn't require an answer and whether text frames or binary frames get an answer simply belongs to your server application. So this is a valid minimal example. Until this point you've learned everything you need to basically use websockets with _libmicrohttpd_ and _libmicrohttpd_ws_. These libraries offer much more functions for some specific cases. The further chapters of this tutorial focus on some specific problems and the client site programming. Using full-duplex websockets ============================ To use full-duplex websockets you can simply create two threads per websocket connection. One of these threads is used for receiving data with a blocking 'recv()' call and the other thread is triggered by the application internal codes and sends the data. A full-duplex websocket example is implemented in the example file 'websocket_chatserver_example.c'. Error handling ============== The most functions of _libmicrohttpd_ws_ return a value of 'enum MHD_WEBSOCKET_STATUS'. The values of this enumeration can be converted into an integer and have an easy interpretation: * If the value is less than zero an error occurred and the call has failed. Check the enumeration values for more specific information. * If the value is equal to zero, the call succeeded. * If the value is greater than zero, the call succeeded and the value specifies the decoded frame type. Currently positive values are only returned by 'MHD_websocket_decode()' (of the functions with this return enumeration type). A websocket stream can also get broken when invalid frame data is received. Also the other site could send a close frame which puts the stream into a state where it may not be used for regular communication. Whether a stream has become broken, can be checked with 'MHD_websocket_stream_is_valid()'. Fragmentation ============= In addition to the regular TCP/IP fragmentation the websocket protocol also supports fragmentation. Fragmentation could be used for continuous payload data such as video data from a webcam. Whether or not you want to receive fragmentation is specified upon initialization of the websocket stream. If you pass 'MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS' in the flags parameter of 'MHD_websocket_stream_init()' then you can receive fragments. If you don't pass this flag (in the most cases you just pass zero as flags) then you don't want to handle fragments on your own. _libmicrohttpd_ws_ removes then the fragmentation for you in the background. You only get the completely assembled frames. Upon encoding you specify whether or not you want to create a fragmented frame by passing a flag to the corresponding encode function. Only 'MHD_websocket_encode_text()' and 'MHD_websocket_encode_binary()' can be used for fragmentation, because the other frame types may not be fragmented. Encoding fragmented frames is independent of the 'MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS' flag upon initialization. Quick guide to websockets in JavaScript ======================================= Websockets are supported in all modern web browsers. You initialize a websocket connection by creating an instance of the 'WebSocket' class provided by the web browser. There are some simple rules for using websockets in the browser: * When you initialize the instance of the websocket class you must pass an URL. The URL must either start with 'ws://' (for not encrypted websocket protocol) or 'wss://' (for TLS-encrypted websocket protocol). *IMPORTANT:* If your website is accessed via 'https://' then you are in a security context, which means that you are only allowed to access other secure protocols. So you can only use 'wss://' for websocket connections then. If you try to 'ws://' instead then your websocket connection will automatically fail. * The WebSocket class uses events to handle the receiving of data. JavaScript is per definition a single-threaded language so the receiving events will never overlap. Sending is done directly by calling a method of the instance of the WebSocket class. Here is a short example for receiving/sending data to the same host as the website is running on: Websocket Demo  File: libmicrohttpd-tutorial.info, Node: Bibliography, Next: License text, Prev: Websockets, Up: Top Appendix A Bibliography *********************** API reference ============= * The _GNU libmicrohttpd_ manual by Marco Maggi and Christian Grothoff 2008 * All referenced RFCs can be found on the website of _The Internet Engineering Task Force_ * _RFC 2616_: Fielding, R., Gettys, J., Mogul, J., Frystyk, H., and T. Berners-Lee, "Hypertext Transfer Protocol - HTTP/1.1", RFC 2016, January 1997. * _RFC 2617_: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", RFC 2617, June 1999. * _RFC 6455_: Fette, I., Melnikov, A., "The WebSocket Protocol", RFC 6455, December 2011. * A well-structured _HTML_ reference can be found on For those readers understanding German or French, there is an excellent document both for learning _HTML_ and for reference, whose English version unfortunately has been discontinued. and  File: libmicrohttpd-tutorial.info, Node: License text, Next: Example programs, Prev: Bibliography, Up: Top Appendix B GNU Free Documentation License ***************************************** Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements." 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See . Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents ==================================================== To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.  File: libmicrohttpd-tutorial.info, Node: Example programs, Prev: License text, Up: Top Appendix C Example programs *************************** * Menu: * hellobrowser.c:: * logging.c:: * responseheaders.c:: * basicauthentication.c:: * simplepost.c:: * largepost.c:: * sessions.c:: * tlsauthentication.c:: * websocket.c::  File: libmicrohttpd-tutorial.info, Node: hellobrowser.c, Next: logging.c, Up: Example programs C.1 hellobrowser.c ================== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #define PORT 8888 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: logging.c, Next: responseheaders.c, Prev: hellobrowser.c, Up: Example programs C.2 logging.c ============= /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #define PORT 8888 static enum MHD_Result print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { (void) cls; /* Unused. Silent compiler warning. */ (void) kind; /* Unused. Silent compiler warning. */ printf ("%s: %s\n", key, value); return MHD_YES; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ printf ("New %s request for %s using version %s\n", method, url, version); MHD_get_connection_values (connection, MHD_HEADER_KIND, print_out_key, NULL); return MHD_NO; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: responseheaders.c, Next: basicauthentication.c, Prev: logging.c, Up: Example programs C.3 responseheaders.c ===================== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #include #include #define PORT 8888 #define FILENAME "picture.png" #define MIMETYPE "image/png" static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; int fd; enum MHD_Result ret; struct stat sbuf; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if ( (-1 == (fd = open (FILENAME, O_RDONLY))) || (0 != fstat (fd, &sbuf)) ) { const char *errorstr = "An internal server error has occurred!\ "; /* error accessing file */ if (fd != -1) (void) close (fd); response = MHD_create_response_from_buffer_static (strlen (errorstr), errorstr); if (NULL != response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return ret; } else return MHD_NO; } response = MHD_create_response_from_fd_at_offset64 ((size_t) sbuf.st_size, fd, 0); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, MIMETYPE)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content encoding anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: basicauthentication.c, Next: simplepost.c, Prev: responseheaders.c, Up: Example programs C.4 basicauthentication.c ========================= /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #include #define PORT 8888 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: simplepost.c, Next: largepost.c, Prev: basicauthentication.c, Up: Example programs C.5 simplepost.c ================ /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #if defined(_MSC_VER) && _MSC_VER + 0 <= 1800 /* Substitution is OK while return value is not used */ #define snprintf _snprintf #endif #define PORT 8888 #define POSTBUFFERSIZE 512 #define MAXNAMESIZE 20 #define MAXANSWERSIZE 512 #define GET 0 #define POST 1 struct connection_info_struct { int connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; static const char *askpage = "\n" "What's your name, Sir?
    \n" "
    \n" "\n" "\n" ""; #define GREETINGPAGE \ "

    Welcome, %s!

    " static const char *errorpage = "This doesn't seem to be right."; static enum MHD_Result send_page (struct MHD_Connection *connection, const char *page) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (page), page); if (! response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 == strcmp (key, "name")) { if ((size > 0) && (size <= MAXNAMESIZE)) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (! answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, GREETINGPAGE, data); con_info->answerstring = answerstring; } else con_info->answerstring = NULL; return MHD_NO; } return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == con_info) return; if (con_info->connectiontype == POST) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { struct connection_info_struct *con_info; con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void *) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else con_info->connectiontype = GET; *req_cls = (void *) con_info; return MHD_YES; } if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (*upload_data_size != 0) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) return MHD_NO; *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } return send_page (connection, errorpage); } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, request_completed, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: largepost.c, Next: sessions.c, Prev: simplepost.c, Up: Example programs C.6 largepost.c =============== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #if defined(_MSC_VER) && _MSC_VER + 0 <= 1800 /* Substitution is OK while return value is not used */ #define snprintf _snprintf #endif #define PORT 8888 #define POSTBUFFERSIZE 512 #define MAXCLIENTS 2 enum ConnectionType { GET = 0, POST = 1 }; static unsigned int nr_of_uploading_clients = 0; /** * Information we keep per connection. */ struct connection_info_struct { enum ConnectionType connectiontype; /** * Handle to the POST processing state. */ struct MHD_PostProcessor *postprocessor; /** * File handle where we write uploaded data. */ FILE *fp; /** * HTTP response body we will return, NULL if not yet known. */ const char *answerstring; /** * HTTP status code we will return, 0 for undecided. */ unsigned int answercode; }; #define ASKPAGE \ "\n" \ "Upload a file, please!
    \n" \ "There are %u clients uploading at the moment.
    \n" \ "
    \n" \ "\n" \ "\n" \ "" static const char *busypage = "This server is busy, please try again later."; static const char *completepage = "The upload has been completed."; static const char *errorpage = "This doesn't seem to be right."; static const char *servererrorpage = "Invalid request."; static const char *fileexistspage = "This file already exists."; static const char *fileioerror = "IO error writing to disk."; static const char *const postprocerror = "ErrorError processing POST data"; static enum MHD_Result send_page (struct MHD_Connection *connection, const char *page, unsigned int status_code) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (page), page); if (! response) return MHD_NO; if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html")) { fprintf (stderr, "Failed to set content type header!\n"); } ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; FILE *fp; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 != strcmp (key, "file")) { con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_BAD_REQUEST; return MHD_YES; } if (! con_info->fp) { if (0 != con_info->answercode) /* something went wrong */ return MHD_YES; if (NULL != (fp = fopen (filename, "rb"))) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_YES; } /* NOTE: This is technically a race with the 'fopen()' above, but there is no easy fix, short of moving to open(O_EXCL) instead of using fopen(). For the example, we do not care. */ con_info->fp = fopen (filename, "ab"); if (! con_info->fp) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } if (size > 0) { if (! fwrite (data, sizeof (char), size, con_info->fp)) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { /* First call, setup data structures */ struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page (connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answercode = 0; /* none yet */ con_info->fp = NULL; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, &iterate_post, (void *) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; } else { con_info->connectiontype = GET; } *req_cls = (void *) con_info; return MHD_YES; } if (0 == strcmp (method, MHD_HTTP_METHOD_GET)) { /* We just return the standard form for uploads on all GET requests */ char buffer[1024]; snprintf (buffer, sizeof (buffer), ASKPAGE, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { /* Upload not yet done */ if (0 != con_info->answercode) { /* we already know the answer, skip rest of upload */ *upload_data_size = 0; return MHD_YES; } if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) { con_info->answerstring = postprocerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } *upload_data_size = 0; return MHD_YES; } /* Upload finished */ if (NULL != con_info->fp) { fclose (con_info->fp); con_info->fp = NULL; } if (0 == con_info->answercode) { /* No errors encountered, declare success */ con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; } return send_page (connection, con_info->answerstring, con_info->answercode); } /* Note a GET or a POST, generate error */ return send_page (connection, errorpage, MHD_HTTP_BAD_REQUEST); } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); if (NULL == daemon) { fprintf (stderr, "Failed to start daemon.\n"); return 1; } (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: sessions.c, Next: tlsauthentication.c, Prev: largepost.c, Up: Example programs C.7 sessions.c ============== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #include #include #include #include #include /** * Invalid method page. */ #define METHOD_ERROR \ "Illegal requestGo away." /** * Invalid URL page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * Front page. (/) */ #define MAIN_PAGE \ "Welcome
    What is your name? " #define FORM_V1 MAIN_PAGE /** * Second page. (/2) */ #define SECOND_PAGE \ "Tell me moreprevious %s, what is your job? " #define FORM_V1_V2 SECOND_PAGE /** * Second page (/S) */ #define SUBMIT_PAGE \ "Ready to submit?previous " /** * Last page. */ #define LAST_PAGE \ "Thank youThank you." /** * Name of our cookie. */ #define COOKIE_NAME "session" /** * State we keep for each user/session/browser. */ struct Session { /** * We keep all sessions in a linked list. */ struct Session *next; /** * Unique ID for this session. */ char sid[33]; /** * Reference counter giving the number of connections * currently using this session. */ unsigned int rc; /** * Time when this session was last active. */ time_t start; /** * String submitted via form. */ char value_1[64]; /** * Another value submitted via form. */ char value_2[64]; }; /** * Data kept per request. */ struct Request { /** * Associated session. */ struct Session *session; /** * Post processor handling form data (IF this is * a POST request). */ struct MHD_PostProcessor *pp; /** * URL to serve in response to this POST (if this request * was a 'POST') */ const char *post_url; }; /** * Linked list of all active sessions. Yes, O(n) but a * hash table would be overkill for a simple example... */ static struct Session *sessions; /** * Return the session handle for this connection, or * create one if this is a new user. */ static struct Session * get_session (struct MHD_Connection *connection) { struct Session *ret; const char *cookie; cookie = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, COOKIE_NAME); if (cookie != NULL) { /* find existing session */ ret = sessions; while (NULL != ret) { if (0 == strcmp (cookie, ret->sid)) break; ret = ret->next; } if (NULL != ret) { ret->rc++; return ret; } } /* create fresh session */ ret = calloc (1, sizeof (struct Session)); if (NULL == ret) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return NULL; } /* not a super-secure way to generate a random session ID, but should do for a simple example... */ snprintf (ret->sid, sizeof (ret->sid), "%X%X%X%X", (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand ()); ret->rc++; ret->start = time (NULL); ret->next = sessions; sessions = ret; return ret; } /** * Type of handler that generates a reply. * * @param cls content for the page (handler-specific) * @param mime mime type to use * @param session session information * @param connection connection to process * @param #MHD_YES on success, #MHD_NO on failure */ typedef enum MHD_Result (*PageHandler)(const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection); /** * Entry we generate for each page served. */ struct Page { /** * Acceptable URL for this page. */ const char *url; /** * Mime type to set for the page. */ const char *mime; /** * Handler to call to generate response. */ PageHandler handler; /** * Extra argument to handler. */ const void *handler_cls; }; /** * Add header to response to set a session cookie. * * @param session session to use * @param response response to modify */ static void add_session_cookie (struct Session *session, struct MHD_Response *response) { char cstr[256]; snprintf (cstr, sizeof (cstr), "%s=%s", COOKIE_NAME, session->sid); if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE, cstr)) { fprintf (stderr, "Failed to set session cookie header!\n"); } } /** * Handler that returns a simple static HTTP page that * is passed in via 'cls'. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result serve_simple_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; const char *form = cls; struct MHD_Response *response; /* return static form */ response = MHD_create_response_from_buffer_static (strlen (form), form); add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' value to the given HTML code. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; int reply_len; (void) cls; /* Unused */ /* Emulate 'asprintf' */ reply_len = snprintf (NULL, 0, FORM_V1, session->value_1); if (0 > reply_len) return MHD_NO; /* Internal error */ reply = (char *) malloc ((size_t) ((size_t) reply_len + 1)); if (NULL == reply) return MHD_NO; /* Out-of-memory error */ if (reply_len != snprintf (reply, (size_t) (((size_t) reply_len) + 1), FORM_V1, session->value_1)) { free (reply); return MHD_NO; /* printf error */ } /* return static form */ response = MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len, (void *) reply, &free); if (NULL != response) { add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else { free (reply); ret = MHD_NO; } return ret; } /** * Handler that adds the 'v1' and 'v2' values to the given HTML code. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_v2_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; int reply_len; (void) cls; /* Unused */ /* Emulate 'asprintf' */ reply_len = snprintf (NULL, 0, FORM_V1_V2, session->value_1, session->value_2); if (0 > reply_len) return MHD_NO; /* Internal error */ reply = (char *) malloc ((size_t) ((size_t) reply_len + 1)); if (NULL == reply) return MHD_NO; /* Out-of-memory error */ if (reply_len != snprintf (reply, (size_t) ((size_t) reply_len + 1), FORM_V1_V2, session->value_1, session->value_2)) { free (reply); return MHD_NO; /* printf error */ } /* return static form */ response = MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len, (void *) reply, &free); if (NULL != response) { add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else { free (reply); ret = MHD_NO; } return ret; } /** * Handler used to generate a 404 reply. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result not_found_page (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) session; /* Unused. Silent compiler warning. */ /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), NOT_FOUND_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } MHD_destroy_response (response); return ret; } /** * List of all pages served by this HTTP server. */ static const struct Page pages[] = { { "/", "text/html", &fill_v1_form, NULL }, { "/2", "text/html", &fill_v1_v2_form, NULL }, { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE }, { "/F", "text/html", &serve_simple_form, LAST_PAGE }, { NULL, NULL, ¬_found_page, NULL } /* 404 */ }; /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; struct Session *session = request->session; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ if (0 == strcmp ("DONE", key)) { fprintf (stdout, "Session `%s' submitted `%s', `%s'\n", session->sid, session->value_1, session->value_2); return MHD_YES; } if (0 == strcmp ("v1", key)) { if (off >= sizeof(session->value_1) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_1)) size = (size_t) (sizeof (session->value_1) - off - 1); /* crop extra data */ memcpy (&session->value_1[off], data, size); if (size + off < sizeof (session->value_1)) session->value_1[size + off] = '\0'; return MHD_YES; } if (0 == strcmp ("v2", key)) { if (off >= sizeof(session->value_2) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_2)) size = (size_t) (sizeof (session->value_2) - off - 1); /* crop extra data */ memcpy (&session->value_2[off], data, size); if (size + off < sizeof (session->value_2)) session->value_2[size + off] = '\0'; return MHD_YES; } fprintf (stderr, "Unsupported form value `%s'\n", key); return MHD_YES; } /** * Main MHD callback for handling requests. * * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle to connection which is being processed * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; struct Request *request; struct Session *session; enum MHD_Result ret; unsigned int i; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ request = *req_cls; if (NULL == request) { request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { request->pp = MHD_create_post_processor (connection, 1024, &post_iterator, request); if (NULL == request->pp) { fprintf (stderr, "Failed to setup post processor for `%s'\n", url); return MHD_NO; /* internal error */ } } return MHD_YES; } if (NULL == request->session) { request->session = get_session (connection); if (NULL == request->session) { fprintf (stderr, "Failed to setup session for `%s'\n", url); return MHD_NO; /* internal error */ } } session = request->session; session->start = time (NULL); if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* evaluate POST data */ if (MHD_YES != MHD_post_process (request->pp, upload_data, *upload_data_size)) return MHD_NO; /* internal error */ if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } /* done with POST data, serve response */ MHD_destroy_post_processor (request->pp); request->pp = NULL; method = MHD_HTTP_METHOD_GET; /* fake 'GET' */ if (NULL != request->post_url) url = request->post_url; } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { /* find out which page to serve */ i = 0; while ( (pages[i].url != NULL) && (0 != strcmp (pages[i].url, url)) ) i++; ret = pages[i].handler (pages[i].handler_cls, pages[i].mime, session, connection); if (ret != MHD_YES) fprintf (stderr, "Failed to create page for `%s'\n", url); return ret; } /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (METHOD_ERROR), METHOD_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_NOT_ACCEPTABLE, response); MHD_destroy_response (response); return ret; } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == request) return; if (NULL != request->session) request->session->rc--; if (NULL != request->pp) MHD_destroy_post_processor (request->pp); free (request); } /** * Clean up handles of sessions that have been idle for * too long. */ static void expire_sessions (void) { struct Session *pos; struct Session *prev; struct Session *next; time_t now; now = time (NULL); prev = NULL; pos = sessions; while (NULL != pos) { next = pos->next; if (now - pos->start > 60 * 60) { /* expire sessions after 1h */ if (NULL == prev) sessions = pos->next; else prev->next = next; free (pos); } else prev = pos; pos = next; } } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; unsigned int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } if ( (1 != sscanf (argv[1], "%u", &port)) || (0 == port) || (65535 < port) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { expire_sessions (); max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) fprintf (stderr, "Aborting due to error during select: %s\n", strerror (errno)); break; } MHD_run (d); } MHD_stop_daemon (d); return 0; }  File: libmicrohttpd-tutorial.info, Node: tlsauthentication.c, Next: websocket.c, Prev: sessions.c, Up: Example programs C.8 tlsauthentication.c ======================= /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #define PORT 8888 #define REALM "Maintenance" #define USER "a legitimate user" #define PASSWORD "and his password" #define SERVERKEYFILE "server.key" #define SERVERCERTFILE "server.pem" static size_t get_file_size (const char *filename) { FILE *fp; fp = fopen (filename, "rb"); if (fp) { long size; if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp)))) size = 0; fclose (fp); return (size_t) size; } else return 0; } static char * load_file (const char *filename) { FILE *fp; char *buffer; size_t size; size = get_file_size (filename); if (0 == size) return NULL; fp = fopen (filename, "rb"); if (! fp) return NULL; buffer = malloc (size + 1); if (! buffer) { fclose (fp); return NULL; } buffer[size] = '\0'; if (size != fread (buffer, 1, size, fp)) { free (buffer); buffer = NULL; } fclose (fp); return buffer; } static enum MHD_Result ask_for_authentication (struct MHD_Connection *connection, const char *realm) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_empty (MHD_RF_NONE); if (! response) return MHD_NO; ret = MHD_queue_basic_auth_required_response3 (connection, realm, MHD_YES, response); MHD_destroy_response (response); return ret; } static int is_authenticated (struct MHD_Connection *connection, const char *username, const char *password) { struct MHD_BasicAuthInfo *auth_info; int authenticated; auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) return 0; authenticated = ( (strlen (username) == auth_info->username_len) && (0 == memcmp (auth_info->username, username, auth_info->username_len)) && /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL != auth_info->password) && (strlen (password) == auth_info->password_len) && (0 == memcmp (auth_info->password, password, auth_info->password_len)) ); MHD_free (auth_info); return authenticated; } static enum MHD_Result secret_page (struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); if (! response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } if (! is_authenticated (connection, USER, PASSWORD)) return ask_for_authentication (connection, REALM); return secret_page (connection); } int main (void) { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); if (NULL != key_pem) free (key_pem); if (NULL != cert_pem) free (cert_pem); return 1; } daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } (void) getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; }  File: libmicrohttpd-tutorial.info, Node: websocket.c, Prev: tlsauthentication.c, Up: Example programs C.9 websocket.c =============== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #include #else #include #endif #include #include #include #include #include #include #include #define PORT 80 #define PAGE \ "\n" \ "\n" \ "\n" \ "\n" \ "Websocket Demo\n" \ "\n" \ "\n" \ "\n" \ "\n" \ "" #define PAGE_NOT_FOUND \ "404 Not Found" #define PAGE_INVALID_WEBSOCKET_REQUEST \ "Invalid WebSocket request!" static void send_all (MHD_socket fd, const char *buf, size_t len); static void make_blocking (MHD_socket fd); static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { /* make the socket blocking (operating-system-dependent code) */ make_blocking (fd); /* create a websocket stream for this connection */ struct MHD_WebSocketStream *ws; int result = MHD_websocket_stream_init (&ws, 0, 0); if (0 != result) { /* Couldn't create the websocket stream. * So we close the socket and leave */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return; } /* Let's wait for incoming data */ const size_t buf_len = 256; char buf[buf_len]; ssize_t got; while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws)) { got = recv (fd, buf, buf_len, 0); if (0 >= got) { /* the TCP/IP socket has been closed */ break; } /* parse the entire received data */ size_t buf_offset = 0; while (buf_offset < (size_t) got) { size_t new_offset = 0; char *frame_data = NULL; size_t frame_len = 0; int status = MHD_websocket_decode (ws, buf + buf_offset, ((size_t) got) - buf_offset, &new_offset, &frame_data, &frame_len); if (0 > status) { /* an error occurred and the connection must be closed */ if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } break; } else { buf_offset += new_offset; if (0 < status) { /* the frame is complete */ switch (status) { case MHD_WEBSOCKET_STATUS_TEXT_FRAME: /* The client has sent some text. * We will display it and answer with a text frame. */ if (NULL != frame_data) { printf ("Received message: %s\n", frame_data); MHD_websocket_free (ws, frame_data); frame_data = NULL; } result = MHD_websocket_encode_text (ws, "Hello", 5, /* length of "Hello" */ 0, &frame_data, &frame_len, NULL); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_CLOSE_FRAME: /* if we receive a close frame, we will respond with one */ MHD_websocket_free (ws, frame_data); frame_data = NULL; result = MHD_websocket_encode_close (ws, 0, NULL, 0, &frame_data, &frame_len); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_PING_FRAME: /* if we receive a ping frame, we will respond */ /* with the corresponding pong frame */ { char *pong = NULL; size_t pong_len = 0; result = MHD_websocket_encode_pong (ws, frame_data, frame_len, &pong, &pong_len); if (0 == result) { send_all (fd, pong, pong_len); } MHD_websocket_free (ws, pong); } break; default: /* Other frame types are ignored * in this minimal example. * This is valid, because they become * automatically skipped if we receive them unexpectedly */ break; } } if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } } } } /* free the websocket stream */ MHD_websocket_stream_free (ws); /* close the socket when it is not needed anymore */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } /* This helper function is used for the case that * we need to resend some data */ static void send_all (MHD_socket fd, const char *buf, size_t len) { ssize_t ret; size_t off; for (off = 0; off < len; off += ret) { ret = send (fd, &buf[off], (int) (len - off), 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } } /* This helper function contains operating-system-dependent code and * is used to make a socket blocking. */ static void make_blocking (MHD_socket fd) { #ifndef _WIN32 int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #else /* _WIN32 */ unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) abort (); #endif /* _WIN32 */ } static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; int ret; (void) cls; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ if (0 == strcmp (url, "/")) { /* Default page for visiting the server */ struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else if (0 == strcmp (url, "/chat")) { char is_valid = 1; const char *value = NULL; char sec_websocket_accept[29]; if (0 != MHD_websocket_check_http_version (version)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (0 != MHD_websocket_check_connection_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE); if (0 != MHD_websocket_check_upgrade_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION); if (0 != MHD_websocket_check_version_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY); if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept)) { is_valid = 0; } if (1 == is_valid) { /* upgrade the connection */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "websocket"); MHD_add_response_header (response, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT, sec_websocket_accept); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); } else { /* return error page */ struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen ( PAGE_INVALID_WEBSOCKET_REQUEST), PAGE_INVALID_WEBSOCKET_REQUEST); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); } } else { struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (PAGE_NOT_FOUND), PAGE_NOT_FOUND); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { (void) argc; /* Unused. Silent compiler warning. */ (void) argv; /* Unused. Silent compiler warning. */ struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_ALLOW_UPGRADE | MHD_USE_ERROR_LOG, PORT, NULL, NULL, &access_handler, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getc (stdin); MHD_stop_daemon (daemon); return 0; }  Tag Table: Node: Top873 Node: Introduction1942 Node: Hello browser example3248 Node: Exploring requests14504 Node: Response headers19928 Node: Supporting basic authentication27861 Node: Processing POST data37947 Node: Improved processing of POST data46693 Node: Session management57511 Node: Adding a layer of security61025 Node: Websockets75792 Node: Bibliography103375 Node: License text104652 Node: Example programs129808 Node: hellobrowser.c130137 Node: logging.c132268 Node: responseheaders.c134432 Node: basicauthentication.c137961 Node: simplepost.c141899 Node: largepost.c148653 Node: sessions.c159825 Node: tlsauthentication.c187089 Node: websocket.c193151  End Tag Table  Local Variables: coding: utf-8 End: libmicrohttpd-1.0.2/doc/version.texi0000644000175000017500000000014715035216652014433 00000000000000@set UPDATED 24 September 2024 @set UPDATED-MONTH September 2024 @set EDITION 1.0.2 @set VERSION 1.0.2 libmicrohttpd-1.0.2/doc/gpl-2.0.texi0000644000175000017500000004362714674632555014053 00000000000000@c The GNU General Public License. @center Version 2, June 1991 @c This file is intended to be included within another document, @c hence no sectioning command or @node. @display Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @end display @heading Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software---to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. @heading TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @enumerate 0 @item This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. @item You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. @item You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: @enumerate a @item You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. @item You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. @item If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) @end enumerate These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. @item You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: @enumerate a @item Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, @item Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, @item Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) @end enumerate The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. @item You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. @item You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. @item Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. @item If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. @item If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. @item The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. @item If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. @iftex @heading NO WARRANTY @end iftex @ifinfo @center NO WARRANTY @end ifinfo @item BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. @item IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. @end enumerate @iftex @heading END OF TERMS AND CONDITIONS @end iftex @ifinfo @center END OF TERMS AND CONDITIONS @end ifinfo @page @heading Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found. @smallexample @var{one line to give the program's name and a brief idea of what it does.} Copyright (C) @var{yyyy} @var{name of author} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. @end smallexample Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: @smallexample Gnomovision version 69, Copyright (C) @var{year} @var{name of author} Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. @end smallexample The hypothetical commands @samp{show w} and @samp{show c} should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than @samp{show w} and @samp{show c}; they could even be mouse-clicks or menu items---whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here is a sample; alter the names: @example Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. @var{signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice @end example This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. libmicrohttpd-1.0.2/doc/libmicrohttpd.info0000644000175000017500000107366215035216653015612 00000000000000This is libmicrohttpd.info, produced by makeinfo version 7.1.1 from libmicrohttpd.texi. This manual is for GNU libmicrohttpd (version 1.0.2, 24 September 2024), a library for embedding an HTTP(S) server into C applications. Copyright © 2007-2019 Christian Grothoff Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION Software libraries START-INFO-DIR-ENTRY * libmicrohttpd: (libmicrohttpd). Embedded HTTP server library. END-INFO-DIR-ENTRY  File: libmicrohttpd.info, Node: Top, Next: microhttpd-intro, Up: (dir) The GNU libmicrohttpd Library ***************************** This manual is for GNU libmicrohttpd (version 1.0.2, 24 September 2024), a library for embedding an HTTP(S) server into C applications. Copyright © 2007-2019 Christian Grothoff Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". * Menu: * microhttpd-intro:: Introduction. * microhttpd-const:: Constants. * microhttpd-struct:: Structures type definition. * microhttpd-cb:: Callback functions definition. * microhttpd-init:: Starting and stopping the server. * microhttpd-inspect:: Implementing external ‘select’. * microhttpd-requests:: Handling requests. * microhttpd-responses:: Building responses to requests. * microhttpd-flow:: Flow control. * microhttpd-dauth:: Utilizing Authentication. * microhttpd-post:: Adding a ‘POST’ processor. * microhttpd-info:: Obtaining and modifying status information. * microhttpd-util:: Utilities. * microhttpd-websocket:: Websockets. Appendices * GNU-LGPL:: The GNU Lesser General Public License says how you can copy and share almost all of 'libmicrohttpd'. * eCos License:: The eCos License says how you can copy and share some parts of 'libmicrohttpd'. * GNU-GPL:: The GNU General Public License (with eCos extension) says how you can copy and share some parts of 'libmicrohttpd'. * GNU-FDL:: The GNU Free Documentation License says how you can copy and share the documentation of 'libmicrohttpd'. Indices * Concept Index:: Index of concepts and programs. * Function and Data Index:: Index of functions, variables and data types. * Type Index:: Index of data types.  File: libmicrohttpd.info, Node: microhttpd-intro, Next: microhttpd-const, Prev: Top, Up: Top 1 Introduction ************** All symbols defined in the public API start with ‘MHD_’. MHD is a small HTTP daemon library. As such, it does not have any API for logging errors (you can only enable or disable logging to stderr). Also, it may not support all of the HTTP features directly, where applicable, portions of HTTP may have to be handled by clients of the library. The library is supposed to handle everything that it must handle (because the API would not allow clients to do this), such as basic connection management. However, detailed interpretations of headers, such as range requests, are left to the main application. In particular, if an application developer wants to support range requests, he needs to explicitly indicate support in responses and also explicitly parse the range header and generate a response (for example, using the ‘MHD_create_response_from_fd_at_offset’ call to serve ranges from a file). MHD does understands headers that control connection management (specifically, ‘Connection: close’ and ‘Expect: 100 continue’ are understood and handled automatically). ‘Connection: upgrade’ is supported by passing control over the socket (or something that behaves like the real socket in the case of TLS) to the application (after sending the desired HTTP response header). MHD largely ignores the semantics of the different HTTP methods, so clients are left to handle those. One exception is that MHD does understand ‘HEAD’ and will only send the headers of the response and not the body, even if the client supplied a body. (In fact, clients do need to construct a response with the correct length, even for ‘HEAD’ request.) MHD understands ‘POST’ data and is able to decode certain formats (at the moment only ‘application/x-www-form-urlencoded’ and ‘multipart/form-data’) using the post processor API. The data stream of a POST is also provided directly to the main application, so unsupported encodings could still be processed, just not conveniently by MHD. The header file defines various constants used by the HTTP protocol. This does not mean that MHD actually interprets all of these values. The provided constants are exported as a convenience for users of the library. MHD does not verify that transmitted HTTP headers are part of the standard specification; users of the library are free to define their own extensions of the HTTP standard and use those with MHD. All functions are guaranteed to be completely reentrant and thread-safe. MHD checks for allocation failures and tries to recover gracefully (for example, by closing the connection). Additionally, clients can specify resource limits on the overall number of connections, number of connections per IP address and memory used per connection to avoid resource exhaustion. 1.1 Scope ========= MHD is currently used in a wide range of implementations. Examples based on reports we've received from developers include: • Embedded HTTP server on a cortex M3 (128 KB code space) • Large-scale multimedia server (reportedly serving at the simulator limit of 7.5 GB/s) • Administrative console (via HTTP/HTTPS) for network appliances 1.2 Thread modes and event loops ================================ MHD supports four basic thread modes and up to three event loop styles. The four basic thread modes are external sockets polling (MHD creates no threads, event loop is fully managed by the application), internal polling (MHD creates one thread for all connections), polling in thread pool (MHD creates a thread pool which is used to process all connections) and thread-per-connection (MHD creates one thread for listen sockets and then one thread per accepted connection). These thread modes are then combined with the evet loop styles (polling function type). MHD support select, poll and epoll. select is available on all platforms, epoll and poll may not be available on some platforms. Note that it is possible to combine MHD using epoll with an external select-based event loop. The default (if no other option is passed) is "external select". The highest performance can typically be obtained with a thread pool using ‘epoll’. Apache Benchmark (ab) was used to compare the performance of ‘select’ and ‘epoll’ when using a thread pool and a large number of connections. *note Figure 1.1: fig:performance. shows the resulting plot from the ‘benchmark.c’ example, which measures the latency between an incoming request and the completion of the transmission of the response. In this setting, the ‘epoll’ thread pool with four threads was able to handle more than 45,000 connections per second on loopback (with Apache Benchmark running three processes on the same machine). [image src="libmicrohttpd_performance_data.png" alt="Data"] Figure 1.1: Performance measurements for select vs. epoll (with thread-pool). Not all combinations of thread modes and event loop styles are supported. This is partially to keep the API simple, and partially because some combinations simply make no sense as others are strictly superior. Note that the choice of style depends first of all on the application logic, and then on the performance requirements. Applications that perform a blocking operation while handling a request within the callbacks from MHD must use a thread per connection. This is typically rather costly. Applications that do not support threads or that must run on embedded devices without thread-support must use the external mode. Using ‘epoll’ is only supported on some platform, thus portable applications must at least have a fallback option available. *note Table 1.1: tbl:supported. lists the sane combinations. select poll epoll external yes no yes internal yes yes yes thread pool yes yes yes thread-per-connection yes yes no Table 1.1: Supported combinations of event styles and thread modes. 1.3 Compiling GNU libmicrohttpd =============================== MHD uses the standard GNU system where the usual build process involves running $ ./configure $ make $ make install MHD supports various options to be given to configure to tailor the binary to a specific situation. Note that some of these options will remove portions of the MHD code that are required for binary-compatibility. They should only be used on embedded systems with tight resource constraints and no concerns about library versioning. Standard distributions including MHD are expected to always ship with all features enabled, otherwise unexpected incompatibilities can arise! Here is a list of MHD-specific options that can be given to configure (canonical configure options such as "-prefix" are also supported, for a full list of options run "./configure -help"): ‘``--disable-curl''’ disable running testcases using libcurl ‘``--disable-largefile''’ disable support for 64-bit files ‘``--disable-messages''’ disable logging of error messages (smaller binary size, not so much fun for debugging) ‘``--disable-https''’ disable HTTPS support, even if GNUtls is found; this option must be used if eCOS license is desired as an option (in all cases the resulting binary falls under a GNU LGPL-only license) ‘``--disable-postprocessor''’ do not include the post processor API (results in binary incompatibility) ‘``--disable-dauth''’ do not include the authentication APIs (results in binary incompatibility) ‘``--disable-httpupgrade''’ do not build code for HTTP "Upgrade" (smaller binary size, binary incompatible library) ‘``--disable-epoll''’ do not include epoll support, even if it supported (minimally smaller binary size, good for portability testing) ‘``--enable-coverage''’ set flags for analysis of code-coverage with gcc/gcov (results in slow, large binaries) ‘``--with-threads=posix,w32,none,auto''’ sets threading library to use. With use "none" to not support threads. In this case, MHD will only support the "external" threading modes and not perform any locking of data structures! Use ‘MHD_is_feature_supported(MHD_FEATURE_THREADS)’ to test if threads are available. Default is "auto". ‘``--with-gcrypt=PATH''’ specifies path to libgcrypt installation ‘``--with-gnutls=PATH''’ specifies path to libgnutls installation To cross-compile MHD for Android, install the Android NDK and use: ./configure --target=arm-linux-androideabi --host=arm-linux-androideabi --disable-doc --disable-examples make Similar build commands should work for cross-compilation to other platforms. Note that you may have to first cross-compile GnuTLS to get MHD with TLS support. 1.4 Validity of pointers ======================== MHD will give applications access to its internal data structures via pointers via arguments and return values from its API. This creates the question as to how long those pointers are assured to stay valid. Most MHD data structures are associated with the connection of an HTTP client. Thus, pointers associated with a connection are typically valid until the connection is finished, at which point MHD will call the ‘MHD_RequestCompletedCallback’ if one is registered. Applications that have such a callback registered may assume that keys and values from the ‘MHD_KeyValueIterator’, return values from ‘MHD_lookup_connection_value’ and the ‘url’, ‘method’ and ‘version’ arguments to the ‘MHD_AccessHandlerCallback’ will remain valid until the respective ‘MHD_RequestCompletedCallback’ is invoked. In contrast, the ‘upload_data’ argument of ‘MHD_RequestCompletedCallback’ as well as all pointers from the ‘MHD_PostDataIterator’ are only valid for the duration of the callback. Pointers returned from ‘MHD_get_response_header’ are valid as long as the response itself is valid. 1.5 Including the microhttpd.h header ===================================== Ideally, before including "microhttpd.h" you should add the necessary includes to define the ‘va_list’, ‘size_t’, ‘ssize_t’, ‘intptr_t’, ‘off_t’, ‘uint8_t’, ‘uint16_t’, ‘int32_t’, ‘uint32_t’, ‘int64_t’, ‘uint64_t’, ‘fd_set’, ‘socklen_t’ and ‘struct sockaddr’ data types. Which specific headers are needed may depend on your platform and your build system might include some tests to provide you with the necessary conditional operations. For possible suggestions consult ‘platform.h’ and ‘configure.ac’ in the MHD distribution. Once you have ensured that you manually (!) included the right headers for your platform before "microhttpd.h", you should also add a line with ‘#define MHD_PLATFORM_H’ which will prevent the "microhttpd.h" header from trying (and, depending on your platform, failing) to include the right headers. If you do not define MHD_PLATFORM_H, the "microhttpd.h" header will automatically include headers needed on GNU/Linux systems (possibly causing problems when porting to other platforms). 1.6 SIGPIPE =========== MHD does not install a signal handler for SIGPIPE. On platforms where this is possible (such as GNU/Linux), it disables SIGPIPE for its I/O operations (by passing MSG_NOSIGNAL or similar). On other platforms, SIGPIPE signals may be generated from network operations by MHD and will cause the process to die unless the developer explicitly installs a signal handler for SIGPIPE. Hence portable code using MHD must install a SIGPIPE handler or explicitly block the SIGPIPE signal. MHD does not do so in order to avoid messing with other parts of the application that may need to handle SIGPIPE in a particular way. You can make your application handle SIGPIPE by calling the following function in ‘main’: static void catcher (int sig) { } static void ignore_sigpipe () { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } 1.7 MHD_UNSIGNED_LONG_LONG ========================== Some platforms do not support ‘long long’. Hence MHD defines a macro ‘MHD_UNSIGNED LONG_LONG’ which will default to ‘unsigned long long’. For standard desktop operating systems, this is all you need to know. However, if your platform does not support ‘unsigned long long’, you should change "platform.h" to define ‘MHD_LONG_LONG’ and ‘MHD_UNSIGNED_LONG_LONG’ to an appropriate alternative type and also define ‘MHD_LONG_LONG_PRINTF’ and ‘MHD_UNSIGNED_LONG_LONG_PRINTF’ to the corresponding format string for printing such a data type. Note that the "signed" versions are deprecated. Also, for historical reasons, ‘MHD_LONG_LONG_PRINTF’ is without the percent sign, whereas ‘MHD_UNSIGNED_LONG_LONG_PRINTF’ is with the percent sign. Newly written code should only use the unsigned versions. However, you need to define both in "platform.h" if you need to change the definition for the specific platform. 1.8 Portability to W32 ====================== libmicrohttpd in general ported well to W32. Most libmicrohttpd features are supported. W32 do not support some functions, like epoll and corresponding MHD features are not available on W32. 1.9 Portability to z/OS ======================= To compile MHD on z/OS, extract the archive and run iconv -f UTF-8 -t IBM-1047 contrib/ascebc > /tmp/ascebc.sh chmod +x /tmp/ascebc.sh for n in `find * -type f` do /tmp/ascebc.sh $n done to convert all source files to EBCDIC. Note that you must run ‘configure’ from the directory where the configure script is located. Otherwise, configure will fail to find the ‘contrib/xcc’ script (which is a wrapper around the z/OS c89 compiler).  File: libmicrohttpd.info, Node: microhttpd-const, Next: microhttpd-struct, Prev: microhttpd-intro, Up: Top 2 Constants *********** -- Enumeration: MHD_FLAG Options for the MHD daemon. Note that MHD will run automatically in background thread(s) only if ‘MHD_USE_INTERNAL_POLLING_THREAD’ is used. Otherwise caller (application) must use ‘MHD_run’ or ‘MHD_run_from_select’ to have MHD processed network connections and data. Starting the daemon may also fail if a particular option is not implemented or not supported on the target platform (i.e. no support for TLS, threads or IPv6). TLS support generally depends on options given during MHD compilation. ‘MHD_NO_FLAG’ No options selected. ‘MHD_USE_ERROR_LOG’ If this flag is used, the library should print error messages and warnings to stderr (or to custom error printer if it's specified by options). Note that for this run-time option to have any effect, MHD needs to be compiled with messages enabled. This is done by default except you ran configure with the ‘--disable-messages’ flag set. ‘MHD_USE_DEBUG’ Currently the same as ‘MHD_USE_ERROR_LOG’. ‘MHD_USE_TLS’ Run in HTTPS-mode. If you specify ‘MHD_USE_TLS’ and MHD was compiled without SSL support, ‘MHD_start_daemon’ will return NULL. ‘MHD_USE_THREAD_PER_CONNECTION’ Run using one thread per connection. ‘MHD_USE_INTERNAL_POLLING_THREAD’ Run using an internal thread doing ‘SELECT’. ‘MHD_USE_IPv6’ Run using the IPv6 protocol (otherwise, MHD will just support IPv4). If you specify ‘MHD_USE_IPV6’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. If you want MHD to support IPv4 and IPv6 using a single socket, pass MHD_USE_DUAL_STACK, otherwise, if you only pass this option, MHD will try to bind to IPv6-only (resulting in no IPv4 support). ‘MHD_USE_DUAL_STACK’ Use a single socket for IPv4 and IPv6. Note that this will mean that IPv4 addresses are returned by MHD in the IPv6-mapped format (the 'struct sockaddr_in6' format will be used for IPv4 and IPv6). ‘MHD_USE_PEDANTIC_CHECKS’ Deprecated (use ‘MHD_OPTION_STRICT_FOR_CLIENT’). Be pedantic about the protocol. Specifically, at the moment, this flag causes MHD to reject HTTP 1.1 connections without a ‘Host’ header. This is required by the standard, but of course in violation of the "be as liberal as possible in what you accept" norm. It is recommended to turn this *ON* if you are testing clients against MHD, and *OFF* in production. ‘MHD_USE_POLL’ Use ‘poll()’ instead of ‘select()’. This allows sockets with descriptors ‘>= FD_SETSIZE’. This option currently only works in conjunction with ‘MHD_USE_INTERNAL_POLLING_THREAD’ (at this point). If you specify ‘MHD_USE_POLL’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. ‘MHD_USE_EPOLL’ Use ‘epoll()’ instead of ‘poll()’ or ‘select()’. This allows sockets with descriptors ‘>= FD_SETSIZE’. This option is only available on some systems and does not work in conjunction with ‘MHD_USE_THREAD_PER_CONNECTION’ (at this point). If you specify ‘MHD_USE_EPOLL’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. Using ‘epoll()’ instead of ‘select()’ or ‘poll()’ can in some situations result in significantly higher performance as the system call has fundamentally lower complexity (O(1) for ‘epoll()’ vs. O(n) for ‘select()’/‘poll()’ where n is the number of open connections). ‘MHD_USE_TURBO’ Enable optimizations to aggressively improve performance. Currently, the optimizations this option enables are based on opportunistic reads and writes. Basically, MHD will simply try to read or write or accept on a socket before checking that the socket is ready for IO using the event loop mechanism. As the sockets are non-blocking, this may fail (at a loss of performance), but generally MHD does this in situations where the operation is likely to succeed, in which case performance is improved. Setting the flag should generally be safe (even though the code is slightly more experimental). You may want to benchmark your application to see if this makes any difference for you. ‘MHD_USE_SUPPRESS_DATE_NO_CLOCK’ Suppress (automatically) adding the 'Date:' header to HTTP responses. This option should ONLY be used on systems that do not have a clock and that DO provide other mechanisms for cache control. See also RFC 2616, section 14.18 (exception 3). ‘MHD_USE_NO_LISTEN_SOCKET’ Run the HTTP server without any listen socket. This option only makes sense if ‘MHD_add_connection’ is going to be used exclusively to connect HTTP clients to the HTTP server. This option is incompatible with using a thread pool; if it is used, ‘MHD_OPTION_THREAD_POOL_SIZE’ is ignored. ‘MHD_USE_ITC’ Force MHD to use a signal inter-thread communication channel to notify the event loop (of threads) of our shutdown and other events. This is required if an application uses ‘MHD_USE_INTERNAL_POLLING_THREAD’ and then performs ‘MHD_quiesce_daemon’ (which eliminates our ability to signal termination via the listen socket). In these modes, ‘MHD_quiesce_daemon’ will fail if this option was not set. Also, use of this option is automatic (as in, you do not even have to specify it), if ‘MHD_USE_NO_LISTEN_SOCKET’ is specified. In "external" select mode, this option is always simply ignored. Using this option also guarantees that MHD will not call ‘shutdown()’ on the listen socket, which means a parent process can continue to use the socket. ‘MHD_ALLOW_SUSPEND_RESUME’ Enables using ‘MHD_suspend_connection’ and ‘MHD_resume_connection’, as performing these calls requires some additional inter-thred communication channels to be created, and code not using these calls should not pay the cost. ‘MHD_USE_TCP_FASTOPEN’ Enable TCP_FASTOPEN on the listen socket. TCP_FASTOPEN is currently supported on Linux >= 3.6. On other systems using this option with cause ‘MHD_start_daemon’ to fail. ‘MHD_ALLOW_UPGRADE’ This option must be set if you want to upgrade connections (via "101 Switching Protocols" responses). This requires MHD to allocate additional resources, and hence we require this special flag so we only use the resources that are really needed. ‘MHD_USE_AUTO’ Automatically select best event loop style (polling function) depending on requested mode by other MHD flags and functions available on platform. If application doesn't have requirements for any specific polling function, it's recommended to use this flag. This flag is very convenient for multiplatform applications. ‘MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT’ Tell the TLS library to support post handshake client authentication. Only useful in combination with ‘MHD_USE_TLS’. This option will only work if the underlying TLS library supports it (i.e. GnuTLS after 3.6.3). If the TLS library does not support it, MHD may ignore the option and proceed without supporting this features. ‘MHD_USE_INSECURE_TLS_EARLY_DATA’ Tell the TLS library to support TLS v1.3 early data (0-RTT) with the resulting security drawbacks. Only enable this if you really know what you are doing. MHD currently does NOT enforce that this only affects GET requests! You have been warned. This option will only work if the underlying TLS library supports it (i.e. GnuTLS after 3.6.3). If the TLS library does not support it, MHD may ignore the option and proceed without supporting this features. -- Enumeration: MHD_OPTION MHD options. Passed in the varargs portion of ‘MHD_start_daemon()’. ‘MHD_OPTION_END’ No more options / last option. This is used to terminate the VARARGs list. ‘MHD_OPTION_CONNECTION_MEMORY_LIMIT’ Maximum memory size per connection (followed by a ‘size_t’). The default is 32 kB (32*1024 bytes) as defined by the internal constant ‘MHD_POOL_SIZE_DEFAULT’. Values above 128k are unlikely to result in much benefit, as half of the memory will be typically used for IO, and TCP buffers are unlikely to support window sizes above 64k on most systems. ‘MHD_OPTION_CONNECTION_MEMORY_INCREMENT’ Increment to use for growing the read buffer (followed by a ‘size_t’). The default is 1024 (bytes). Increasing this value will make MHD use memory for reading more aggressively, which can reduce the number of ‘recvfrom’ calls but may increase the number of ‘sendto’ calls. The given value must fit within MHD_OPTION_CONNECTION_MEMORY_LIMIT. ‘MHD_OPTION_CONNECTION_LIMIT’ Maximum number of concurrent connections to accept (followed by an ‘unsigned int’). The default is ‘FD_SETSIZE - 4’ (the maximum number of file descriptors supported by ‘select’ minus four for ‘stdin’, ‘stdout’, ‘stderr’ and the server socket). In other words, the default is as large as possible. If the connection limit is reached, MHD's behavior depends a bit on other options. If ‘MHD_USE_ITC’ was given, MHD will stop accepting connections on the listen socket. This will cause the operating system to queue connections (up to the ‘listen()’ limit) above the connection limit. Those connections will be held until MHD is done processing at least one of the active connections. If ‘MHD_USE_ITC’ is not set, then MHD will continue to ‘accept()’ and immediately ‘close()’ these connections. Note that if you set a low connection limit, you can easily get into trouble with browsers doing request pipelining. For example, if your connection limit is "1", a browser may open a first connection to access your "index.html" file, keep it open but use a second connection to retrieve CSS files, images and the like. In fact, modern browsers are typically by default configured for up to 15 parallel connections to a single server. If this happens, MHD will refuse to even accept the second connection until the first connection is closed -- which does not happen until timeout. As a result, the browser will fail to render the page and seem to hang. If you expect your server to operate close to the connection limit, you should first consider using a lower timeout value and also possibly add a "Connection: close" header to your response to ensure that request pipelining is not used and connections are closed immediately after the request has completed: MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ‘MHD_OPTION_CONNECTION_TIMEOUT’ After how many seconds of inactivity should a connection automatically be timed out? (followed by an ‘unsigned int’; use zero for no timeout). The default is zero (no timeout). ‘MHD_OPTION_NOTIFY_COMPLETED’ Register a function that should be called whenever a request has been completed (this can be used for application-specific clean up). Requests that have never been presented to the application (via ‘MHD_AccessHandlerCallback()’) will not result in notifications. This option should be followed by *TWO* pointers. First a pointer to a function of type ‘MHD_RequestCompletedCallback()’ and second a pointer to a closure to pass to the request completed callback. The second pointer maybe ‘NULL’. ‘MHD_OPTION_NOTIFY_CONNECTION’ Register a function that should be called when the TCP connection to a client is opened or closed. The registered callback is called twice per TCP connection, with ‘MHD_CONNECTION_NOTIFY_STARTED’ and ‘MHD_CONNECTION_NOTIFY_CLOSED’ respectively. An additional argument can be used to store TCP connection specific information, which can be retrieved using ‘MHD_CONNECTION_INFO_SOCKET_CONTEXT’ during the lifetime of the TCP connection. Note ‘MHD_OPTION_NOTIFY_COMPLETED’ and the ‘req_cls’ argument to the ‘MHD_AccessHandlerCallback’ are per HTTP request (and there can be multiple HTTP requests per TCP connection). This option should be followed by *TWO* pointers. First a pointer to a function of type ‘MHD_NotifyConnectionCallback()’ and second a pointer to a closure to pass to the request completed callback. The second pointer maybe ‘NULL’. ‘MHD_OPTION_PER_IP_CONNECTION_LIMIT’ Limit on the number of (concurrent) connections made to the server from the same IP address. Can be used to prevent one IP from taking over all of the allowed connections. If the same IP tries to establish more than the specified number of connections, they will be immediately rejected. The option should be followed by an ‘unsigned int’. The default is zero, which means no limit on the number of connections from the same IP address. ‘MHD_OPTION_LISTEN_BACKLOG_SIZE’ Set the size of the ‘listen()’ back log queue of the TCP socket. Takes an ‘unsigned int’ as the argument. Default is the platform-specific value of ‘SOMAXCONN’. ‘MHD_OPTION_STRICT_FOR_CLIENT’ Specify how strict we should enforce the HTTP protocol. Takes an ‘int’ as the argument. Default is zero. If set to 1, MHD will be strict about the protocol. Specifically, at the moment, this flag uses MHD to reject HTTP 1.1 connections without a "Host" header. This is required by the standard, but of course in violation of the "be as liberal as possible in what you accept" norm. It is recommended to set this to 1 if you are testing clients against MHD, and 0 in production. If set to -1 MHD will be permissive about the protocol, allowing slight deviations that are technically not allowed by the RFC. Specifically, at the moment, this flag causes MHD to allow spaces in header field names. This is disallowed by the standard. It is not recommended to set it to -1 on publicly available servers as it may potentially lower level of protection. ‘MHD_OPTION_SERVER_INSANITY’ Allows the application to disable certain sanity precautions in MHD. With these, the client can break the HTTP protocol, so this should never be used in production. The options are, however, useful for testing HTTP clients against "broken" server implementations. This argument must be followed by an ‘unsigned int’, corresponding to an ‘enum MHD_DisableSanityCheck’. Right now, no sanity checks can be disabled. ‘MHD_OPTION_SOCK_ADDR’ Bind daemon to the supplied socket address. This option should be followed by a ‘struct sockaddr *’. If ‘MHD_USE_IPv6’ is specified, the ‘struct sockaddr*’ should point to a ‘struct sockaddr_in6’, otherwise to a ‘struct sockaddr_in’. If this option is not specified, the daemon will listen to incoming connections from anywhere. If you use this option, the 'port' argument from ‘MHD_start_daemon’ is ignored and the port from the given ‘struct sockaddr *’ will be used instead. ‘MHD_OPTION_URI_LOG_CALLBACK’ Specify a function that should be called before parsing the URI from the client. The specified callback function can be used for processing the URI (including the options) before it is parsed. The URI after parsing will no longer contain the options, which maybe inconvenient for logging. This option should be followed by two arguments, the first one must be of the form void * my_logger(void * cls, const char * uri, struct MHD_Connection *con) where the return value will be passed as ‘*req_cls’ in calls to the ‘MHD_AccessHandlerCallback’ when this request is processed later; returning a value of ‘NULL’ has no special significance; (however, note that if you return non-‘NULL’, you can no longer rely on the first call to the access handler having ‘NULL == *req_cls’ on entry) ‘cls’ will be set to the second argument following MHD_OPTION_URI_LOG_CALLBACK. Finally, ‘uri’ will be the 0-terminated URI of the request. Note that during the time of this call, most of the connection's state is not initialized (as we have not yet parsed he headers). However, information about the connecting client (IP, socket) is available. ‘MHD_OPTION_HTTPS_MEM_KEY’ Memory pointer to the private key to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_CERT'. ‘MHD_OPTION_HTTPS_KEY_PASSWORD’ Memory pointer to the password that decrypts the private key to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. The password (or passphrase) is only used immediately during ‘MHD_start_daemon()’. Thus, the application may want to erase it from memory afterwards for additional security. ‘MHD_OPTION_HTTPS_MEM_CERT’ Memory pointer to the certificate to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. ‘MHD_OPTION_HTTPS_MEM_TRUST’ Memory pointer to the CA certificate to be used by the HTTPS daemon to authenticate and trust clients certificates. This option should be followed by an "const char*" argument. The presence of this option activates the request of certificate to the client. The request to the client is marked optional, and it is the responsibility of the server to check the presence of the certificate if needed. Note that most browsers will only present a client certificate only if they have one matching the specified CA, not sending any certificate otherwise. ‘MHD_OPTION_HTTPS_CRED_TYPE’ Daemon credentials type. Either certificate or anonymous, this option should be followed by one of the values listed in "enum gnutls_credentials_type_t". ‘MHD_OPTION_HTTPS_PRIORITIES’ SSL/TLS protocol version and ciphers. This option must be followed by an "const char *" argument specifying the SSL/TLS protocol versions and ciphers that are acceptable for the application. The string is passed unchanged to gnutls_priority_init. If this option is not specified, "NORMAL" is used. ‘MHD_OPTION_HTTPS_CERT_CALLBACK’ Use a callback to determine which X.509 certificate should be used for a given HTTPS connection. This option should be followed by a argument of type "gnutls_certificate_retrieve_function2 *". This option provides an alternative to MHD_OPTION_HTTPS_MEM_KEY and MHD_OPTION_HTTPS_MEM_CERT. You must use this version if multiple domains are to be hosted at the same IP address using TLS's Server Name Indication (SNI) extension. In this case, the callback is expected to select the correct certificate based on the SNI information provided. The callback is expected to access the SNI data using gnutls_server_name_get(). Using this option requires GnuTLS 3.0 or higher. ‘MHD_OPTION_HTTPS_CERT_CALLBACK2’ Use a callback to determine which X.509 certificate should be used for a given HTTPS connection. This option should be followed by a argument of type 'gnutls_certificate_retrieve_function3 *'. This option provides an alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK. You must use this version if you want to use OCSP stapling. Using this option requires GnuTLS 3.6.3 or higher. ‘MHD_OPTION_GNUTLS_PSK_CRED_HANDLER’ Use pre-shared key for TLS credentials. Pass a pointer to callback of type ‘MHD_PskServerCredentialsCallback’ and a closure. The function will be called to retrieve the shared key for a given username. ‘MHD_OPTION_DIGEST_AUTH_RANDOM’ Digest Authentication nonce's seed. This option should be followed by two arguments. First an integer of type "size_t" which specifies the size of the buffer pointed to by the second argument in bytes. Note that the application must ensure that the buffer of the second argument remains allocated and unmodified while the daemon is running. For security, you SHOULD provide a fresh random nonce when using MHD with Digest Authentication. ‘MHD_OPTION_NONCE_NC_SIZE’ Size of an array of nonce and nonce counter map. This option must be followed by an "unsigned int" argument that have the size (number of elements) of a map of a nonce and a nonce-counter. If this option is not specified, a default value of 4 will be used (which might be too small for servers handling many requests). If you do not use digest authentication at all, you can specify a value of zero to save some memory. You should calculate the value of NC_SIZE based on the number of connections per second multiplied by your expected session duration plus a factor of about two for hash table collisions. For example, if you expect 100 digest-authenticated connections per second and the average user to stay on your site for 5 minutes, then you likely need a value of about 60000. On the other hand, if you can only expect only 10 digest-authenticated connections per second, tolerate browsers getting a fresh nonce for each request and expect a HTTP request latency of 250 ms, then a value of about 5 should be fine. ‘MHD_OPTION_LISTEN_SOCKET’ Listen socket to use. Pass a listen socket for MHD to use (systemd-style). If this option is used, MHD will not open its own listen socket(s). The argument passed must be of type "int" and refer to an existing socket that has been bound to a port and is listening. ‘MHD_OPTION_EXTERNAL_LOGGER’ Use the given function for logging error messages. This option must be followed by two arguments; the first must be a pointer to a function of type 'void fun(void * arg, const char * fmt, va_list ap)' and the second a pointer of type 'void*' which will be passed as the "arg" argument to "fun". Note that MHD will not generate any log messages without the MHD_USE_ERROR_LOG flag set and if MHD was compiled with the "-disable-messages" flag. ‘MHD_OPTION_THREAD_POOL_SIZE’ Number (unsigned int) of threads in thread pool. Enable thread pooling by setting this value to to something greater than 1. Currently, thread mode must be MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled (‘MHD_start_daemon’ returns ‘NULL’ for an unsupported thread mode). ‘MHD_OPTION_ARRAY’ This option can be used for initializing MHD using options from an array. A common use for this is writing an FFI for MHD. The actual options given are in an array of 'struct MHD_OptionItem', so this option requires a single argument of type 'struct MHD_OptionItem'. The array must be terminated with an entry ‘MHD_OPTION_END’. An example for code using MHD_OPTION_ARRAY is: struct MHD_OptionItem ops[] = { { MHD_OPTION_CONNECTION_LIMIT, 100, NULL }, { MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL }, { MHD_OPTION_END, 0, NULL } }; d = MHD_start_daemon(0, 8080, NULL, NULL, dh, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_END); For options that expect a single pointer argument, the second member of the ‘struct MHD_OptionItem’ is ignored. For options that expect two pointer arguments, the first argument must be cast to ‘intptr_t’. ‘MHD_OPTION_UNESCAPE_CALLBACK’ Specify a function that should be called for unescaping escape sequences in URIs and URI arguments. Note that this function will NOT be used by the MHD_PostProcessor. If this option is not specified, the default method will be used which decodes escape sequences of the form "%HH". This option should be followed by two arguments, the first one must be of the form size_t my_unescaper(void * cls, struct MHD_Connection *c, char *s) where the return value must be ‘strlen(s)’ and ‘s’ should be updated. Note that the unescape function must not lengthen ‘s’ (the result must be shorter than the input and still be 0-terminated). ‘cls’ will be set to the second argument following MHD_OPTION_UNESCAPE_CALLBACK. ‘MHD_OPTION_THREAD_STACK_SIZE’ Maximum stack size for threads created by MHD. This option must be followed by a ‘size_t’). Not specifying this option or using a value of zero means using the system default (which is likely to differ based on your platform). ‘MHD_OPTION_TCP_FASTQUEUE_QUEUE_SIZE’ When the flag ‘MHD_USE_TCP_FASTOPEN’ is used, this option sets the connection handshake queue size for the TCP FASTOPEN connections. Note that a TCP FASTOPEN connection handshake occupies more resources than a TCP handshake as the SYN packets also contain DATA which is kept in the associate state until handshake is completed. If this option is not given the queue size is set to a default value of 10. This option must be followed by a ‘unsigned int’. ‘MHD_OPTION_HTTPS_MEM_DHPARAMS’ Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used by the HTTPS daemon for key exchange. This option must be followed by a ‘const char *’ argument. The argument would be a zero-terminated string with a PEM encoded PKCS3 DH parameters structure suitable for passing to ‘gnutls_dh_parms_import_pkcs3’. ‘MHD_OPTION_LISTENING_ADDRESS_REUSE’ This option must be followed by a ‘unsigned int’ argument. If this option is present and true (nonzero) parameter is given, allow reusing the address:port of the listening socket (using ‘SO_REUSEPORT’ on most platforms, and ‘SO_REUSEADDR’ on Windows). If a false (zero) parameter is given, disallow reusing the the address:port of the listening socket (this usually requires no special action, but ‘SO_EXCLUSIVEADDRUSE’ is needed on Windows). If this option is not present ‘SO_REUSEADDR’ is used on all platforms except Windows so reusing of address:port is disallowed. -- C Struct: MHD_OptionItem Entry in an MHD_OPTION_ARRAY. See the ‘MHD_OPTION_ARRAY’ option argument for its use. The ‘option’ member is used to specify which option is specified in the array. The other members specify the respective argument. Note that for options taking only a single pointer, the ‘ptr_value’ member should be set. For options taking two pointer arguments, the first pointer must be cast to ‘intptr_t’ and both the ‘value’ and the ‘ptr_value’ members should be used to pass the two pointers. -- Enumeration: MHD_ValueKind The ‘MHD_ValueKind’ specifies the source of the key-value pairs in the HTTP protocol. ‘MHD_HEADER_KIND’ HTTP header. ‘MHD_COOKIE_KIND’ Cookies. Note that the original HTTP header containing the cookie(s) will still be available and intact. ‘MHD_POSTDATA_KIND’ ‘POST’ data. This is available only if a content encoding supported by MHD is used (currently only URL encoding), and only if the posted content fits within the available memory pool. Note that in that case, the upload data given to the ‘MHD_AccessHandlerCallback()’ will be empty (since it has already been processed). ‘MHD_GET_ARGUMENT_KIND’ ‘GET’ (URI) arguments. ‘MHD_FOOTER_KIND’ HTTP footer (only for http 1.1 chunked encodings). -- Enumeration: MHD_RequestTerminationCode The ‘MHD_RequestTerminationCode’ specifies reasons why a request has been terminated (or completed). ‘MHD_REQUEST_TERMINATED_COMPLETED_OK’ We finished sending the response. ‘MHD_REQUEST_TERMINATED_WITH_ERROR’ Error handling the connection (resources exhausted, other side closed connection, application error accepting request, etc.) ‘MHD_REQUEST_TERMINATED_TIMEOUT_REACHED’ No activity on the connection for the number of seconds specified using ‘MHD_OPTION_CONNECTION_TIMEOUT’. ‘MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN’ We had to close the session since MHD was being shut down. -- Enumeration: MHD_ResponseMemoryMode The ‘MHD_ResponeMemoryMode’ specifies how MHD should treat the memory buffer given for the response in ‘MHD_create_response_from_buffer’. ‘MHD_RESPMEM_PERSISTENT’ Buffer is a persistent (static/global) buffer that won't change for at least the lifetime of the response, MHD should just use it, not free it, not copy it, just keep an alias to it. ‘MHD_RESPMEM_MUST_FREE’ Buffer is heap-allocated with ‘malloc’ (or equivalent) and should be freed by MHD after processing the response has concluded (response reference counter reaches zero). ‘MHD_RESPMEM_MUST_COPY’ Buffer is in transient memory, but not on the heap (for example, on the stack or non-malloc allocated) and only valid during the call to ‘MHD_create_response_from_buffer’. MHD must make its own private copy of the data for processing. -- Enumeration: MHD_ResponseFlags Response-specific flags. Passed as an argument to ‘MHD_set_response_options()’. ‘MHD_RF_NONE’ No special handling. ‘MHD_RF_HTTP_VERSION_1_0_ONLY’ Only respond in conservative HTTP 1.0-mode. In particular, do not (automatically) sent "Connection" headers and always close the connection after generating the response. By default, MHD will respond using the same HTTP version which was set in the request. You can also set the ‘MHD_RF_HTTP_VERSION_1_0_RESPONSE’ flag to force version 1.0 in the response. ‘MHD_RF_HTTP_VERSION_1_0_RESPONSE’ Only respond in HTTP 1.0-mode. Contrary to the ‘MHD_RF_HTTP_VERSION_1_0_ONLY’ flag, the response's HTTP version will always be set to 1.0 and "Connection" headers are still supported. You can even combine this option with MHD_RF_HTTP_VERSION_1_0_ONLY to change the response's HTTP version while maintaining strict compliance with HTTP 1.0 regarding connection management. This solution is not perfect as this flag is set on the response which is created after header processing. So MHD will behave as a HTTP 1.1 server until the response is queued. It means that an invalid HTTP 1.1 request will fail even if the response is sent with HTTP 1.0 and the request would be valid if interpreted with this version. For example, this request will fail in strict mode: GET / HTTP/1.1 as the "Host" header is missing and is mandatory in HTTP 1.1, but it should succeed when interpreted with HTTP 1.0. ‘MHD_RF_INSANITY_HEADER_CONTENT_LENGTH’ Disable sanity check preventing clients from manually setting the HTTP content length option. -- Enumeration: MHD_ResponseOptions Response-specific options. Passed in the varargs portion of ‘MHD_set_response_options()’. ‘MHD_RO_END’ No more options / last option. This is used to terminate the VARARGs list. -- Enumeration: MHD_WEBSOCKET_FLAG Options for the MHD websocket stream. This is used for initialization of a websocket stream when calling ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’ and alters the behavior of the websocket stream. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_FLAG_SERVER’ The websocket stream is initialized in server mode (default). Thus all outgoing payload will not be masked. All incoming payload must be masked. This flag cannot be used together with ‘MHD_WEBSOCKET_FLAG_CLIENT’. ‘MHD_WEBSOCKET_FLAG_CLIENT’ The websocket stream is initialized in client mode. You will usually never use that mode in combination with _libmicrohttpd_, because _libmicrohttpd_ provides a server and not a client. In client mode all outgoing payload will be masked (XOR-ed with random values). All incoming payload must be unmasked. If you use this mode, you must always call ‘MHD_websocket_stream_init2’ instead of ‘MHD_websocket_stream_init’, because you need to pass a random number generator callback function for masking. This flag cannot be used together with ‘MHD_WEBSOCKET_FLAG_SERVER’. ‘MHD_WEBSOCKET_FLAG_NO_FRAGMENTS’ You don't want to get fragmented data while decoding (default). Fragmented frames will be internally put together until they are complete. Whether or not data is fragmented is decided by the sender of the data during encoding. This cannot be used together with ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’. ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ You want fragmented data, if it appears while decoding. You will receive the content of the fragmented frame, but if you are decoding text, you will never get an unfinished UTF-8 sequence (if the sequence appears between two fragments). Instead the text will end before the unfinished UTF-8 sequence. With the next fragment, which finishes the UTF-8 sequence, you will get the complete UTF-8 sequence. This cannot be used together with ‘MHD_WEBSOCKET_FLAG_NO_FRAGMENTS’. ‘MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR’ If the websocket stream becomes invalid during decoding due to protocol errors, a matching close frame will automatically be generated. The close frame will be returned via the parameters ‘payload’ and ‘payload_len’ of ‘MHD_websocket_decode’ and the return value is negative (a value of ‘enum MHD_WEBSOCKET_STATUS’). The generated close frame must be freed by the caller with ‘MHD_websocket_free’. -- Enumeration: MHD_WEBSOCKET_FRAGMENTATION This enumeration is used to specify the fragmentation behavior when encoding of data (text/binary) for a websocket stream. This is used with ‘MHD_websocket_encode_text’ or ‘MHD_websocket_encode_binary’. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_FRAGMENTATION_NONE’ You don't want to use fragmentation. The encoded frame consists of only one frame. ‘MHD_WEBSOCKET_FRAGMENTATION_FIRST’ You want to use fragmentation. The encoded frame is the first frame of a series of data frames of the same type (text or binary). You may send control frames (ping, pong or close) between these data frames. ‘MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING’ You want to use fragmentation. The encoded frame is not the first frame of the series of data frames, but also not the last one. You may send control frames (ping, pong or close) between these data frames. ‘MHD_WEBSOCKET_FRAGMENTATION_LAST’ You want to use fragmentation. The encoded frame is the last frame of the series of data frames, but also not the first one. After this frame, you may send all types of frames again. -- Enumeration: MHD_WEBSOCKET_STATUS This enumeration is used for the return value of almost every websocket stream function. Errors are negative and values equal to or above zero mean a success. Positive values are only used by ‘MHD_websocket_decode’. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_STATUS_OK’ The call succeeded. Especially for ‘MHD_websocket_decode’ this means that no error occurred, but also no frame has been completed yet. For other functions this means simply a success. ‘MHD_WEBSOCKET_STATUS_TEXT_FRAME’ ‘MHD_websocket_decode’ has decoded a text frame. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded text (if any). You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_BINARY_FRAME’ ‘MHD_websocket_decode’ has decoded a binary frame. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded binary data (if any). You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_CLOSE_FRAME’ ‘MHD_websocket_decode’ has decoded a close frame. This means you must close the socket using ‘MHD_upgrade_action’ with ‘MHD_UPGRADE_ACTION_CLOSE’. You may respond with a close frame before closing. The parameters ‘payload’ and ‘payload_len’ are filled with the close reason (if any). The close reason starts with a two byte sequence of close code in network byte order (see ‘enum MHD_WEBSOCKET_CLOSEREASON’). After these two bytes a UTF-8 encoded close reason may follow. You can call ‘MHD_websocket_split_close_reason’ to split that close reason. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_PING_FRAME’ ‘MHD_websocket_decode’ has decoded a ping frame. You should respond to this with a pong frame. The pong frame must contain the same binary data as the corresponding ping frame (if it had any). The parameters ‘payload’ and ‘payload_len’ are filled with the binary ping data (if any). You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_PONG_FRAME’ ‘MHD_websocket_decode’ has decoded a pong frame. You should usually only receive pong frames if you sent a ping frame before. The binary data should be equal to your ping frame and can be used to distinguish the response if you sent multiple ping frames. The parameters ‘payload’ and ‘payload_len’ are filled with the binary pong data (if any). You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT’ ‘MHD_websocket_decode’ has decoded a text frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded text (if any). This is like ‘MHD_WEBSOCKET_STATUS_TEXT_FRAME’, but it can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT’ ‘MHD_websocket_decode’ has decoded a binary frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded binary data (if any). This is like ‘MHD_WEBSOCKET_STATUS_BINARY_FRAME’, but it can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT’ ‘MHD_websocket_decode’ has decoded the next text frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded text (if any). This is like ‘MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT’, but it appears only after the first and before the last fragment of a series of fragments. It can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT’ ‘MHD_websocket_decode’ has decoded the next binary frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded binary data (if any). This is like ‘MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT’, but it appears only after the first and before the last fragment of a series of fragments. It can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT’ ‘MHD_websocket_decode’ has decoded the last text frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded text (if any). This is like ‘MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT’, but it appears only for the last fragment of a series of fragments. It can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT’ ‘MHD_websocket_decode’ has decoded the last binary frame fragment. The parameters ‘payload’ and ‘payload_len’ are filled with the decoded binary data (if any). This is like ‘MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT’, but it appears only for the last fragment of a series of fragments. It can only appear if you specified ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. You must free the returned ‘payload’ after use with ‘MHD_websocket_free’. ‘MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR’ The call failed and the stream is invalid now for decoding. You must close the websocket now using ‘MHD_upgrade_action’ with ‘MHD_UPGRADE_ACTION_CLOSE’. You may send a close frame before closing. This is only used by ‘MHD_websocket_decode’ and happens if the stream contains errors (i. e. invalid byte data). ‘MHD_WEBSOCKET_STATUS_STREAM_BROKEN’ You tried to decode something, but the stream has already been marked invalid. You must close the websocket now using ‘MHD_upgrade_action’ with ‘MHD_UPGRADE_ACTION_CLOSE’. You may send a close frame before closing. This is only used by ‘MHD_websocket_decode’ and happens if you call ‘MDM_websocket_decode’ again after has been invalidated. You can call ‘MHD_websocket_stream_is_valid’ at any time to check whether a stream is invalid or not. ‘MHD_WEBSOCKET_STATUS_MEMORY_ERROR’ A memory allocation failed. The stream remains valid. If this occurred while decoding, the decoding could be possible later if enough memory is available. This could happen while decoding if you received a too big data frame. You could try to specify max_payload_size during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’ to avoid this and close the websocket instead. ‘MHD_WEBSOCKET_STATUS_PARAMETER_ERROR’ You passed invalid parameters during the function call (i. e. a NULL pointer for a required parameter). The stream remains valid. ‘MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED’ The maximum payload size has been exceeded. If you got this return code from ‘MHD_websocket_decode’ then the stream becomes invalid and the websocket must be closed using ‘MHD_upgrade_action’ with ‘MHD_UPGRADE_ACTION_CLOSE’. You may send a close frame before closing. The maximum payload size is specified during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. This can also appear if you specified 0 as maximum payload size when the message is greater than the maximum allocatable memory size (i. e. more than 4 GiB on 32 bit systems). If you got this return code from ‘MHD_websocket_encode_close’, ‘MHD_websocket_encode_ping’ or ‘MHD_websocket_encode_pong’ then you passed to much payload data. The stream remains valid then. ‘MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR’ An UTF-8 sequence is invalid. If you got this return code from ‘MHD_websocket_decode’ then the stream becomes invalid and you must close the websocket using ‘MHD_upgrade_action’ with ‘MHD_UPGRADE_ACTION_CLOSE’. You may send a close frame before closing. If you got this from ‘MHD_websocket_encode_text’ or ‘MHD_websocket_encode_close’ then you passed invalid UTF-8 text. The stream remains valid then. ‘MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER’ A check routine for the HTTP headers came to the conclusion that the header value isn't valid for a websocket handshake request. This value can only be returned from the following functions: ‘MHD_websocket_check_http_version’, ‘MHD_websocket_check_connection_header’, ‘MHD_websocket_check_upgrade_header’, ‘MHD_websocket_check_version_header’, ‘MHD_websocket_create_accept_header’ -- Enumeration: MHD_WEBSOCKET_CLOSEREASON Enumeration of possible close reasons for websocket close frames. The possible values are specified in RFC 6455 7.4.1 These close reasons here are the default set specified by RFC 6455, but also other close reasons could be used. The definition is for short: • 0-999 are never used (if you pass 0 in ‘MHD_websocket_encode_close’ then no close reason is used). • 1000-2999 are specified by RFC 6455. • 3000-3999 are specified by libraries, etc. but must be registered by IANA. • 4000-4999 are reserved for private use. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_CLOSEREASON_NO_REASON’ This value is used as placeholder for ‘MHD_websocket_encode_close’ to tell that you don't want to specify any reason. If you use this value then no reason text may be used. This value cannot be a result of decoding, because this value is not a valid close reason for the websocket protocol. ‘MHD_WEBSOCKET_CLOSEREASON_REGULAR’ You close the websocket because it fulfilled its purpose and shall now be closed in a normal, planned way. ‘MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY’ You close the websocket because you are shutting down the server or something similar. ‘MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR’ You close the websocket because a protocol error occurred during decoding (i. e. invalid byte data). ‘MHD_WEBSOCKET_CLOSEREASON_UNSUPPORTED_DATATYPE’ You close the websocket because you received data which you don't accept. For example if you received a binary frame, but your application only expects text frames. ‘MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8’ You close the websocket because it contains malformed UTF-8. The UTF-8 validity is automatically checked by ‘MHD_websocket_decode’, so you don't need to check it on your own. UTF-8 is specified in RFC 3629. ‘MHD_WEBSOCKET_CLOSEREASON_POLICY_VIOLATED’ You close the websocket because you received a frame which is too big to process. You can specify the maximum allowed payload size during the call of ‘MHD_websocket_stream_init’ or ‘MHD_websocket_stream_init2’. ‘MHD_WEBSOCKET_CLOSEREASON_MISSING_EXTENSION’ This status code can be sent by the client if it expected a specific extension, but this extension hasn't been negotiated. ‘MHD_WEBSOCKET_CLOSEREASON_UNEXPECTED_CONDITION’ The server closes the websocket because it encountered an unexpected condition that prevented it from fulfilling the request. -- Enumeration: MHD_WEBSOCKET_UTF8STEP Enumeration of possible UTF-8 check steps for websocket functions These values are used during the encoding of fragmented text frames or for error analysis while encoding text frames. Its values specify the next step of the UTF-8 check. UTF-8 sequences consist of one to four bytes. This enumeration just says how long the current UTF-8 sequence is and what is the next expected byte. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_UTF8STEP_NORMAL’ There is no open UTF-8 sequence. The next byte must be 0x00-0x7F or 0xC2-0xF4. ‘MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1’ The second byte of a two byte UTF-8 sequence. The first byte was 0xC2-0xDF. The next byte must be 0x80-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2’ The second byte of a three byte UTF-8 sequence. The first byte was 0xE0. The next byte must be 0xA0-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2’ The second byte of a three byte UTF-8 sequence. The first byte was 0xED. The next byte must by 0x80-0x9F. ‘MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2’ The second byte of a three byte UTF-8 sequence. The first byte was 0xE1-0xEC or 0xEE-0xEF. The next byte must be 0x80-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2’ The third byte of a three byte UTF-8 sequence. The next byte must be 0x80-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3’ The second byte of a four byte UTF-8 sequence. The first byte was 0xF0. The next byte must be 0x90-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3’ The second byte of a four byte UTF-8 sequence. The first byte was 0xF4. The next byte must be 0x80-0x8F. ‘MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3’ The second byte of a four byte UTF-8 sequence. The first byte was 0xF1-0xF3. The next byte must be 0x80-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3’ The third byte of a four byte UTF-8 sequence. The next byte must be 0x80-0xBF. ‘MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3’ The fourth byte of a four byte UTF-8 sequence. The next byte must be 0x80-0xBF. -- Enumeration: MHD_WEBSOCKET_VALIDITY Enumeration of validity values of a websocket stream These values are used for ‘MHD_websocket_stream_is_valid’ and specify the validity status. Note that websocket streams are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. ‘MHD_WEBSOCKET_VALIDITY_INVALID’ The stream is invalid. It cannot be used for decoding anymore. ‘MHD_WEBSOCKET_VALIDITY_VALID’ The stream is valid. Decoding works as expected. ‘MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES’ The stream has received a close frame and is partly invalid. You can still use the stream for decoding, but if a data frame is received an error will be reported. After a close frame has been sent, no data frames may follow from the sender of the close frame.  File: libmicrohttpd.info, Node: microhttpd-struct, Next: microhttpd-cb, Prev: microhttpd-const, Up: Top 3 Structures type definition **************************** -- C Struct: MHD_Daemon Handle for the daemon (listening on a socket for HTTP traffic). -- C Struct: MHD_Connection Handle for a connection / HTTP request. With HTTP/1.1, multiple requests can be run over the same connection. However, MHD will only show one request per TCP connection to the client at any given time. -- C Struct: MHD_Response Handle for a response. -- C Struct: MHD_IoVec An element of an array of memory buffers. -- C Struct: MHD_PostProcessor Handle for ‘POST’ processing. -- C Union: MHD_ConnectionInfo Information about a connection. -- C Union: MHD_DaemonInfo Information about an MHD daemon. -- C Struct: MHD_WebSocketStream Information about a MHD websocket stream.  File: libmicrohttpd.info, Node: microhttpd-cb, Next: microhttpd-init, Prev: microhttpd-struct, Up: Top 4 Callback functions definition ******************************* -- Function Pointer: enum MHD_Result *MHD_AcceptPolicyCallback (void *cls, const struct sockaddr * addr, socklen_t addrlen) Invoked in the context of a connection to allow or deny a client to connect. This callback return ‘MHD_YES’ if connection is allowed, ‘MHD_NO’ if not. CLS custom value selected at callback registration time; ADDR address information from the client; ADDRLEN length of the address information. -- Function Pointer: enum MHD_Result *MHD_AccessHandlerCallback (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) Invoked in the context of a connection to answer a request from the client. This callback must call MHD functions (example: the ‘MHD_Response’ ones) to provide content to give back to the client and return an HTTP status code (i.e. ‘200’ for OK, ‘404’, etc.). *note microhttpd-post::, for details on how to code this callback. Must return ‘MHD_YES’ if the connection was handled successfully, ‘MHD_NO’ if the socket must be closed due to a serious error while handling the request CLS custom value selected at callback registration time; URL the URL requested by the client; METHOD the HTTP method used by the client (‘GET’, ‘PUT’, ‘DELETE’, ‘POST’, etc.); VERSION the HTTP version string (i.e. ‘HTTP/1.1’); UPLOAD_DATA the data being uploaded (excluding headers): ‘POST’ data *will* be made available incrementally in UPLOAD_DATA; even if ‘POST’ data is available, the first time the callback is invoked there won't be upload data, as this is done just after MHD parses the headers. If supported by the client and the HTTP version, the application can at this point queue an error response to possibly avoid the upload entirely. If no response is generated, MHD will (if required) automatically send a 100 CONTINUE reply to the client. Afterwards, POST data will be passed to the callback to be processed incrementally by the application. The application may return ‘MHD_NO’ to forcefully terminate the TCP connection without generating a proper HTTP response. Once all of the upload data has been provided to the application, the application will be called again with 0 bytes of upload data. At this point, a response should be queued to complete the handling of the request. UPLOAD_DATA_SIZE set initially to the size of the UPLOAD_DATA provided; this callback must update this value to the number of bytes *NOT* processed; unless external select is used, the callback maybe required to process at least some data. If the callback fails to process data in multi-threaded or internal-select mode and if the read-buffer is already at the maximum size that MHD is willing to use for reading (about half of the maximum amount of memory allowed for the connection), then MHD will abort handling the connection and return an internal server error to the client. In order to avoid this, clients must be able to process upload data incrementally and reduce the value of ‘upload_data_size’. REQ_CLS reference to a pointer, initially set to ‘NULL’, that this callback can set to some address and that will be preserved by MHD for future calls for this request; since the access handler may be called many times (i.e., for a ‘PUT’/‘POST’ operation with plenty of upload data) this allows the application to easily associate some request-specific state; if necessary, this state can be cleaned up in the global ‘MHD_RequestCompletedCallback’ (which can be set with the ‘MHD_OPTION_NOTIFY_COMPLETED’). -- Function Pointer: void *MHD_RequestCompletedCallback (void *cls, struct MHD_Connectionconnection, void **req_cls, enum MHD_RequestTerminationCode toe) Signature of the callback used by MHD to notify the application about completed requests. CLS custom value selected at callback registration time; CONNECTION connection handle; REQ_CLS value as set by the last call to the ‘MHD_AccessHandlerCallback’; TOE reason for request termination see ‘MHD_OPTION_NOTIFY_COMPLETED’. -- Function Pointer: enum MHD_Result *MHD_KeyValueIterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *value, size_t value_size) Iterator over key-value pairs. This iterator can be used to iterate over all of the cookies, headers, or ‘POST’-data fields of a request, and also to iterate over the headers that have been added to a response. CLS custom value specified when iteration was triggered; KIND kind of the header we are looking at KEY key for the value, can be an empty string VALUE value corresponding value, can be NULL VALUE_SIZE number of bytes in ‘value’. This argument was introduced in ‘MHD_VERSION’ 0x00096301 to allow applications to use binary zeros in values. Applications using this argument must ensure that they are using a sufficiently recent version of MHD, i.e. by testing ‘MHD_get_version()’ for values above or equal to 0.9.64. Applications that do not need zeros in values and that want to compile without warnings against newer versions of MHD should not declare this argument and cast the function pointer argument to ‘MHD_KeyValueIterator’. Return ‘MHD_YES’ to continue iterating, ‘MHD_NO’ to abort the iteration. -- Function Pointer: ssize_t *MHD_ContentReaderCallback (void *cls, uint64_t pos, char *buf, size_t max) Callback used by MHD in order to obtain content. The callback has to copy at most MAX bytes of content into BUF. The total number of bytes that has been placed into BUF should be returned. Note that returning zero will cause MHD to try again. Thus, returning zero should only be used in conjunction with ‘MHD_suspend_connection()’ to avoid busy waiting. While usually the callback simply returns the number of bytes written into BUF, there are two special return value: ‘MHD_CONTENT_READER_END_OF_STREAM’ (-1) should be returned for the regular end of transmission (with chunked encoding, MHD will then terminate the chunk and send any HTTP footers that might be present; without chunked encoding and given an unknown response size, MHD will simply close the connection; note that while returning ‘MHD_CONTENT_READER_END_OF_STREAM’ is not technically legal if a response size was specified, MHD accepts this and treats it just as ‘MHD_CONTENT_READER_END_WITH_ERROR’. ‘MHD_CONTENT_READER_END_WITH_ERROR’ (-2) is used to indicate a server error generating the response; this will cause MHD to simply close the connection immediately. If a response size was given or if chunked encoding is in use, this will indicate an error to the client. Note, however, that if the client does not know a response size and chunked encoding is not in use, then clients will not be able to tell the difference between ‘MHD_CONTENT_READER_END_WITH_ERROR’ and ‘MHD_CONTENT_READER_END_OF_STREAM’. This is not a limitation of MHD but rather of the HTTP protocol. CLS custom value selected at callback registration time; POS position in the datastream to access; note that if an ‘MHD_Response’ object is re-used, it is possible for the same content reader to be queried multiple times for the same data; however, if an ‘MHD_Response’ is not re-used, MHD guarantees that POS will be the sum of all non-negative return values obtained from the content reader so far. Return ‘-1’ on error (MHD will no longer try to read content and instead close the connection with the client). -- Function Pointer: void *MHD_ContentReaderFreeCallback (void *cls) This method is called by MHD if we are done with a content reader. It should be used to free resources associated with the content reader. -- Function Pointer: enum MHD_Result *MHD_PostDataIterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) Iterator over key-value pairs where the value maybe made available in increments and/or may not be zero-terminated. Used for processing ‘POST’ data. CLS custom value selected at callback registration time; KIND type of the value; KEY zero-terminated key for the value; FILENAME name of the uploaded file, ‘NULL’ if not known; CONTENT_TYPE mime-type of the data, ‘NULL’ if not known; TRANSFER_ENCODING encoding of the data, ‘NULL’ if not known; DATA pointer to size bytes of data at the specified offset; OFF offset of data in the overall value; SIZE number of bytes in data available. Return ‘MHD_YES’ to continue iterating, ‘MHD_NO’ to abort the iteration. -- Function Pointer: void* *MHD_WebSocketMallocCallback (size_t buf_len) This callback function is used internally by many websocket functions for allocating data. By default ‘malloc’ is used. You can use your own allocation function with ‘MHD_websocket_stream_init2’ if you wish to. This can be useful for operating systems like Windows where ‘malloc’, ‘realloc’ and ‘free’ are compiler-dependent. You can call the associated ‘malloc’ callback of a websocket stream with ‘MHD_websocket_malloc’. BUF_LEN size of the buffer to allocate in bytes. Return the pointer of the allocated buffer or ‘NULL’ on failure. -- Function Pointer: void* *MHD_WebSocketReallocCallback (void *buf, size_t new_buf_len) This callback function is used internally by many websocket functions for reallocating data. By default ‘realloc’ is used. You can use your own reallocation function with ‘MHD_websocket_stream_init2’ if you wish to. This can be useful for operating systems like Windows where ‘malloc’, ‘realloc’ and ‘free’ are compiler-dependent. You can call the associated ‘realloc’ callback of a websocket stream with ‘MHD_websocket_realloc’. BUF current buffer, may be ‘NULL’; NEW_BUF_LEN new size of the buffer in bytes. Return the pointer of the reallocated buffer or ‘NULL’ on failure. On failure the old pointer must remain valid. -- Function Pointer: void *MHD_WebSocketFreeCallback (void *buf) This callback function is used internally by many websocket functions for freeing data. By default ‘free’ is used. You can use your own free function with ‘MHD_websocket_stream_init2’ if you wish to. This can be useful for operating systems like Windows where ‘malloc’, ‘realloc’ and ‘free’ are compiler-dependent. You can call the associated ‘free’ callback of a websocket stream with ‘MHD_websocket_free’. CLS current buffer to free, this may be ‘NULL’ then nothing happens. -- Function Pointer: size_t *MHD_WebSocketRandomNumberGenerator (void *cls, void* buf, size_t buf_len) This callback function is used for generating random numbers for masking payload data in client mode. If you use websockets in server mode with _libmicrohttpd_ then you don't need a random number generator, because the server doesn't mask its outgoing messages. However if you wish to use a websocket stream in client mode, you must pass this callback function to ‘MHD_websocket_stream_init2’. CLS closure specified in ‘MHD_websocket_stream_init2’; BUF buffer to fill with random values; BUF_LEN size of buffer in bytes. Return the number of generated random bytes. The return value should usually equal to buf_len.  File: libmicrohttpd.info, Node: microhttpd-init, Next: microhttpd-inspect, Prev: microhttpd-cb, Up: Top 5 Starting and stopping the server ********************************** -- Function: void MHD_set_panic_func (MHD_PanicCallback cb, void *cls) Set a handler for fatal errors. CB function to call if MHD encounters a fatal internal error. If no handler was set explicitly, MHD will call ‘abort’. CLS closure argument for cb; the other arguments are the name of the source file, line number and a string describing the nature of the fatal error (which can be ‘NULL’) -- Function: struct MHD_Daemon * MHD_start_daemon (unsigned int flags, unsigned short port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...) Start a webserver on the given port. FLAGS OR-ed combination of ‘MHD_FLAG’ values; PORT port to bind to; APC callback to call to check which clients will be allowed to connect; you can pass ‘NULL’ in which case connections from any IP will be accepted; APC_CLS extra argument to APC; DH default handler for all URIs; DH_CLS extra argument to DH. Additional arguments are a list of options (type-value pairs, terminated with ‘MHD_OPTION_END’). It is mandatory to use ‘MHD_OPTION_END’ as last argument, even when there are no additional arguments. Return ‘NULL’ on error, handle to daemon on success. -- Function: MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon) Stop accepting connections from the listening socket. Allows clients to continue processing, but stops accepting new connections. Note that the caller is responsible for closing the returned socket; however, if MHD is run using threads (anything but external select mode), it must not be closed until AFTER ‘MHD_stop_daemon’ has been called (as it is theoretically possible that an existing thread is still using it). This function is useful in the special case that a listen socket is to be migrated to another process (i.e. a newer version of the HTTP server) while existing connections should continue to be processed until they are finished. Return ‘-1’ on error (daemon not listening), the handle to the listen socket otherwise. -- Function: void MHD_stop_daemon (struct MHD_Daemon *daemon) Shutdown an HTTP daemon. -- Function: enum MHD_Result MHD_run (struct MHD_Daemon *daemon) Run webserver operations (without blocking unless in client callbacks). This method should be called by clients in combination with ‘MHD_get_fdset()’ if the client-controlled ‘select’-method is used. This function will work for external ‘poll’ and ‘select’ mode. However, if using external ‘select’ mode, you may want to instead use ‘MHD_run_from_select’, as it is more efficient. DAEMON daemon to process connections of Return ‘MHD_YES’ on success, ‘MHD_NO’ if this daemon was not started with the right options for this call. -- Function: enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) Run webserver operations given sets of ready socket handles. This method should be called by clients in combination with ‘MHD_get_fdset’ if the client-controlled (external) select method is used. You can use this function instead of ‘MHD_run’ if you called ‘select’ on the result from ‘MHD_get_fdset’. File descriptors in the sets that are not controlled by MHD will be ignored. Calling this function instead of ‘MHD_run’ is more efficient as MHD will not have to call ‘select’ again to determine which operations are ready. DAEMON daemon to process connections of READ_FD_SET set of descriptors that must be ready for reading without blocking WRITE_FD_SET set of descriptors that must be ready for writing without blocking EXCEPT_FD_SET ignored, can be NULL Return ‘MHD_YES’ on success, ‘MHD_NO’ on serious internal errors. -- Function: void MHD_add_connection (struct MHD_Daemon *daemon, int client_socket, const struct sockaddr *addr, socklen_t addrlen) Add another client connection to the set of connections managed by MHD. This API is usually not needed (since MHD will accept inbound connections on the server socket). Use this API in special cases, for example if your HTTP server is behind NAT and needs to connect out to the HTTP client, or if you are building a proxy. If you use this API in conjunction with a internal select or a thread pool, you must set the option ‘MHD_USE_ITC’ to ensure that the freshly added connection is immediately processed by MHD. The given client socket will be managed (and closed!) by MHD after this call and must no longer be used directly by the application afterwards. DAEMON daemon that manages the connection CLIENT_SOCKET socket to manage (MHD will expect to receive an HTTP request from this socket next). ADDR IP address of the client ADDRLEN number of bytes in addr This function will return ‘MHD_YES’ on success, ‘MHD_NO’ if this daemon could not handle the connection (i.e. malloc failed, etc). The socket will be closed in any case; 'errno' is set to indicate further details about the error.  File: libmicrohttpd.info, Node: microhttpd-inspect, Next: microhttpd-requests, Prev: microhttpd-init, Up: Top 6 Implementing external ‘select’ ******************************** -- Function: enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd) Obtain the ‘select()’ sets for this daemon. The daemon's socket is added to READ_FD_SET. The list of currently existent connections is scanned and their file descriptors added to the correct set. When calling this function, FD_SETSIZE is assumed to be platform's default. If you changed FD_SETSIZE for your application, you should use ‘MHD_get_fdset2()’ instead. This function should only be called in when MHD is configured to use external select with ‘select()’ or with ‘epoll()’. In the latter case, it will only add the single ‘epoll()’ file descriptor used by MHD to the sets. After the call completed successfully: the variable referenced by MAX_FD references the file descriptor with highest integer identifier. The variable must be set to zero before invoking this function. Return ‘MHD_YES’ on success, ‘MHD_NO’ if: the arguments are invalid (example: ‘NULL’ pointers); this daemon was not started with the right options for this call. -- Function: enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd, unsigned int fd_setsize) Like ‘MHD_get_fdset()’, except that you can manually specify the value of FD_SETSIZE used by your application. -- Function: enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, unsigned long long *timeout) Obtain timeout value for select for this daemon (only needed if connection timeout is used). The returned value is how many milliseconds ‘select’ should at most block, not the timeout value set for connections. This function must not be called if the ‘MHD_USE_THREAD_PER_CONNECTION’ mode is in use (since then it is not meaningful to ask for a timeout, after all, there is concurrenct activity). The function must also not be called by user-code if ‘MHD_USE_INTERNAL_POLLING_THREAD’ is in use. In the latter case, the behavior is undefined. DAEMON which daemon to obtain the timeout from. TIMEOUT will be set to the timeout (in milliseconds). Return ‘MHD_YES’ on success, ‘MHD_NO’ if timeouts are not used (or no connections exist that would necessitate the use of a timeout right now).  File: libmicrohttpd.info, Node: microhttpd-requests, Next: microhttpd-responses, Prev: microhttpd-inspect, Up: Top 7 Handling requests ******************* -- Function: int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) Get all the headers matching KIND from the request. The KIND argument can be a bitmask, ORing the various header kinds that are requested. The ITERATOR callback is invoked once for each header, with ITERATOR_CLS as first argument. After version 0.9.19, the headers are iterated in the same order as they were received from the network; previous versions iterated over the headers in reverse order. ‘MHD_get_connection_values’ returns the number of entries iterated over; this can be less than the number of headers if, while iterating, ITERATOR returns ‘MHD_NO’. ITERATOR can be ‘NULL’: in this case this function just counts and returns the number of headers. In the case of ‘MHD_GET_ARGUMENT_KIND’, the VALUE argument will be ‘NULL’ if the URL contained a key without an equals operator. For example, for a HTTP request to the URL "http://foo/bar?key", the VALUE argument is ‘NULL’; in contrast, a HTTP request to the URL "http://foo/bar?key=", the VALUE argument is the empty string. The normal case is that the URL contains "http://foo/bar?key=value" in which case VALUE would be the string "value" and KEY would contain the string "key". -- Function: enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value) This function can be used to append an entry to the list of HTTP headers of a connection (so that the ‘MHD_get_connection_values function’ will return them - and the MHD PostProcessor will also see them). This maybe required in certain situations (see Mantis #1399) where (broken) HTTP implementations fail to supply values needed by the post processor (or other parts of the application). This function MUST only be called from within the MHD_AccessHandlerCallback (otherwise, access maybe improperly synchronized). Furthermore, the client must guarantee that the key and value arguments are 0-terminated strings that are NOT freed until the connection is closed. (The easiest way to do this is by passing only arguments to permanently allocated strings.). CONNECTION is the connection for which the entry for KEY of the given KIND should be set to the given VALUE. The function returns ‘MHD_NO’ if the operation could not be performed due to insufficient memory and ‘MHD_YES’ on success. -- Function: const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key) Get a particular header value. If multiple values match the KIND, return one of them (the "first", whatever that means). KEY must reference a zero-terminated ASCII-coded string representing the header to look for: it is compared against the headers using (basically) ‘strcasecmp()’, so case is ignored. -- Function: const char * MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) Get a particular header value. If multiple values match the KIND, return one of them (the "first", whatever that means). KEY must reference an ASCII-coded string representing the header to look for: it is compared against the headers using (basically) ‘strncasecmp()’, so case is ignored. The VALUE_PTR is set to the address of the value found, and VALUE_SIZE_PTR is set to the number of bytes in the value.  File: libmicrohttpd.info, Node: microhttpd-responses, Next: microhttpd-flow, Prev: microhttpd-requests, Up: Top 8 Building responses to requests ******************************** Response objects handling by MHD is asynchronous with respect to the application execution flow. Instances of the ‘MHD_Response’ structure are not associated to a daemon and neither to a client connection: they are managed with reference counting. In the simplest case: we allocate a new ‘MHD_Response’ structure for each response, we use it once and finally we destroy it. MHD allows more efficient resources usages. Example: we allocate a new ‘MHD_Response’ structure for each response *kind*, we use it every time we have to give that response and we finally destroy it only when the daemon shuts down. * Menu: * microhttpd-response enqueue:: Enqueuing a response. * microhttpd-response create:: Creating a response object. * microhttpd-response headers:: Adding headers to a response. * microhttpd-response options:: Setting response options. * microhttpd-response inspect:: Inspecting a response object. * microhttpd-response upgrade:: Creating a response for protocol upgrades.  File: libmicrohttpd.info, Node: microhttpd-response enqueue, Next: microhttpd-response create, Up: microhttpd-responses 8.1 Enqueuing a response ======================== -- Function: enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response) Queue a response to be transmitted to the client as soon as possible but only after MHD_AccessHandlerCallback returns. This function checks that it is legal to queue a response at this time for the given connection. It also increments the internal reference counter for the response object (the counter will be decremented automatically once the response has been transmitted). CONNECTION the connection identifying the client; STATUS_CODE HTTP status code (i.e. ‘200’ for OK); RESPONSE response to transmit. Return ‘MHD_YES’ on success or if message has been queued. Return ‘MHD_NO’: if arguments are invalid (example: ‘NULL’ pointer); on error (i.e. reply already sent). -- Function: void MHD_destroy_response (struct MHD_Response *response) Destroy a response object and associated resources (decrement the reference counter). Note that MHD may keep some of the resources around if the response is still in the queue for some clients, so the memory may not necessarily be freed immediately. An explanation of reference counting(1): 1. a ‘MHD_Response’ object is allocated: struct MHD_Response * response = MHD_create_response_from_buffer(...); /* here: reference counter = 1 */ 2. the ‘MHD_Response’ object is enqueued in a ‘MHD_Connection’: MHD_queue_response(connection, , response); /* here: reference counter = 2 */ 3. the creator of the response object discharges responsibility for it: MHD_destroy_response(response); /* here: reference counter = 1 */ 4. the daemon handles the connection sending the response's data to the client then decrements the reference counter by calling ‘MHD_destroy_response()’: the counter's value drops to zero and the ‘MHD_Response’ object is released. ---------- Footnotes ---------- (1) Note to readers acquainted to the Tcl API: reference counting on ‘MHD_Connection’ structures is handled in the same way as Tcl handles ‘Tcl_Obj’ structures through ‘Tcl_IncrRefCount()’ and ‘Tcl_DecrRefCount()’.  File: libmicrohttpd.info, Node: microhttpd-response create, Next: microhttpd-response headers, Prev: microhttpd-response enqueue, Up: microhttpd-responses 8.2 Creating a response object ============================== -- Function: struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response, ‘-1’ for unknown; BLOCK_SIZE preferred block size for querying CRC (advisory only, MHD may still call CRC using smaller chunks); this is essentially the buffer size used for IO, clients should pick a value that is appropriate for IO and memory performance requirements; CRC callback to use to obtain response data; CRC_CLS extra argument to CRC; CRFC callback to call to free CRC_CLS resources. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_fd (uint64_t size, int fd) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response (should be smaller or equal to the size of the file) FD file descriptor referring to a file on disk with the data; will be closed when response is destroyed; note that 'fd' must be an actual file descriptor (not a pipe or socket) since MHD might use 'sendfile' or 'seek' on it. The descriptor should be in blocking-IO mode. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_pipe (int fd) Create a response object. The response object can be extended with header information and then it can be used ONLY ONCE. FD file descriptor of the read-end of the pipe; will be closed when response is destroyed. The descriptor should be in blocking-IO mode. Return ‘NULL’ on error (i.e. out of memory). -- Function: struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset) Create a response object. The response object can be extended with header information and then it can be used any number of times. Note that you need to be a bit careful about ‘off_t’ when writing this code. Depending on your platform, MHD is likely to have been compiled with support for 64-bit files. When you compile your own application, you must make sure that ‘off_t’ is also a 64-bit value. If not, your compiler may pass a 32-bit value as ‘off_t’, which will result in 32-bits of garbage. If you use the autotools, use the ‘AC_SYS_LARGEFILE’ autoconf macro and make sure to include the generated ‘config.h’ file before ‘microhttpd.h’ to avoid problems. If you do not have a build system and only want to run on a GNU/Linux system, you could also use #define _FILE_OFFSET_BITS 64 #include #include #include #include to ensure 64-bit ‘off_t’. Note that if your operating system does not support 64-bit files, MHD will be compiled with a 32-bit ‘off_t’ (in which case the above would be wrong). SIZE size of the data portion of the response (number of bytes to transmit from the file starting at offset). FD file descriptor referring to a file on disk with the data; will be closed when response is destroyed; note that 'fd' must be an actual file descriptor (not a pipe or socket) since MHD might use 'sendfile' or 'seek' on it. The descriptor should be in blocking-IO mode. OFFSET offset to start reading from in the file Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *data, enum MHD_ResponseMemoryMode mode) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response; BUFFER the data itself; MODE memory management options for buffer; use MHD_RESPMEM_PERSISTENT if the buffer is static/global memory, use MHD_RESPMEM_MUST_FREE if the buffer is heap-allocated and should be freed by MHD and MHD_RESPMEM_MUST_COPY if the buffer is in transient memory (i.e. on the stack) and must be copied by MHD; Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *data, MHD_ContentReaderFreeCallback crfc) Create a response object. The buffer at the end must be free'd by calling the CRFC function. SIZE size of the data portion of the response; BUFFER the data itself; CRFC function to call at the end to free memory allocated at BUFFER. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy) Create a response object. The response object can be extended with header information and then it can be used any number of times. This function is deprecated, use ‘MHD_create_response_from_buffer’ instead. SIZE size of the data portion of the response; DATA the data itself; MUST_FREE if true: MHD should free data when done; MUST_COPY if true: MHD allocates a block of memory and use it to make a copy of DATA embedded in the returned ‘MHD_Response’ structure; handling of the embedded memory is responsibility of MHD; DATA can be released anytime after this call returns. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). Example: create a response from a statically allocated string: const char * data = "

    Error!

    "; struct MHD_Connection * connection = ...; struct MHD_Response * response; response = MHD_create_response_from_buffer (strlen(data), data, MHD_RESPMEM_PERSISTENT); MHD_queue_response(connection, 404, response); MHD_destroy_response(response); -- Function: struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, int iovcnt, MHD_ContentReaderFreeCallback crfc, void *cls) Create a response object from an array of memory buffers. The response object can be extended with header information and then be used any number of times. IOV the array for response data buffers, an internal copy of this will be made; however, note that the data pointed to by the IOV is not copied and must be preserved unchanged at the given locations until the response is no longer in use and the CRFC is called; IOVCNT the number of elements in IOV; CRFC the callback to call to free resources associated with IOV; CLS the argument to CRFC; Return ‘NULL’ on error (i.e. invalid arguments, out of memory).  File: libmicrohttpd.info, Node: microhttpd-response headers, Next: microhttpd-response options, Prev: microhttpd-response create, Up: microhttpd-responses 8.3 Adding headers to a response ================================ -- Function: enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content) Add a header line to the response. The strings referenced by HEADER and CONTENT must be zero-terminated and they are duplicated into memory blocks embedded in RESPONSE. Notice that the strings must not hold newlines, carriage returns or tab chars. MHD_add_response_header() prevents applications from setting a "Transfer-Encoding" header to values other than "identity" or "chunked" as other transfer encodings are not supported by MHD. Note that usually MHD will pick the transfer encoding correctly automatically, but applications can use the header to force a particular behavior. MHD_add_response_header() also prevents applications from setting a "Content-Length" header. MHD will automatically set a correct "Content-Length" header if it is possible and allowed. Return ‘MHD_NO’ on error (i.e. invalid header or content format or memory allocation error). -- Function: enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content) Add a footer line to the response. The strings referenced by FOOTER and CONTENT must be zero-terminated and they are duplicated into memory blocks embedded in RESPONSE. Notice that the strings must not hold newlines, carriage returns or tab chars. You can add response footers at any time before signalling the end of the response to MHD (not just before calling 'MHD_queue_response'). Footers are useful for adding cryptographic checksums to the reply or to signal errors encountered during data generation. This call was introduced in MHD 0.9.3. Return ‘MHD_NO’ on error (i.e. invalid header or content format or memory allocation error). -- Function: enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content) Delete a header (or footer) line from the response. Return ‘MHD_NO’ on error (arguments are invalid or no such header known).  File: libmicrohttpd.info, Node: microhttpd-response options, Next: microhttpd-response inspect, Prev: microhttpd-response headers, Up: microhttpd-responses 8.4 Setting response options ============================ -- Function: enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...) Set special flags and options for a response. Calling this functions sets the given flags and options for the response. RESPONSE which response should be modified; FLAGS flags to set for the response; Additional arguments are a list of options (type-value pairs, terminated with ‘MHD_RO_END’). It is mandatory to use ‘MHD_RO_END’ as last argument, even when there are no additional arguments. Return ‘MHD_NO’ on error, ‘MHD_YES’ on success.  File: libmicrohttpd.info, Node: microhttpd-response inspect, Next: microhttpd-response upgrade, Prev: microhttpd-response options, Up: microhttpd-responses 8.5 Inspecting a response object ================================ -- Function: int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) Get all of the headers added to a response. Invoke the ITERATOR callback for each header in the response, using ITERATOR_CLS as first argument. Return number of entries iterated over. ITERATOR can be ‘NULL’: in this case the function just counts headers. ITERATOR should not modify the its key and value arguments, unless we know what we are doing. -- Function: const char * MHD_get_response_header (struct MHD_Response *response, const char *key) Find and return a pointer to the value of a particular header from the response. KEY must reference a zero-terminated string representing the header to look for. The search is case sensitive. Return ‘NULL’ if header does not exist or KEY is ‘NULL’. We should not modify the value, unless we know what we are doing.  File: libmicrohttpd.info, Node: microhttpd-response upgrade, Prev: microhttpd-response inspect, Up: microhttpd-responses 8.6 Creating a response for protocol upgrades ============================================= With RFC 2817 a mechanism to switch protocols within HTTP was introduced. Here, a client sends a request with a "Connection: Upgrade" header. The server responds with a "101 Switching Protocols" response header, after which the two parties begin to speak a different (non-HTTP) protocol over the TCP connection. This mechanism is used for upgrading HTTP 1.1 connections to HTTP2 or HTTPS, as well as for implementing WebSockets. Which protocol upgrade is performed is negotiated between server and client in additional headers, in particular the "Upgrade" header. MHD supports switching protocols using this mechanism only if the ‘MHD_ALLOW_SUSPEND_RESUME’ flag has been set when starting the daemon. If this flag has been set, applications can upgrade a connection by queueing a response (using the ‘MHD_HTTP_SWITCHING_PROTOCOLS’ status code) which must have been created with the following function: -- Function: enum MHD_Result MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) Create a response suitable for switching protocols. Returns ‘MHD_YES’ on success. ‘upgrade_handler’ must not be ‘NULL’. When creating this type of response, the "Connection: Upgrade" header will be set automatically for you. MHD requires that you additionally set an "Upgrade:" header. The "Upgrade" header must simply exist, the specific value is completely up to the application. The ‘upgrade_handler’ argument to the above has the following type: -- Function Pointer: void *MHD_UpgradeHandler (void *cls, struct MHD_Connection *connection, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) This function will be called once MHD has transmitted the header of the response to the connection that is being upgraded. At this point, the application is expected to take over the socket ‘sock’ and speak the non-HTTP protocol to which the connection was upgraded. MHD will no longer use the socket; this includes handling timeouts. The application must call ‘MHD_upgrade_action’ with an upgrade action of ‘MHD_UPGRADE_ACTION_CLOSE’ when it is done processing the connection to close the socket. The application must not call ‘MHD_stop_daemon’ on the respective daemon as long as it is still handling the connection. The arguments given to the ‘upgrade_handler’ have the following meaning: CLS matches the ‘upgrade_handler_cls’ that was given to ‘MHD_create_response_for_upgrade’ CONNECTION identifies the connection that is being upgraded; REQ_CLS last value left in '*req_cls' in the 'MHD_AccessHandlerCallback' EXTRA_IN buffer of bytes MHD read "by accident" from the socket already. This can happen if the client eagerly transmits more than just the HTTP request. The application should treat these as if it had read them from the socket. EXTRA_IN_SIZE number of bytes in ‘extra_in’ SOCK the socket which the application can now use directly for some bi-directional communication with the client. The application can henceforth use ‘recv()’ and ‘send()’ or ‘read()’ and ‘write()’ system calls on the socket. However, ‘ioctl()’ and ‘setsockopt()’ functions will not work as expected when using HTTPS. Such operations may be supported in the future via ‘MHD_upgrade_action’. Most importantly, the application must never call ‘close()’ on this socket. Closing the socket must be done using ‘MHD_upgrade_action’. However, while close is forbidden, the application may call ‘shutdown()’ on the socket. URH argument for calls to ‘MHD_upgrade_action’. Applications must eventually use this function to perform the ‘close()’ action on the socket. -- Function: enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...) Perform special operations related to upgraded connections. URH identifies the upgraded connection to perform an action on ACTION specifies the action to perform; further arguments to the function depend on the specifics of the action. -- Enumeration: MHD_UpgradeAction Set of actions to be performed on upgraded connections. Passed as an argument to ‘MHD_upgrade_action()’. ‘MHD_UPGRADE_ACTION_CLOSE’ Closes the connection. Must be called once the application is done with the client. Takes no additional arguments. ‘MHD_UPGRADE_ACTION_CORK_ON’ Enable corking on the underlying socket. ‘MHD_UPGRADE_ACTION_CORK_OFF’ Disable corking on the underlying socket.  File: libmicrohttpd.info, Node: microhttpd-flow, Next: microhttpd-dauth, Prev: microhttpd-responses, Up: Top 9 Flow control. *************** Sometimes it may be possible that clients upload data faster than an application can process it, or that an application needs an extended period of time to generate a response. If ‘MHD_USE_THREAD_PER_CONNECTION’ is used, applications can simply deal with this by performing their logic within the thread and thus effectively blocking connection processing by MHD. In all other modes, blocking logic must not be placed within the callbacks invoked by MHD as this would also block processing of other requests, as a single thread may be responsible for tens of thousands of connections. Instead, applications using thread modes other than ‘MHD_USE_THREAD_PER_CONNECTION’ should use the following functions to perform flow control. -- Function: enum MHD_Result MHD_suspend_connection (struct MHD_Connection *connection) Suspend handling of network data for a given connection. This can be used to dequeue a connection from MHD's event loop (external select, internal select or thread pool; not applicable to thread-per-connection!) for a while. If you use this API in conjunction with a internal select or a thread pool, you must set the option ‘MHD_ALLOW_SUSPEND_RESUME’ to ensure that a resumed connection is immediately processed by MHD. Suspended connections continue to count against the total number of connections allowed (per daemon, as well as per IP, if such limits are set). Suspended connections will NOT time out; timeouts will restart when the connection handling is resumed. While a connection is suspended, MHD will not detect disconnects by the client. The only safe time to suspend a connection is from the ‘MHD_AccessHandlerCallback’ or from the respective ‘MHD_ContentReaderCallback’ (but in this case the response object must not be shared among multiple connections). When suspending from the ‘MHD_AccessHandlerCallback’ you MUST afterwards return ‘MHD_YES’ from the access handler callback (as MHD_NO would imply to both close and suspend the connection, which is not allowed). Finally, it is an API violation to call ‘MHD_stop_daemon’ while having suspended connections (this will at least create memory and socket leaks or lead to undefined behavior). You must explicitly resume all connections before stopping the daemon. CONNECTION the connection to suspend -- Function: enum MHD_Result MHD_resume_connection (struct MHD_Connection *connection) Resume handling of network data for suspended connection. It is safe to resume a suspended connection at any time. Calling this function on a connection that was not previously suspended will result in undefined behavior. If you are using this function in "external" select mode, you must make sure to run ‘MHD_run’ afterwards (before again calling ‘MHD_get_fdset’), as otherwise the change may not be reflected in the set returned by ‘MHD_get_fdset’ and you may end up with a connection that is stuck until the next network activity. You can check whether a connection is currently suspended using ‘MHD_get_connection_info’ by querying for ‘MHD_CONNECTION_INFO_CONNECTION_SUSPENDED’. CONNECTION the connection to resume  File: libmicrohttpd.info, Node: microhttpd-dauth, Next: microhttpd-post, Prev: microhttpd-flow, Up: Top 10 Utilizing Authentication *************************** MHD support three types of client authentication. Basic authentication uses a simple authentication method based on BASE64 algorithm. Username and password are exchanged in clear between the client and the server, so this method must only be used for non-sensitive content or when the session is protected with https. When using basic authentication MHD will have access to the clear password, possibly allowing to create a chained authentication toward an external authentication server. Digest authentication uses a one-way authentication method based on MD5 hash algorithm. Only the hash will transit over the network, hence protecting the user password. The nonce will prevent replay attacks. This method is appropriate for general use, especially when https is not used to encrypt the session. Client certificate authentication uses a X.509 certificate from the client. This is the strongest authentication mechanism but it requires the use of HTTPS. Client certificate authentication can be used simultaneously with Basic or Digest Authentication in order to provide a two levels authentication (like for instance separate machine and user authentication). A code example for using client certificates is presented in the MHD tutorial. * Menu: * microhttpd-dauth basic:: Using Basic Authentication. * microhttpd-dauth digest:: Using Digest Authentication.  File: libmicrohttpd.info, Node: microhttpd-dauth basic, Next: microhttpd-dauth digest, Up: microhttpd-dauth 10.1 Using Basic Authentication =============================== -- Function: void MHD_free (void *ptr) Free the memory given at ‘ptr’. Used to free data structures allocated by MHD. Calls ‘free(ptr)’. -- Function: char * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection) Get the username and password from the basic authorization header sent by the client. Return ‘NULL’ if no Basic Authorization header set by the client or if Base64 encoding is invalid; a pointer to the structure with username and password if found values set by the client. If returned value is not ‘NULL’, the value must be ‘MHD_free()’'ed. -- Function: enum MHD_Result MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response) Queues a response to request basic authentication from the client. Return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. PREFER_UTF8 if set to ‘MHD_YES’ then parameter ‘charset’ with value ‘UTF-8’ will be added to the response authentication header which indicates that UTF-8 encoding is preferred for username and password. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status.  File: libmicrohttpd.info, Node: microhttpd-dauth digest, Prev: microhttpd-dauth basic, Up: microhttpd-dauth 10.2 Using Digest Authentication ================================ MHD supports MD5 (deprecated by IETF) and SHA-256 hash algorithms for digest authentication. The ‘MHD_DigestAuthAlgorithm’ enumeration is used to specify which algorithm should be used. -- Enumeration: MHD_DigestAuthAlgorithm Which digest algorithm should be used. Must be used consistently. ‘MHD_DIGEST_ALG_AUTO’ Have MHD pick an algorithm currently considered secure. For now defaults to SHA-256. ‘MHD_DIGEST_ALG_MD5’ Force use of (deprecated, ancient, insecure) MD5. ‘MHD_DIGEST_ALG_SHA256’ Force use of SHA-256. -- Enumeration: MHD_DigestAuthResult The result of digest authentication of the client. ‘MHD_DAUTH_OK’ Authentication OK. ‘MHD_DAUTH_ERROR’ General error, like "out of memory". ‘MHD_DAUTH_WRONG_HEADER’ No "Authorization" header or wrong format of the header. ‘MHD_DAUTH_WRONG_USERNAME’ Wrong "username". ‘MHD_DAUTH_WRONG_REALM’ Wrong "realm". ‘MHD_DAUTH_WRONG_URI’ Wrong "URI" (or URI parameters). ‘MHD_DAUTH_NONCE_STALE’ The "nonce" is too old. Suggest the client to retry with the same username and password to get the fresh "nonce". The validity of the "nonce" may not be checked. ‘MHD_DAUTH_NONCE_WRONG’ The "nonce" is wrong. May indicate an attack attempt. ‘MHD_DAUTH_RESPONSE_WRONG’ The "response" is wrong. May indicate an attack attempt. -- Function: char * MHD_digest_auth_get_username (struct MHD_Connection *connection) Find and return a pointer to the username value from the request header. Return ‘NULL’ if the value is not found or header does not exist. If returned value is not ‘NULL’, the value must be ‘MHD_free()’'ed. -- Function: enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC7616. If valid return ‘MHD_DAUTH_OK’, otherwise return the error code. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT the nonce validity duration in seconds. Most of the time it is sound to specify 300 seconds as its values. ALGO which digest algorithm should we use. -- Function: int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. ALGO which digest algorithm should we use. -- Function: int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. Deprecated, use ‘MHD_digest_auth_check2’ instead. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. -- Function: enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC7616. If valid return ‘MHD_DAUTH_OK’, otherwise return the error code. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST the pointer to the binary digest for the precalculated hash value "username:realm:password" with specified ALGO. DIGEST_SIZE the number of bytes in DIGEST (the size must match ALGO!) NONCE_TIMEOUT the nonce validity duration in seconds. Most of the time it is sound to specify 300 seconds as its values. ALGO digest authentication algorithm to use. -- Function: int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST pointer to the binary MD5 sum for the precalculated hash value "userame:realm:password". The size must match the selected ALGO! NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. ALGO digest authentication algorithm to use. -- Function: int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const unsigned char digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. Deprecated, use ‘MHD_digest_auth_check_digest2’ instead. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST pointer to the binary MD5 sum for the precalculated hash value "userame:realm:password" of ‘MHD_MD5_DIGEST_SIZE’ bytes. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. -- Function: enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo) Queues a response to request authentication from the client, return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. OPAQUE must reference to a zero-terminated string representing a value that gets passed to the client and expected to be passed again to the server as-is. This value can be a hexadecimal or base64 string. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status. SIGNAL_STALE a value that signals "stale=true" in the response header to indicate the invalidity of the nonce and no need to ask for authentication parameters and only a new nonce gets generated. ‘MHD_YES’ to generate a new nonce, ‘MHD_NO’ to ask for authentication parameters. ALGO which digest algorithm should we use. The same algorithm must then be selected when checking digests received from clients! -- Function: enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale) Queues a response to request authentication from the client, return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. OPAQUE must reference to a zero-terminated string representing a value that gets passed to the client and expected to be passed again to the server as-is. This value can be a hexadecimal or base64 string. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status. SIGNAL_STALE a value that signals "stale=true" in the response header to indicate the invalidity of the nonce and no need to ask for authentication parameters and only a new nonce gets generated. ‘MHD_YES’ to generate a new nonce, ‘MHD_NO’ to ask for authentication parameters. Example: handling digest authentication requests and responses. #define PAGE "libmicrohttpd demoAccess granted" #define DENIED "libmicrohttpd demoAccess denied" #define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" static int ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; int ret; static int already_called_marker; if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if (username == NULL) { response = MHD_create_response_from_buffer(strlen (DENIED), DENIED, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_auth_fail_response2 (connection, realm, OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response(response); return ret; } ret = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_SHA256); MHD_free(username); if ( (ret == MHD_INVALID_NONCE) || (ret == MHD_NO) ) { response = MHD_create_response_from_buffer(strlen (DENIED), DENIED, MHD_RESPMEM_PERSISTENT); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_fail_response2 (connection, realm, OPAQUE, response, (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response(response); return ret; } response = MHD_create_response_from_buffer (strlen(PAGE), PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret; }  File: libmicrohttpd.info, Node: microhttpd-post, Next: microhttpd-info, Prev: microhttpd-dauth, Up: Top 11 Adding a ‘POST’ processor **************************** * Menu: * microhttpd-post api:: Programming interface for the ‘POST’ processor. MHD provides the post processor API to make it easier for applications to parse the data of a client's ‘POST’ request: the ‘MHD_AccessHandlerCallback’ will be invoked multiple times to process data as it arrives; at each invocation a new chunk of data must be processed. The arguments UPLOAD_DATA and UPLOAD_DATA_SIZE are used to reference the chunk of data. When ‘MHD_AccessHandlerCallback’ is invoked for a new request: its ‘*REQ_CLS’ argument is set to ‘NULL’. When ‘POST’ data comes in the upload buffer it is *mandatory* to use the REQ_CLS to store a reference to per-request data. The fact that the pointer was initially ‘NULL’ can be used to detect that this is a new request. One method to detect that a new request was started is to set ‘*req_cls’ to an unused integer: int access_handler (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int old_connection_marker; int new_connection = (NULL == *req_cls); if (new_connection) { /* new connection with POST */ *req_cls = &old_connection_marker; } ... } In contrast to the previous example, for ‘POST’ requests in particular, it is more common to use the value of ‘*req_cls’ to keep track of actual state used during processing, such as the post processor (or a struct containing a post processor): int access_handler (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_PostProcessor * pp = *req_cls; if (pp == NULL) { pp = MHD_create_post_processor(connection, ...); *req_cls = pp; return MHD_YES; } if (*upload_data_size) { MHD_post_process(pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else { MHD_destroy_post_processor(pp); return MHD_queue_response(...); } } Note that the callback from ‘MHD_OPTION_NOTIFY_COMPLETED’ should be used to destroy the post processor. This cannot be done inside of the access handler since the connection may not always terminate normally.  File: libmicrohttpd.info, Node: microhttpd-post api, Up: microhttpd-post 11.1 Programming interface for the ‘POST’ processor =================================================== -- Function: struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iterator, void *iterator_cls) Create a PostProcessor. A PostProcessor can be used to (incrementally) parse the data portion of a ‘POST’ request. CONNECTION the connection on which the ‘POST’ is happening (used to determine the ‘POST’ format); BUFFER_SIZE maximum number of bytes to use for internal buffering (used only for the parsing, specifically the parsing of the keys). A tiny value (256-1024) should be sufficient; do *NOT* use a value smaller than 256; for good performance, use 32k or 64k (i.e. 65536). ITERATOR iterator to be called with the parsed data; must *NOT* be ‘NULL’; ITERATOR_CLS custom value to be used as first argument to ITERATOR. Return ‘NULL’ on error (out of memory, unsupported encoding), otherwise a PP handle. -- Function: enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) Parse and process ‘POST’ data. Call this function when ‘POST’ data is available (usually during an ‘MHD_AccessHandlerCallback’) with the UPLOAD_DATA and UPLOAD_DATA_SIZE. Whenever possible, this will then cause calls to the ‘MHD_IncrementalKeyValueIterator’. PP the post processor; POST_DATA POST_DATA_LEN bytes of ‘POST’ data; POST_DATA_LEN length of POST_DATA. Return ‘MHD_YES’ on success, ‘MHD_NO’ on error (out-of-memory, iterator aborted, parse error). -- Function: enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp) Release PostProcessor resources. After this function is being called, the PostProcessor is guaranteed to no longer call its iterator. There is no special call to the iterator to indicate the end of the post processing stream. After destroying the PostProcessor, the programmer should perform any necessary work to complete the processing of the iterator. Return ‘MHD_YES’ if processing completed nicely, ‘MHD_NO’ if there were spurious characters or formatting problems with the post request. It is common to ignore the return value of this function.  File: libmicrohttpd.info, Node: microhttpd-info, Next: microhttpd-util, Prev: microhttpd-post, Up: Top 12 Obtaining and modifying status information. ********************************************** * Menu: * microhttpd-info daemon:: State information about an MHD daemon * microhttpd-info conn:: State information about a connection * microhttpd-option conn:: Modify per-connection options  File: libmicrohttpd.info, Node: microhttpd-info daemon, Next: microhttpd-info conn, Up: microhttpd-info 12.1 Obtaining state information about an MHD daemon ==================================================== -- Function: const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType infoType, ...) Obtain information about the given daemon. This function is currently not fully implemented. DAEMON the daemon about which information is desired; INFOTYPE type of information that is desired ... additional arguments about the desired information (depending on infoType) Returns a union with the respective member (depending on infoType) set to the desired information), or ‘NULL’ in case the desired information is not available or applicable. -- Enumeration: MHD_DaemonInfoType Values of this enum are used to specify what information about a daemon is desired. ‘MHD_DAEMON_INFO_KEY_SIZE’ Request information about the key size for a particular cipher algorithm. The cipher algorithm should be passed as an extra argument (of type 'enum MHD_GNUTLS_CipherAlgorithm'). No longer supported, using this value will cause ‘MHD_get_daemon_info’ to return NULL. ‘MHD_DAEMON_INFO_MAC_KEY_SIZE’ Request information about the key size for a particular cipher algorithm. The cipher algorithm should be passed as an extra argument (of type 'enum MHD_GNUTLS_HashAlgorithm'). No longer supported, using this value will cause ‘MHD_get_daemon_info’ to return NULL. ‘MHD_DAEMON_INFO_LISTEN_FD’ Request the file-descriptor number that MHD is using to listen to the server socket. This can be useful if no port was specified and a client needs to learn what port is actually being used by MHD. No extra arguments should be passed. ‘MHD_DAEMON_INFO_EPOLL_FD’ Request the file-descriptor number that MHD is using for epoll. If the build is not supporting epoll, NULL is returned; if we are using a thread pool or this daemon was not started with ‘MHD_USE_EPOLL’, (a pointer to) -1 is returned. If we are using ‘MHD_USE_INTERNAL_POLLING_THREAD’ or are in 'external' select mode, the internal epoll FD is returned. This function must be used in external select mode with epoll to obtain the FD to call epoll on. No extra arguments should be passed. ‘MHD_DAEMON_INFO_CURRENT_CONNECTIONS’ Request the number of current connections handled by the daemon. No extra arguments should be passed and a pointer to a ‘union MHD_DaemonInfo’ value is returned, with the ‘num_connections’ member of type ‘unsigned int’ set to the number of active connections. Note that in multi-threaded or internal-select mode, the real number of current connections may already be different when ‘MHD_get_daemon_info’ returns. The number of current connections can be used (even in multi-threaded and internal-select mode) after ‘MHD_quiesce_daemon’ to detect whether all connections have been handled.  File: libmicrohttpd.info, Node: microhttpd-info conn, Next: microhttpd-option conn, Prev: microhttpd-info daemon, Up: microhttpd-info 12.2 Obtaining state information about a connection =================================================== -- Function: const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType infoType, ...) Obtain information about the given connection. CONNECTION the connection about which information is desired; INFOTYPE type of information that is desired ... additional arguments about the desired information (depending on infoType) Returns a union with the respective member (depending on infoType) set to the desired information), or ‘NULL’ in case the desired information is not available or applicable. -- Enumeration: MHD_ConnectionInfoType Values of this enum are used to specify what information about a connection is desired. ‘MHD_CONNECTION_INFO_CIPHER_ALGO’ What cipher algorithm is being used (HTTPS connections only). ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_PROTOCOL,’ Allows finding out the TLS/SSL protocol used (HTTPS connections only). ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CLIENT_ADDRESS’ Returns information about the address of the client. Returns essentially a ‘struct sockaddr **’ (since the API returns a ‘union MHD_ConnectionInfo *’ and that union contains a ‘struct sockaddr *’). Takes no extra arguments. ‘MHD_CONNECTION_INFO_GNUTLS_SESSION,’ Takes no extra arguments. Allows access to the underlying GNUtls session, including access to the underlying GNUtls client certificate (HTTPS connections only). Takes no extra arguments. ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT,’ Dysfunctional (never implemented, deprecated). Use MHD_CONNECTION_INFO_GNUTLS_SESSION to get the ‘gnutls_session_t’ and then call ‘gnutls_certificate_get_peers()’. ‘MHD_CONNECTION_INFO_DAEMON’ Returns information about ‘struct MHD_Daemon’ which manages this connection. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_FD’ Returns the file descriptor (usually a TCP socket) associated with this connection (in the "connect-fd" member of the returned struct). Note that manipulating the descriptor directly can have problematic consequences (as in, break HTTP). Applications might use this access to manipulate TCP options, for example to set the "TCP-NODELAY" option for COMET-like applications. Note that MHD will set TCP-CORK after sending the HTTP header and clear it after finishing the footers automatically (if the platform supports it). As the connection callbacks are invoked in between, those might be used to set different values for TCP-CORK and TCP-NODELAY in the meantime. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_SUSPENDED’ Returns pointer to an integer that is ‘MHD_YES’ if the connection is currently suspended (and thus can be safely resumed) and ‘MHD_NO’ otherwise. Takes no extra arguments. ‘MHD_CONNECTION_INFO_SOCKET_CONTEXT’ Returns the client-specific pointer to a ‘void *’ that was (possibly) set during a ‘MHD_NotifyConnectionCallback’ when the socket was first accepted. Note that this is NOT the same as the ‘req_cls’ argument of the ‘MHD_AccessHandlerCallback’. The ‘req_cls’ is fresh for each HTTP request, while the ‘socket_context’ is fresh for each socket. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_TIMEOUT’ Returns pointer to an ‘unsigned int’ that is the current timeout used for the connection (in seconds, 0 for no timeout). Note that while suspended connections will not timeout, the timeout value returned for suspended connections will be the timeout that the connection will use after it is resumed, and thus might not be zero. Takes no extra arguments. ‘MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE’ Returns pointer to an ‘size_t’ that represents the size of the HTTP header received from the client. Only valid after the first callback to the access handler. Takes no extra arguments. ‘MHD_CONNECTION_INFO_HTTP_STATUS’ Returns the HTTP status code of the response that was queued. Returns NULL if no response was queued yet. Takes no extra arguments.  File: libmicrohttpd.info, Node: microhttpd-option conn, Prev: microhttpd-info conn, Up: microhttpd-info 12.3 Setting custom options for an individual connection ======================================================== -- Function: int MHD_set_connection_option (struct MHD_Connection *daemon, enum MHD_CONNECTION_OPTION option, ...) Set a custom option for the given connection. CONNECTION the connection for which an option should be set or modified; OPTION option to set ... additional arguments for the option (depending on option) Returns ‘MHD_YES’ on success, ‘MHD_NO’ for errors (i.e. option argument invalid or option unknown). -- Enumeration: MHD_CONNECTION_OPTION Values of this enum are used to specify which option for a connection should be changed. ‘MHD_CONNECTION_OPTION_TIMEOUT’ Set a custom timeout for the given connection. Specified as the number of seconds, given as an ‘unsigned int’. Use zero for no timeout.  File: libmicrohttpd.info, Node: microhttpd-util, Next: microhttpd-websocket, Prev: microhttpd-info, Up: Top 13 Utility functions. ********************* * Menu: * microhttpd-util feature:: Test supported MHD features * microhttpd-util unescape:: Unescape strings  File: libmicrohttpd.info, Node: microhttpd-util feature, Next: microhttpd-util unescape, Up: microhttpd-util 13.1 Testing for supported MHD features ======================================= -- Enumeration: MHD_FEATURE Values of this enum are used to specify what information about a daemon is desired. ‘MHD_FEATURE_MESSAGES’ Get whether messages are supported. If supported then in debug mode messages can be printed to stderr or to external logger. ‘MHD_FEATURE_SSL’ Get whether HTTPS is supported. If supported then flag MHD_USE_SSL and options MHD_OPTION_HTTPS_MEM_KEY, MHD_OPTION_HTTPS_MEM_CERT, MHD_OPTION_HTTPS_MEM_TRUST, MHD_OPTION_HTTPS_MEM_DHPARAMS, MHD_OPTION_HTTPS_CRED_TYPE, MHD_OPTION_HTTPS_PRIORITIES can be used. ‘MHD_FEATURE_HTTPS_CERT_CALLBACK’ Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is supported. ‘MHD_FEATURE_IPv6’ Get whether IPv6 is supported. If supported then flag MHD_USE_IPv6 can be used. ‘MHD_FEATURE_IPv6_ONLY’ Get whether IPv6 without IPv4 is supported. If not supported then IPv4 is always enabled in IPv6 sockets and flag MHD_USE_DUAL_STACK if always used when MHD_USE_IPv6 is specified. ‘MHD_FEATURE_POLL’ Get whether ‘poll()’ is supported. If supported then flag MHD_USE_POLL can be used. ‘MHD_FEATURE_EPOLL’ Get whether ‘epoll()’ is supported. If supported then Flags MHD_USE_EPOLL and MHD_USE_EPOLL_INTERNAL_THREAD can be used. ‘MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET’ Get whether shutdown on listen socket to signal other threads is supported. If not supported flag MHD_USE_ITC is automatically forced. ‘MHD_FEATURE_SOCKETPAIR’ Get whether a ‘socketpair()’ is used internally instead of a ‘pipe()’ to signal other threads. ‘MHD_FEATURE_TCP_FASTOPEN’ Get whether TCP Fast Open is supported. If supported then flag MHD_USE_TCP_FASTOPEN and option MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. ‘MHD_FEATURE_BASIC_AUTH’ Get whether HTTP Basic authorization is supported. If supported then functions ‘MHD_basic_auth_get_username_password()’ and ‘MHD_queue_basic_auth_fail_response()’ can be used. ‘MHD_FEATURE_DIGEST_AUTH’ Get whether HTTP Digest authorization is supported. If supported then options MHD_OPTION_DIGEST_AUTH_RANDOM, MHD_OPTION_NONCE_NC_SIZE and functions ‘MHD_digest_auth_check()’, can be used. ‘MHD_FEATURE_POSTPROCESSOR’ Get whether postprocessor is supported. If supported then functions ‘MHD_create_post_processor()’, ‘MHD_post_process()’, ‘MHD_destroy_post_processor()’ can be used. ‘MHD_FEATURE_SENDFILE’ Get whether ‘sendfile()’ is supported. -- Function: int MHD_is_feature_supported (enum MHD_FEATURE feature) Get information about supported MHD features. Indicate that MHD was compiled with or without support for particular feature. Some features require additional support by the kernel. However, kernel support is not checked by this function. FEATURE type of requested information Returns ‘MHD_YES’ if the feature is supported, and ‘MHD_NO’ if not.  File: libmicrohttpd.info, Node: microhttpd-util unescape, Prev: microhttpd-util feature, Up: microhttpd-util 13.2 Unescape strings ===================== -- Function: size_t MHD_http_unescape (char *val) Process escape sequences ('%HH') Updates val in place; the result should be UTF-8 encoded and cannot be larger than the input. The result must also still be 0-terminated. VAL value to unescape (modified in the process), must be a 0-terminated UTF-8 string. Returns length of the resulting val (‘strlen(val)’ may be shorter afterwards due to elimination of escape sequences).  File: libmicrohttpd.info, Node: microhttpd-websocket, Next: GNU-LGPL, Prev: microhttpd-util, Up: Top 14 Websocket functions. *********************** Websocket functions provide what you need to use an upgraded connection as a websocket. These functions are only available if you include the header file ‘microhttpd_ws.h’ and compiled _libmicrohttpd_ with websockets. * Menu: * microhttpd-websocket handshake:: Websocket handshake functions * microhttpd-websocket stream:: Websocket stream functions * microhttpd-websocket decode:: Websocket decode functions * microhttpd-websocket encode:: Websocket encode functions * microhttpd-websocket memory:: Websocket memory functions  File: libmicrohttpd.info, Node: microhttpd-websocket handshake, Next: microhttpd-websocket stream, Up: microhttpd-websocket 14.1 Websocket handshake functions ================================== -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_check_http_version (const char* http_version) Checks the HTTP version of the incoming request. Websocket requests are only allowed for HTTP/1.1 or above. HTTP_VERSION The value of the ‘version’ parameter of your ‘access_handler’ callback. If you pass ‘NULL’ then this is handled like a not matching HTTP version. Returns 0 when the HTTP version is valid for a websocket request and a value less than zero when the HTTP version isn't valid for a websocket request. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_check_connection_header (const char* connection_header) Checks the value of the ‘Connection’ HTTP request header. Websocket requests require the token ‘Upgrade’ in the ‘Connection’ HTTP request header. CONNECTION_HEADER Value of the ‘Connection’ request header. You can get this request header value by passing ‘MHD_HTTP_HEADER_CONNECTION’ to ‘MHD_lookup_connection_value()’. If you pass ‘NULL’ then this is handled like a not matching ‘Connection’ header value. Returns 0 when the ‘Connection’ header is valid for a websocket request and a value less than zero when the ‘Connection’ header isn't valid for a websocket request. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_check_upgrade_header (const char* upgrade_header) Checks the value of the ‘Upgrade’ HTTP request header. Websocket requests require the value ‘websocket’ in the ‘Upgrade’ HTTP request header. UPGRADE_HEADER Value of the ‘Upgrade’ request header. You can get this request header value by passing ‘MHD_HTTP_HEADER_UPGRADE’ to ‘MHD_lookup_connection_value()’. If you pass ‘NULL’ then this is handled like a not matching ‘Upgrade’ header value. Returns 0 when the ‘Upgrade’ header is valid for a websocket request and a value less than zero when the ‘Upgrade’ header isn't valid for a websocket request. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_check_version_header (const char* version_header) Checks the value of the ‘Sec-WebSocket-Version’ HTTP request header. Websocket requests require the value ‘13’ in the ‘Sec-WebSocket-Version’ HTTP request header. VERSION_HEADER Value of the ‘Sec-WebSocket-Version’ request header. You can get this request header value by passing ‘MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION’ to ‘MHD_lookup_connection_value()’. If you pass ‘NULL’ then this is handled like a not matching ‘Sec-WebSocket-Version’ header value. Returns 0 when the ‘Sec-WebSocket-Version’ header is valid for a websocket request and a value less than zero when the ‘Sec-WebSocket-Version’ header isn't valid for a websocket request. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_create_accept_header (const char* sec_websocket_key, char* sec_websocket_accept) Checks the value of the ‘Sec-WebSocket-Key’ HTTP request header and generates the value for the ‘Sec-WebSocket-Accept’ HTTP response header. The generated value must be sent to the client. SEC_WEBSOCKET_KEY Value of the ‘Sec-WebSocket-Key’ request header. You can get this request header value by passing ‘MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY’ to ‘MHD_lookup_connection_value()’. If you pass ‘NULL’ then this is handled like a not matching ‘Sec-WebSocket-Key’ header value. SEC_WEBSOCKET_ACCEPT Response buffer, which will receive the generated value for the ‘Sec-WebSocket-Accept’ HTTP response header. This buffer must be at least 29 bytes long and will contain the response value plus a terminating ‘NUL’ character on success. Must not be ‘NULL’. You can add this HTTP header to your response by passing ‘MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT’ to ‘MHD_add_response_header()’. Returns 0 when the ‘Sec-WebSocket-Key’ header was not empty and a result value for the ‘Sec-WebSocket-Accept’ was calculated. A value less than zero is returned when the ‘Sec-WebSocket-Key’ header isn't valid for a websocket request or when any error occurred. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’.  File: libmicrohttpd.info, Node: microhttpd-websocket stream, Next: microhttpd-websocket decode, Prev: microhttpd-websocket handshake, Up: microhttpd-websocket 14.2 Websocket stream functions =============================== -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size) Creates a new websocket stream, used for decoding/encoding. WS pointer a variable to fill with the newly created ‘struct MHD_WebSocketStream’, receives ‘NULL’ on error. May not be ‘NULL’. If not required anymore, free the created websocket stream with ‘MHD_websocket_stream_free()’. FLAGS combination of ‘enum MHD_WEBSOCKET_FLAG’ values to modify the behavior of the websocket stream. MAX_PAYLOAD_SIZE maximum size for incoming payload data in bytes. Use 0 to allow each size. Returns 0 on success, negative values on error. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size, MHD_WebSocketMallocCallback callback_malloc, MHD_WebSocketReallocCallback callback_realloc, MHD_WebSocketFreeCallback callback_free, void* cls_rng, MHD_WebSocketRandomNumberGenerator callback_rng) Creates a new websocket stream, used for decoding/encoding, but with custom memory functions for malloc, realloc and free. Also a random number generator can be specified for client mode. WS pointer a variable to fill with the newly created ‘struct MHD_WebSocketStream’, receives ‘NULL’ on error. Must not be ‘NULL’. If not required anymore, free the created websocket stream with ‘MHD_websocket_stream_free’. FLAGS combination of ‘enum MHD_WEBSOCKET_FLAG’ values to modify the behavior of the websocket stream. MAX_PAYLOAD_SIZE maximum size for incoming payload data in bytes. Use 0 to allow each size. CALLBACK_MALLOC callback function for allocating memory. Must not be ‘NULL’. The shorter ‘MHD_websocket_stream_init()’ passes a reference to ‘malloc’ here. CALLBACK_REALLOC callback function for reallocating memory. Must not be ‘NULL’. The shorter ‘MHD_websocket_stream_init()’ passes a reference to ‘realloc’ here. CALLBACK_FREE callback function for freeing memory. Must not be ‘NULL’. The shorter ‘MHD_websocket_stream_init()’ passes a reference to ‘free’ here. CLS_RNG closure for the random number generator. This is only required when ‘MHD_WEBSOCKET_FLAG_CLIENT’ is passed in ‘flags’. The given value is passed to the random number generator callback. May be ‘NULL’ if not needed. Should be ‘NULL’ when you are not using ‘MHD_WEBSOCKET_FLAG_CLIENT’. The shorter ‘MHD_websocket_stream_init’ passes ‘NULL’ here. CALLBACK_RNG callback function for a secure random number generator. This is only required when ‘MHD_WEBSOCKET_FLAG_CLIENT’ is passed in ‘flags’ and must not be ‘NULL’ then. Should be ‘NULL’ otherwise. The shorter ‘MHD_websocket_stream_init()’ passes ‘NULL’ here. Returns 0 on success, negative values on error. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_free (struct MHD_WebSocketStream *ws) Frees a previously allocated websocket stream WS websocket stream to free, this value may be ‘NULL’. Returns 0 on success, negative values on error. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws) Invalidates a websocket stream. After invalidation a websocket stream cannot be used for decoding anymore. Encoding is still possible. WS websocket stream to invalidate. Returns 0 on success, negative values on error. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_VALIDITY MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws) Queries whether a websocket stream is valid. Invalidated websocket streams cannot be used for decoding anymore. Encoding is still possible. WS websocket stream to invalidate. Returns 0 if invalid, 1 if valid for all types or 2 if valid only for control frames. Can be compared with ‘enum MHD_WEBSOCKET_VALIDITY’.  File: libmicrohttpd.info, Node: microhttpd-websocket decode, Next: microhttpd-websocket encode, Prev: microhttpd-websocket stream, Up: microhttpd-websocket 14.3 Websocket decode functions =============================== -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_decode (struct MHD_WebSocketStream* ws, const char* streambuf, size_t streambuf_len, size_t* streambuf_read_len, char** payload, size_t* payload_len) Decodes a byte sequence for a websocket stream. Decoding is done until either a frame is complete or the end of the byte sequence is reached. WS websocket stream for decoding. STREAMBUF byte sequence for decoding. This is what you typically received via ‘recv()’. STREAMBUF_LEN length of the byte sequence in parameter ‘streambuf’. STREAMBUF_READ_LEN pointer to a variable, which receives the number of bytes, that has been processed by this call. This value may be less than the value of ‘streambuf_len’ when a frame is decoded before the end of the buffer is reached. The remaining bytes of ‘buf’ must be passed to the next call of this function. PAYLOAD pointer to a variable, which receives the allocated buffer with the payload data of the decoded frame. Must not be ‘NULL’. If no decoded data is available or an error occurred ‘NULL’ is returned. When the returned value is not ‘NULL’ then the buffer contains always ‘payload_len’ bytes plus one terminating ‘NUL’ character (regardless of the frame type). The caller must free this buffer using ‘MHD_websocket_free()’. If you passed the flag ‘MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR’ upon creation of the websocket stream and a decoding error occurred (function return value less than 0), then this buffer contains a generated close frame, which must be sent via the socket to the recipient. If you passed the flag ‘MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS’ upon creation of the websocket stream then this payload may only be a part of the complete message. Only complete UTF-8 sequences are returned for fragmented text frames. If necessary the UTF-8 sequence will be completed with the next text fragment. PAYLOAD_LEN pointer to a variable, which receives length of the result ‘payload’ buffer in bytes. Must not be ‘NULL’. This receives 0 when no data is available, when the decoded payload has a length of zero or when an error occurred. Returns a value greater than zero when a frame is complete. Compare with ‘enum MHD_WEBSOCKET_STATUS’ to distinguish the frame type. Returns 0 when the call succeeded, but no frame is available. Returns a value less than zero on errors. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_split_close_reason (const char* payload, size_t payload_len, unsigned short* reason_code, const char** reason_utf8, size_t* reason_utf8_len) Splits the payload of a decoded close frame. PAYLOAD payload of the close frame. This parameter may only be ‘NULL’ if ‘payload_len’ is 0. PAYLOAD_LEN length of ‘payload’. REASON_CODE pointer to a variable, which receives the numeric close reason. If there was no close reason, this is 0. This value can be compared with ‘enum MHD_WEBSOCKET_CLOSEREASON’. May be ‘NULL’. REASON_UTF8 pointer to a variable, which receives the literal close reason. If there was no literal close reason, this will be ‘NULL’. May be ‘NULL’. Please note that no memory is allocated in this function. If not ‘NULL’ the returned value of this parameter points to a position in the specified ‘payload’. REASON_UTF8_LEN pointer to a variable, which receives the length of the literal close reason. If there was no literal close reason, this is 0. May be ‘NULL’. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’.  File: libmicrohttpd.info, Node: microhttpd-websocket encode, Next: microhttpd-websocket memory, Prev: microhttpd-websocket decode, Up: microhttpd-websocket 14.4 Websocket encode functions =============================== -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_text (struct MHD_WebSocketStream* ws, const char* payload_utf8, size_t payload_utf8_len, int fragmentation, char** frame, size_t* frame_len, int* utf8_step) Encodes an UTF-8 encoded text into websocket text frame WS websocket stream; PAYLOAD_UTF8 text to send. This must be UTF-8 encoded. If you don't want UTF-8 then send a binary frame with ‘MHD_websocket_encode_binary()’ instead. May be be ‘NULL’ if ‘payload_utf8_len’ is 0, must not be ‘NULL’ otherwise. PAYLOAD_UTF8_LEN length of ‘payload_utf8’ in bytes. FRAGMENTATION A value of ‘enum MHD_WEBSOCKET_FRAGMENTATION’ to specify the fragmentation behavior. Specify ‘MHD_WEBSOCKET_FRAGMENTATION_NONE’ or just 0 if you don't want to use fragmentation (default). FRAME pointer to a variable, which receives a buffer with the encoded text frame. Must not be ‘NULL’. The buffer contains what you typically send via ‘send()’ to the recipient. If no encoded data is available the variable receives ‘NULL’. If the variable is not ‘NULL’ then the buffer contains always ‘frame_len’ bytes plus one terminating ‘NUL’ character. The caller must free this buffer using ‘MHD_websocket_free()’. FRAME_LEN pointer to a variable, which receives the length of the encoded frame in bytes. Must not be ‘NULL’. UTF8_STEP If fragmentation is used (the parameter ‘fragmentation’ is not 0) then is parameter is required and must not be ‘NULL’. If no fragmentation is used, this parameter is optional and should be ‘NULL’. This parameter is a pointer to a variable which contains the last check status of the UTF-8 sequence. It is required to continue a previous UTF-8 sequence check when fragmentation is used, because a UTF-8 sequence could be split upon fragments. ‘enum MHD_WEBSOCKET_UTF8STEP’ is used for this value. If you start a new fragment using ‘MHD_WEBSOCKET_FRAGMENTATION_NONE’ or ‘MHD_WEBSOCKET_FRAGMENTATION_FIRST’ the old value of this variable will be discarded and the value of this variable will be initialized to ‘MHD_WEBSOCKET_UTF8STEP_NORMAL’. On all other fragmentation modes the previous value of the pointed variable will be used to continue the UTF-8 sequence check. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_binary (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, int fragmentation, char** frame, size_t* frame_len) Encodes binary data into websocket binary frame WS websocket stream; PAYLOAD binary data to send. May be be ‘NULL’ if ‘payload_len’ is 0, must not be ‘NULL’ otherwise. PAYLOAD_LEN length of ‘payload’ in bytes. FRAGMENTATION A value of ‘enum MHD_WEBSOCKET_FRAGMENTATION’ to specify the fragmentation behavior. Specify ‘MHD_WEBSOCKET_FRAGMENTATION_NONE’ or just 0 if you don't want to use fragmentation (default). FRAME pointer to a variable, which receives a buffer with the encoded binary frame. Must not be ‘NULL’. The buffer contains what you typically send via ‘send()’ to the recipient. If no encoded data is available the variable receives ‘NULL’. If the variable is not ‘NULL’ then the buffer contains always ‘frame_len’ bytes plus one terminating ‘NUL’ character. The caller must free this buffer using ‘MHD_websocket_free()’. FRAME_LEN pointer to a variable, which receives the length of the encoded frame in bytes. Must not be ‘NULL’. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_ping (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, char** frame, size_t* frame_len) Encodes a websocket ping frame. Ping frames are used to check whether a recipient is still available and what latency the websocket connection has. WS websocket stream; PAYLOAD binary ping data to send. May be ‘NULL’ if ‘payload_len’ is 0. PAYLOAD_LEN length of ‘payload’ in bytes. This may not exceed 125 bytes. FRAME pointer to a variable, which receives a buffer with the encoded ping frame. Must not be ‘NULL’. The buffer contains what you typically send via ‘send()’ to the recipient. If no encoded data is available the variable receives ‘NULL’. If the variable is not ‘NULL’ then the buffer contains always ‘frame_len’ bytes plus one terminating ‘NUL’ character. The caller must free this buffer using ‘MHD_websocket_free()’. FRAME_LEN pointer to a variable, which receives the length of the encoded frame in bytes. Must not be ‘NULL’. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_pong (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, char** frame, size_t* frame_len) Encodes a websocket pong frame. Pong frames are used to answer a previously received websocket ping frame. WS websocket stream; PAYLOAD binary pong data to send, which should be the decoded payload from the received ping frame. May be ‘NULL’ if ‘payload_len’ is 0. PAYLOAD_LEN length of ‘payload’ in bytes. This may not exceed 125 bytes. FRAME pointer to a variable, which receives a buffer with the encoded pong frame. Must not be ‘NULL’. The buffer contains what you typically send via ‘send()’ to the recipient. If no encoded data is available the variable receives ‘NULL’. If the variable is not ‘NULL’ then the buffer contains always ‘frame_len’ bytes plus one terminating ‘NUL’ character. The caller must free this buffer using ‘MHD_websocket_free()’. FRAME_LEN pointer to a variable, which receives the length of the encoded frame in bytes. Must not be ‘NULL’. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’. -- Function: enum MHD_WEBSOCKET_STATUS MHD_websocket_encode_close (struct MHD_WebSocketStream* ws, unsigned short reason_code, const char* reason_utf8, size_t reason_utf8_len, char** frame, size_t* frame_len) Encodes a websocket close frame. Close frames are used to close a websocket connection in a formal way. WS websocket stream; REASON_CODE reason for close. You can use ‘enum MHD_WEBSOCKET_CLOSEREASON’ for typical reasons, but you are not limited to these values. The allowed values are specified in RFC 6455 7.4. If you don't want to enter a reason, you can specify ‘MHD_WEBSOCKET_CLOSEREASON_NO_REASON’ (or just 0) then no reason is encoded. REASON_UTF8 An UTF-8 encoded text reason why the connection is closed. This may be ‘NULL’ if ‘reason_utf8_len’ is 0. This must be ‘NULL’ if ‘reason_code’ equals to zero (‘MHD_WEBSOCKET_CLOSEREASON_NO_REASON’). REASON_UTF8_LEN length of the UTF-8 encoded text reason in bytes. This may not exceed 123 bytes. FRAME pointer to a variable, which receives a buffer with the encoded close frame. Must not be ‘NULL’. The buffer contains what you typically send via ‘send()’ to the recipient. If no encoded data is available the variable receives ‘NULL’. If the variable is not ‘NULL’ then the buffer contains always ‘frame_len’ bytes plus one terminating ‘NUL’ character. The caller must free this buffer using ‘MHD_websocket_free()’. FRAME_LEN pointer to a variable, which receives the length of the encoded frame in bytes. Must not be ‘NULL’. Returns 0 on success or a value less than zero on errors. Can be compared with ‘enum MHD_WEBSOCKET_STATUS’.  File: libmicrohttpd.info, Node: microhttpd-websocket memory, Prev: microhttpd-websocket encode, Up: microhttpd-websocket 14.5 Websocket memory functions =============================== -- Function: void* MHD_websocket_malloc (struct MHD_WebSocketStream* ws, size_t buf_len) Allocates memory with the associated ‘malloc()’ function of the websocket stream. The memory allocation function could be different for a websocket stream if ‘MHD_websocket_stream_init2()’ has been used for initialization. WS websocket stream; BUF_LEN size of the buffer to allocate in bytes. Returns the pointer of the allocated buffer or ‘NULL’ on failure. -- Function: void* MHD_websocket_realloc (struct MHD_WebSocketStream* ws, void* buf, size_t new_buf_len) Reallocates memory with the associated ‘realloc()’ function of the websocket stream. The memory reallocation function could be different for a websocket stream if ‘MHD_websocket_stream_init2()’ has been used for initialization. WS websocket stream; BUF current buffer, may be ‘NULL’; NEW_BUF_LEN new size of the buffer in bytes. Return the pointer of the reallocated buffer or ‘NULL’ on failure. On failure the old pointer remains valid. -- Function: void MHD_websocket_free (struct MHD_WebSocketStream* ws, void* buf) Frees memory with the associated ‘free()’ function of the websocket stream. The memory free function could be different for a websocket stream if ‘MHD_websocket_stream_init2()’ has been used for initialization. WS websocket stream; BUF buffer to free, this may be ‘NULL’ then nothing happens.  File: libmicrohttpd.info, Node: GNU-LGPL, Next: eCos License, Prev: microhttpd-websocket, Up: Top GNU-LGPL ******** Version 2.1, February 1999 Copyright © 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble -------- The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the “Lesser†General Public License because it does _Less_ to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION --------------------------------------------------------------- 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a. The modified work must itself be a software library. b. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b. Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e. Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS --------------------------- How to Apply These Terms to Your New Libraries ---------------------------------------------- If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. ONE LINE TO GIVE THE LIBRARY'S NAME AND AN IDEA OF WHAT IT DOES. Copyright (C) YEAR NAME OF AUTHOR This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. SIGNATURE OF TY COON, 1 April 1990 Ty Coon, President of Vice That's all there is to it!  File: libmicrohttpd.info, Node: eCos License, Next: GNU-GPL, Prev: GNU-LGPL, Up: Top eCos License ************ GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU libmicrohttpd; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License v2. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License.  File: libmicrohttpd.info, Node: GNU-GPL, Next: GNU-FDL, Prev: eCos License, Up: Top GNU General Public License ************************** Version 2, June 1991 Copyright © 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble ======== The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION =============================================================== 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a. You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b. Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c. Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs ======================================================= If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES. Copyright (C) YYYY NAME OF AUTHOR This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) YEAR NAME OF AUTHOR Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands ‘show w’ and ‘show c’ should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than ‘show w’ and ‘show c’; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. SIGNATURE OF TY COON, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.  File: libmicrohttpd.info, Node: GNU-FDL, Next: Concept Index, Prev: GNU-GPL, Up: Top GNU-FDL ******* Version 1.3, 3 November 2008 Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document “free†in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements." 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See . Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents ==================================================== To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.  File: libmicrohttpd.info, Node: Concept Index, Next: Function and Data Index, Prev: GNU-FDL, Up: Top Concept Index ************* [index] * Menu: * ARM: microhttpd-intro. (line 285) * bind, restricting bind: microhttpd-const. (line 330) * bind, restricting bind <1>: microhttpd-const. (line 565) * cipher: microhttpd-const. (line 403) * clock: microhttpd-const. (line 105) * compilation: microhttpd-intro. (line 123) * connection, limiting number of connections: microhttpd-const. (line 209) * connection, limiting number of connections <1>: microhttpd-info daemon. (line 60) * cookie: microhttpd-const. (line 597) * cortex m3: microhttpd-intro. (line 285) * date: microhttpd-const. (line 105) * debugging: microhttpd-const. (line 31) * debugging <1>: microhttpd-const. (line 341) * deprecated: microhttpd-const. (line 61) * DH: microhttpd-const. (line 557) * digest auth: microhttpd-const. (line 442) * digest auth <1>: microhttpd-const. (line 453) * eCos, GNU General Public License with eCos Extension: eCos License. (line 6) * embedded systems: microhttpd-intro. (line 123) * embedded systems <1>: microhttpd-intro. (line 285) * embedded systems <2>: microhttpd-const. (line 105) * embedded systems <3>: microhttpd-const. (line 112) * embedded systems <4>: microhttpd-const. (line 541) * epoll: microhttpd-intro. (line 67) * epoll <1>: microhttpd-const. (line 77) * epoll <2>: microhttpd-info daemon. (line 49) * escaping: microhttpd-const. (line 524) * FD_SETSIZE: microhttpd-const. (line 70) * FD_SETSIZE <1>: microhttpd-const. (line 77) * foreign-function interface: microhttpd-const. (line 502) * HTTP2: microhttpd-response upgrade. (line 6) * IAR: microhttpd-intro. (line 285) * internationalization: microhttpd-const. (line 524) * IPv6: microhttpd-const. (line 45) * IPv6 <1>: microhttpd-const. (line 55) * license: GNU-LGPL. (line 6) * license <1>: eCos License. (line 6) * license <2>: GNU-GPL. (line 6) * license <3>: GNU-FDL. (line 6) * listen: microhttpd-const. (line 112) * listen <1>: microhttpd-const. (line 143) * listen <2>: microhttpd-const. (line 547) * listen <3>: microhttpd-info daemon. (line 43) * logging: microhttpd-const. (line 341) * logging <1>: microhttpd-const. (line 483) * long long: microhttpd-intro. (line 285) * memory: microhttpd-const. (line 201) * memory, limiting memory utilization: microhttpd-const. (line 193) * MHD_LONG_LONG: microhttpd-intro. (line 285) * microhttpd.h: microhttpd-intro. (line 224) * OCSP: microhttpd-const. (line 426) * options: microhttpd-const. (line 502) * performance: microhttpd-intro. (line 91) * performance <1>: microhttpd-const. (line 90) * performance <2>: microhttpd-const. (line 494) * performance <3>: microhttpd-info conn. (line 114) * poll: microhttpd-intro. (line 67) * poll <1>: microhttpd-const. (line 70) * poll <2>: microhttpd-init. (line 74) * portability: microhttpd-intro. (line 123) * portability <1>: microhttpd-intro. (line 224) * POST method: microhttpd-const. (line 601) * POST method <1>: microhttpd-struct. (line 22) * POST method <2>: microhttpd-cb. (line 48) * POST method <3>: microhttpd-post. (line 6) * POST method <4>: microhttpd-post api. (line 6) * proxy: microhttpd-const. (line 112) * PSK: microhttpd-const. (line 436) * pthread: microhttpd-const. (line 541) * PUT method: microhttpd-cb. (line 48) * query string: microhttpd-const. (line 341) * quiesce: microhttpd-const. (line 119) * quiesce <1>: microhttpd-init. (line 51) * random: microhttpd-const. (line 442) * replay attack: microhttpd-const. (line 453) * reusing listening address: microhttpd-const. (line 565) * RFC2817: microhttpd-response upgrade. (line 6) * select: microhttpd-intro. (line 67) * select <1>: microhttpd-const. (line 70) * select <2>: microhttpd-const. (line 77) * select <3>: microhttpd-init. (line 74) * select <4>: microhttpd-init. (line 89) * signals: microhttpd-intro. (line 246) * SNI: microhttpd-const. (line 411) * SNI <1>: microhttpd-const. (line 426) * SSL: microhttpd-const. (line 34) * SSL <1>: microhttpd-const. (line 364) * SSL <2>: microhttpd-const. (line 370) * SSL <3>: microhttpd-const. (line 380) * SSL <4>: microhttpd-const. (line 386) * SSL <5>: microhttpd-const. (line 398) * SSL <6>: microhttpd-const. (line 403) * SSL <7>: microhttpd-const. (line 411) * SSL <8>: microhttpd-const. (line 426) * SSL <9>: microhttpd-const. (line 436) * SSL <10>: microhttpd-const. (line 557) * stack: microhttpd-const. (line 541) * systemd: microhttpd-const. (line 476) * testing: microhttpd-const. (line 319) * thread: microhttpd-const. (line 541) * timeout: microhttpd-const. (line 247) * timeout <1>: microhttpd-inspect. (line 39) * timeout <2>: microhttpd-option conn. (line 6) * TLS: microhttpd-const. (line 34) * TLS <1>: microhttpd-const. (line 364) * TLS <2>: microhttpd-const. (line 370) * TLS <3>: microhttpd-const. (line 380) * TLS <4>: microhttpd-const. (line 386) * TLS <5>: microhttpd-const. (line 398) * TLS <6>: microhttpd-const. (line 403) * TLS <7>: microhttpd-const. (line 411) * TLS <8>: microhttpd-const. (line 426) * TLS <9>: microhttpd-const. (line 436) * TLS <10>: microhttpd-const. (line 557) * upgrade: microhttpd-const. (line 148) * Upgrade: microhttpd-response upgrade. (line 6) * websocket: microhttpd-const. (line 708) * websocket <1>: microhttpd-const. (line 773) * websocket <2>: microhttpd-const. (line 805) * websocket <3>: microhttpd-const. (line 999) * websocket <4>: microhttpd-const. (line 1064) * websocket <5>: microhttpd-const. (line 1122) * websocket <6>: microhttpd-struct. (line 31) * websocket <7>: microhttpd-cb. (line 243) * websocket <8>: microhttpd-cb. (line 259) * websocket <9>: microhttpd-cb. (line 278) * websocket <10>: microhttpd-cb. (line 292) * websocket <11>: microhttpd-websocket handshake. (line 8) * websocket <12>: microhttpd-websocket handshake. (line 24) * websocket <13>: microhttpd-websocket handshake. (line 42) * websocket <14>: microhttpd-websocket handshake. (line 60) * websocket <15>: microhttpd-websocket handshake. (line 80) * websocket <16>: microhttpd-websocket stream. (line 9) * websocket <17>: microhttpd-websocket stream. (line 36) * websocket <18>: microhttpd-websocket stream. (line 91) * websocket <19>: microhttpd-websocket stream. (line 101) * websocket <20>: microhttpd-websocket stream. (line 113) * websocket <21>: microhttpd-websocket decode. (line 10) * websocket <22>: microhttpd-websocket decode. (line 70) * websocket <23>: microhttpd-websocket encode. (line 10) * websocket <24>: microhttpd-websocket encode. (line 70) * websocket <25>: microhttpd-websocket encode. (line 109) * websocket <26>: microhttpd-websocket encode. (line 143) * websocket <27>: microhttpd-websocket encode. (line 178) * websocket <28>: microhttpd-websocket memory. (line 8) * websocket <29>: microhttpd-websocket memory. (line 23) * websocket <30>: microhttpd-websocket memory. (line 42) * WebSockets: microhttpd-response upgrade. (line 6)  File: libmicrohttpd.info, Node: Function and Data Index, Next: Type Index, Prev: Concept Index, Up: Top Function and Data Index *********************** [index] * Menu: * *MHD_ContentReaderCallback: microhttpd-cb. (line 150) * *MHD_ContentReaderFreeCallback: microhttpd-cb. (line 197) * *MHD_RequestCompletedCallback: microhttpd-cb. (line 96) * *MHD_UpgradeHandler: microhttpd-response upgrade. (line 37) * *MHD_WebSocketFreeCallback: microhttpd-cb. (line 277) * *MHD_WebSocketMallocCallback: microhttpd-cb. (line 241) * *MHD_WebSocketRandomNumberGenerator: microhttpd-cb. (line 290) * *MHD_WebSocketReallocCallback: microhttpd-cb. (line 257) * MHD_add_connection: microhttpd-init. (line 115) * MHD_basic_auth_get_username_password3: microhttpd-dauth basic. (line 10) * MHD_create_post_processor: microhttpd-post api. (line 6) * MHD_create_response_from_buffer: microhttpd-response create. (line 104) * MHD_create_response_from_buffer_with_free_callback: microhttpd-response create. (line 125) * MHD_create_response_from_callback: microhttpd-response create. (line 6) * MHD_create_response_from_data: microhttpd-response create. (line 143) * MHD_create_response_from_fd: microhttpd-response create. (line 32) * MHD_create_response_from_fd_at_offset: microhttpd-response create. (line 62) * MHD_create_response_from_iovec: microhttpd-response create. (line 179) * MHD_create_response_from_pipe: microhttpd-response create. (line 50) * MHD_destroy_response: microhttpd-response enqueue. (line 29) * MHD_digest_auth_check: microhttpd-dauth digest. (line 111) * MHD_digest_auth_check_digest: microhttpd-dauth digest. (line 185) * MHD_digest_auth_check_digest2: microhttpd-dauth digest. (line 160) * MHD_digest_auth_check2: microhttpd-dauth digest. (line 86) * MHD_digest_auth_get_username: microhttpd-dauth digest. (line 55) * MHD_DigestAuthResult: microhttpd-dauth digest. (line 62) * MHD_DigestAuthResult <1>: microhttpd-dauth digest. (line 134) * MHD_free: microhttpd-dauth basic. (line 6) * MHD_get_connection_info: microhttpd-info conn. (line 6) * MHD_get_connection_values: microhttpd-requests. (line 6) * MHD_get_daemon_info: microhttpd-info daemon. (line 6) * MHD_get_response_header: microhttpd-response inspect. (line 18) * MHD_get_response_headers: microhttpd-response inspect. (line 6) * MHD_http_unescape: microhttpd-util unescape. (line 6) * MHD_is_feature_supported: microhttpd-util feature. (line 77) * MHD_lookup_connection_value: microhttpd-requests. (line 58) * MHD_lookup_connection_value_n: microhttpd-requests. (line 67) * MHD_queue_basic_auth_fail_response3: microhttpd-dauth basic. (line 19) * MHD_quiesce_daemon: microhttpd-init. (line 50) * MHD_Result: microhttpd-cb. (line 6) * MHD_Result <1>: microhttpd-cb. (line 19) * MHD_Result <2>: microhttpd-cb. (line 116) * MHD_Result <3>: microhttpd-cb. (line 202) * MHD_Result <4>: microhttpd-init. (line 70) * MHD_Result <5>: microhttpd-init. (line 86) * MHD_Result <6>: microhttpd-inspect. (line 6) * MHD_Result <7>: microhttpd-inspect. (line 31) * MHD_Result <8>: microhttpd-inspect. (line 37) * MHD_Result <9>: microhttpd-requests. (line 35) * MHD_Result <10>: microhttpd-response enqueue. (line 6) * MHD_Result <11>: microhttpd-response headers. (line 6) * MHD_Result <12>: microhttpd-response headers. (line 30) * MHD_Result <13>: microhttpd-response headers. (line 47) * MHD_Result <14>: microhttpd-response options. (line 6) * MHD_Result <15>: microhttpd-response upgrade. (line 23) * MHD_Result <16>: microhttpd-response upgrade. (line 91) * MHD_Result <17>: microhttpd-flow. (line 20) * MHD_Result <18>: microhttpd-flow. (line 56) * MHD_Result <19>: microhttpd-dauth digest. (line 208) * MHD_Result <20>: microhttpd-dauth digest. (line 235) * MHD_Result <21>: microhttpd-post api. (line 33) * MHD_Result <22>: microhttpd-post api. (line 52) * MHD_set_connection_option: microhttpd-option conn. (line 6) * MHD_set_panic_func: microhttpd-init. (line 6) * MHD_start_daemon: microhttpd-init. (line 18) * MHD_stop_daemon: microhttpd-init. (line 67) * MHD_websocket_check_connection_header: microhttpd-websocket handshake. (line 21) * MHD_websocket_check_http_version: microhttpd-websocket handshake. (line 6) * MHD_websocket_check_upgrade_header: microhttpd-websocket handshake. (line 39) * MHD_websocket_check_version_header: microhttpd-websocket handshake. (line 57) * MHD_websocket_create_accept_header: microhttpd-websocket handshake. (line 77) * MHD_websocket_decode: microhttpd-websocket decode. (line 6) * MHD_websocket_encode_binary: microhttpd-websocket encode. (line 66) * MHD_websocket_encode_close: microhttpd-websocket encode. (line 174) * MHD_websocket_encode_ping: microhttpd-websocket encode. (line 106) * MHD_websocket_encode_pong: microhttpd-websocket encode. (line 140) * MHD_websocket_encode_text: microhttpd-websocket encode. (line 6) * MHD_websocket_free: microhttpd-websocket memory. (line 40) * MHD_websocket_malloc: microhttpd-websocket memory. (line 6) * MHD_websocket_realloc: microhttpd-websocket memory. (line 21) * MHD_websocket_split_close_reason: microhttpd-websocket decode. (line 66) * MHD_websocket_stream_free: microhttpd-websocket stream. (line 89) * MHD_websocket_stream_init: microhttpd-websocket stream. (line 6) * MHD_websocket_stream_init2: microhttpd-websocket stream. (line 30) * MHD_websocket_stream_invalidate: microhttpd-websocket stream. (line 99) * MHD_websocket_stream_is_valid: microhttpd-websocket stream. (line 111)  File: libmicrohttpd.info, Node: Type Index, Prev: Function and Data Index, Up: Top Type Index ********** [index] * Menu: * MHD_Connection: microhttpd-struct. (line 9) * MHD_CONNECTION_OPTION: microhttpd-option conn. (line 22) * MHD_ConnectionInfo: microhttpd-struct. (line 24) * MHD_ConnectionInfoType: microhttpd-info conn. (line 25) * MHD_Daemon: microhttpd-struct. (line 6) * MHD_DaemonInfo: microhttpd-struct. (line 27) * MHD_DaemonInfoType: microhttpd-info daemon. (line 25) * MHD_DigestAuthAlgorithm: microhttpd-dauth digest. (line 10) * MHD_DigestAuthResult: microhttpd-dauth digest. (line 23) * MHD_FEATURE: microhttpd-util feature. (line 6) * MHD_FLAG: microhttpd-const. (line 6) * MHD_IoVec: microhttpd-struct. (line 18) * MHD_OPTION: microhttpd-const. (line 184) * MHD_OptionItem: microhttpd-const. (line 576) * MHD_PostProcessor: microhttpd-struct. (line 21) * MHD_RequestTerminationCode: microhttpd-const. (line 614) * MHD_Response: microhttpd-struct. (line 15) * MHD_ResponseFlags: microhttpd-const. (line 654) * MHD_ResponseMemoryMode: microhttpd-const. (line 632) * MHD_ResponseOptions: microhttpd-const. (line 699) * MHD_UpgradeAction: microhttpd-response upgrade. (line 103) * MHD_ValueKind: microhttpd-const. (line 589) * MHD_WEBSOCKET_CLOSEREASON: microhttpd-const. (line 998) * MHD_WEBSOCKET_FLAG: microhttpd-const. (line 707) * MHD_WEBSOCKET_FRAGMENTATION: microhttpd-const. (line 772) * MHD_WEBSOCKET_STATUS: microhttpd-const. (line 804) * MHD_WEBSOCKET_UTF8STEP: microhttpd-const. (line 1063) * MHD_WEBSOCKET_VALIDITY: microhttpd-const. (line 1121) * MHD_WebSocketStream: microhttpd-struct. (line 30)  Tag Table: Node: Top818 Node: microhttpd-intro3153 Ref: fig:performance8064 Ref: tbl:supported9036 Node: microhttpd-const17461 Node: microhttpd-struct75242 Node: microhttpd-cb76180 Node: microhttpd-init89479 Node: microhttpd-inspect95357 Node: microhttpd-requests98134 Node: microhttpd-responses102184 Node: microhttpd-response enqueue103383 Ref: microhttpd-response enqueue-Footnote-1105708 Node: microhttpd-response create105943 Node: microhttpd-response headers113953 Node: microhttpd-response options116427 Node: microhttpd-response inspect117310 Node: microhttpd-response upgrade118531 Node: microhttpd-flow123873 Node: microhttpd-dauth127425 Node: microhttpd-dauth basic128985 Node: microhttpd-dauth digest130576 Node: microhttpd-post144187 Node: microhttpd-post api147171 Node: microhttpd-info149839 Node: microhttpd-info daemon150255 Node: microhttpd-info conn153703 Node: microhttpd-option conn158962 Node: microhttpd-util160042 Node: microhttpd-util feature160321 Node: microhttpd-util unescape163907 Node: microhttpd-websocket164551 Node: microhttpd-websocket handshake165270 Node: microhttpd-websocket stream170435 Node: microhttpd-websocket decode175475 Node: microhttpd-websocket encode179973 Node: microhttpd-websocket memory189398 Node: GNU-LGPL191223 Node: eCos License219321 Node: GNU-GPL220712 Node: GNU-FDL239974 Node: Concept Index265043 Node: Function and Data Index278229 Node: Type Index288554  End Tag Table  Local Variables: coding: utf-8 End: libmicrohttpd-1.0.2/doc/chapters/0000755000175000017500000000000015035216653013743 500000000000000libmicrohttpd-1.0.2/doc/chapters/exploringrequests.inc0000644000175000017500000001244514674632555020202 00000000000000This chapter will deal with the information which the client sends to the server at every request. We are going to examine the most useful fields of such an request and print them out in a readable manner. This could be useful for logging facilities. The starting point is the @emph{hellobrowser} program with the former response removed. This time, we just want to collect information in the callback function, thus we will just return MHD_NO after we have probed the request. This way, the connection is closed without much ado by the server. @verbatim static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { ... return MHD_NO; } @end verbatim @noindent The ellipsis marks the position where the following instructions shall be inserted. We begin with the most obvious information available to the server, the request line. You should already have noted that a request consists of a command (or "HTTP method") and a URI (e.g. a filename). It also contains a string for the version of the protocol which can be found in @code{version}. To call it a "new request" is justified because we return only @code{MHD_NO}, thus ensuring the function will not be called again for this connection. @verbatim printf ("New %s request for %s using version %s\n", method, url, version); @end verbatim @noindent The rest of the information is a bit more hidden. Nevertheless, there is lot of it sent from common Internet browsers. It is stored in "key-value" pairs and we want to list what we find in the header. As there is no mandatory set of keys a client has to send, each key-value pair is printed out one by one until there are no more left. We do this by writing a separate function which will be called for each pair just like the above function is called for each HTTP request. It can then print out the content of this pair. @verbatim int print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { printf ("%s: %s\n", key, value); return MHD_YES; } @end verbatim @noindent To start the iteration process that calls our new function for every key, the line @verbatim MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL); @end verbatim @noindent needs to be inserted in the connection callback function too. The second parameter tells the function that we are only interested in keys from the general HTTP header of the request. Our iterating function @code{print_out_key} does not rely on any additional information to fulfill its duties so the last parameter can be NULL. All in all, this constitutes the complete @code{logging.c} program for this chapter which can be found in the @code{examples} section. Connecting with any modern Internet browser should yield a handful of keys. You should try to interpret them with the aid of @emph{RFC 2616}. Especially worth mentioning is the "Host" key which is often used to serve several different websites hosted under one single IP address but reachable by different domain names (this is called virtual hosting). @heading Conclusion The introduced capabilities to itemize the content of a simple GET request---especially the URI---should already allow the server to satisfy clients' requests for small specific resources (e.g. files) or even induce alteration of server state. However, the latter is not recommended as the GET method (including its header data) is by convention considered a "safe" operation, which should not change the server's state in a significant way. By convention, GET operations can thus be performed by crawlers and other automatic software. Naturally actions like searching for a passed string are fine. Of course, no transmission can occur while the return value is still set to @code{MHD_NO} in the callback function. @heading Exercises @itemize @bullet @item By parsing the @code{url} string and delivering responses accordingly, implement a small server for "virtual" files. When asked for @code{/index.htm@{l@}}, let the response consist of a HTML page containing a link to @code{/another.html} page which is also to be created "on the fly" in case of being requested. If neither of these two pages are requested, @code{MHD_HTTP_NOT_FOUND} shall be returned accompanied by an informative message. @item A very interesting information has still been ignored by our logger---the client's IP address. Implement a callback function @verbatim static int on_client_connect (void *cls, const struct sockaddr *addr, socklen_t addrlen) @end verbatim @noindent that prints out the IP address in an appropriate format. You might want to use the POSIX function @code{inet_ntoa} but bear in mind that @code{addr} is actually just a structure containing other substructures and is @emph{not} the variable this function expects. Make sure to return @code{MHD_YES} so that the library knows the client is allowed to connect (and to then process the request). If one wanted to limit access basing on IP addresses, this would be the place to do it. The address of your @code{on_client_connect} function must be passed as the third parameter to the @code{MHD_start_daemon} call. @end itemize libmicrohttpd-1.0.2/doc/chapters/tlsauthentication.inc0000644000175000017500000003473014674632555020142 00000000000000We left the basic authentication chapter with the unsatisfactory conclusion that any traffic, including the credentials, could be intercepted by anyone between the browser client and the server. Protecting the data while it is sent over unsecured lines will be the goal of this chapter. Since version 0.4, the @emph{MHD} library includes support for encrypting the traffic by employing SSL/TSL. If @emph{GNU libmicrohttpd} has been configured to support these, encryption and decryption can be applied transparently on the data being sent, with only minimal changes to the actual source code of the example. @heading Preparation First, a private key for the server will be generated. With this key, the server will later be able to authenticate itself to the client---preventing anyone else from stealing the password by faking its identity. The @emph{OpenSSL} suite, which is available on many operating systems, can generate such a key. For the scope of this tutorial, we will be content with a 1024 bit key: @verbatim > openssl genrsa -out server.key 1024 @end verbatim @noindent In addition to the key, a certificate describing the server in human readable tokens is also needed. This certificate will be attested with our aforementioned key. In this way, we obtain a self-signed certificate, valid for one year. @verbatim > openssl req -days 365 -out server.pem -new -x509 -key server.key @end verbatim @noindent To avoid unnecessary error messages in the browser, the certificate needs to have a name that matches the @emph{URI}, for example, "localhost" or the domain. If you plan to have a publicly reachable server, you will need to ask a trusted third party, called @emph{Certificate Authority}, or @emph{CA}, to attest the certificate for you. This way, any visitor can make sure the server's identity is real. Whether the server's certificate is signed by us or a third party, once it has been accepted by the client, both sides will be communicating over encrypted channels. From this point on, it is the client's turn to authenticate itself. But this has already been implemented in the basic authentication scheme. @heading Changing the source code We merely have to extend the server program so that it loads the two files into memory, @verbatim int main () { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); return 1; } @end verbatim @noindent and then we point the @emph{MHD} daemon to it upon initialization. @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } @end verbatim @noindent The rest consists of little new besides some additional memory cleanups. @verbatim getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; } @end verbatim @noindent The rather unexciting file loader can be found in the complete example @code{tlsauthentication.c}. @heading Remarks @itemize @bullet @item While the standard @emph{HTTP} port is 80, it is 443 for @emph{HTTPS}. The common internet browsers assume standard @emph{HTTP} if they are asked to access other ports than these. Therefore, you will have to type @code{https://localhost:8888} explicitly when you test the example, or the browser will not know how to handle the answer properly. @item The remaining weak point is the question how the server will be trusted initially. Either a @emph{CA} signs the certificate or the client obtains the key over secure means. Anyway, the clients have to be aware (or configured) that they should not accept certificates of unknown origin. @item The introduced method of certificates makes it mandatory to set an expiration date---making it less feasible to hardcode certificates in embedded devices. @item The cryptographic facilities consume memory space and computing time. For this reason, websites usually consists both of uncritically @emph{HTTP} parts and secured @emph{HTTPS}. @end itemize @heading Client authentication You can also use MHD to authenticate the client via SSL/TLS certificates (as an alternative to using the password-based Basic or Digest authentication). To do this, you will need to link your application against @emph{gnutls}. Next, when you start the MHD daemon, you must specify the root CA that you're willing to trust: @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem, MHD_OPTION_END); @end verbatim With this, you can then obtain client certificates for each session. In order to obtain the identity of the client, you first need to obtain the raw GnuTLS session handle from @emph{MHD} using @code{MHD_get_connection_info}. @verbatim #include #include gnutls_session_t tls_session; union MHD_ConnectionInfo *ci; ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_SESSION); tls_session = (gnutls_session_t) ci->tls_session; @end verbatim You can then extract the client certificate: @verbatim /** * Get the client's certificate * * @param tls_session the TLS session * @return NULL if no valid client certificate could be found, a pointer * to the certificate if found */ static gnutls_x509_crt_t get_client_certificate (gnutls_session_t tls_session) { unsigned int listsize; const gnutls_datum_t * pcert; gnutls_certificate_status_t client_cert_status; gnutls_x509_crt_t client_cert; if (tls_session == NULL) return NULL; if (gnutls_certificate_verify_peers2(tls_session, &client_cert_status)) return NULL; if (0 != client_cert_status) { fprintf (stderr, "Failed client certificate invalid: %d\n", client_cert_status); return NULL; } pcert = gnutls_certificate_get_peers(tls_session, &listsize); if ( (pcert == NULL) || (listsize == 0)) { fprintf (stderr, "Failed to retrieve client certificate chain\n"); return NULL; } if (gnutls_x509_crt_init(&client_cert)) { fprintf (stderr, "Failed to initialize client certificate\n"); return NULL; } /* Note that by passing values between 0 and listsize here, you can get access to the CA's certs */ if (gnutls_x509_crt_import(client_cert, &pcert[0], GNUTLS_X509_FMT_DER)) { fprintf (stderr, "Failed to import client certificate\n"); gnutls_x509_crt_deinit(client_cert); return NULL; } return client_cert; } @end verbatim Using the client certificate, you can then get the client's distinguished name and alternative names: @verbatim /** * Get the distinguished name from the client's certificate * * @param client_cert the client certificate * @return NULL if no dn or certificate could be found, a pointer * to the dn if found */ char * cert_auth_get_dn(gnutls_x509_crt_t client_cert) { char* buf; size_t lbuf; lbuf = 0; gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf); buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate dn\n"); return NULL; } gnutls_x509_crt_get_dn(client_cert, buf, &lbuf); return buf; } /** * Get the alternative name of specified type from the client's certificate * * @param client_cert the client certificate * @param nametype The requested name type * @param index The position of the alternative name if multiple names are * matching the requested type, 0 for the first matching name * @return NULL if no matching alternative name could be found, a pointer * to the alternative name if found */ char * MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert, int nametype, unsigned int index) { char* buf; size_t lbuf; unsigned int seq; unsigned int subseq; unsigned int type; int result; subseq = 0; for (seq=0;;seq++) { lbuf = 0; result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf, &type, NULL); if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) return NULL; if (nametype != (int) type) continue; if (subseq == index) break; subseq++; } buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate alt name\n"); return NULL; } result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, buf, &lbuf, NULL, NULL); if (result != nametype) { fprintf (stderr, "Unexpected return value from gnutls: %d\n", result); free (buf); return NULL; } return buf; } @end verbatim Finally, you should release the memory associated with the client certificate: @verbatim gnutls_x509_crt_deinit (client_cert); @end verbatim @heading Using TLS Server Name Indication (SNI) SNI enables hosting multiple domains under one IP address with TLS. So SNI is the TLS-equivalent of virtual hosting. To use SNI with MHD, you need at least GnuTLS 3.0. The main change compared to the simple hosting of one domain is that you need to provide a callback instead of the key and certificate. For example, when you start the MHD daemon, you could do this: @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); @end verbatim Here, @code{sni_callback} is the name of a function that you will have to implement to retrieve the X.509 certificate for an incoming connection. The callback has type @code{gnutls_certificate_retrieve_function2} and is documented in the GnuTLS API for the @code{gnutls_certificate_set_retrieve_function2} as follows: @deftypefn {Function Pointer} int {*gnutls_certificate_retrieve_function2} (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) @table @var @item req_ca_cert is only used in X.509 certificates. Contains a list with the CA names that the server considers trusted. Normally we should send a certificate that is signed by one of these CAs. These names are DER encoded. To get a more meaningful value use the function @code{gnutls_x509_rdn_get()}. @item pk_algos contains a list with server’s acceptable signature algorithms. The certificate returned should support the server’s given algorithms. @item pcert should contain a single certificate and public or a list of them. @item pcert_length is the size of the previous list. @item pkey is the private key. @end table @end deftypefn A possible implementation of this callback would look like this: @verbatim struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; static struct Hosts *hosts; int sni_callback (gnutls_session_t session, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } @end verbatim Note that MHD cannot offer passing a closure or any other additional information to this callback, as the GnuTLS API unfortunately does not permit this at this point. The @code{hosts} list can be initialized by loading the private keys and X.509 certificates from disk as follows: @verbatim static void load_keys(const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit(1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf(stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit(1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); } @end verbatim The code above was largely lifted from GnuTLS. You can find other methods for initializing certificates and keys in the GnuTLS manual and source code. libmicrohttpd-1.0.2/doc/chapters/websocket.inc0000644000175000017500000006644514674632555016376 00000000000000Websockets are a genuine way to implement push notifications, where the server initiates the communication while the client can be idle. Usually a HTTP communication is half-duplex and always requested by the client, but websockets are full-duplex and only initialized by the client. In the further communication both sites can use the websocket at any time to send data to the other site. To initialize a websocket connection the client sends a special HTTP request to the server and initializes a handshake between client and server which switches from the HTTP protocol to the websocket protocol. Thus both the server as well as the client must support websockets. If proxys are used, they must support websockets too. In this chapter we take a look on server and client, but with a focus on the server with @emph{libmicrohttpd}. Since version 0.9.52 @emph{libmicrohttpd} supports upgrading requests, which is required for switching from the HTTP protocol. Since version 0.9.74 the library @emph{libmicrohttpd_ws} has been added to support the websocket protocol. @heading Upgrading connections with libmicrohttpd To support websockets we need to enable upgrading of HTTP connections first. This is done by passing the flag @code{MHD_ALLOW_UPGRADE} to @code{MHD_start_daemon()}. @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_ALLOW_UPGRADE | MHD_USE_ERROR_LOG, PORT, NULL, NULL, &access_handler, NULL, MHD_OPTION_END); @end verbatim @noindent The next step is to turn a specific request into an upgraded connection. This done in our @code{access_handler} by calling @code{MHD_create_response_for_upgrade()}. An @code{upgrade_handler} will be passed to perform the low-level actions on the socket. @emph{Please note that the socket here is just a regular socket as provided by the operating system. To use it as a websocket, some more steps from the following chapters are required.} @verbatim static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { /* ... */ /* some code to decide whether to upgrade or not */ /* ... */ /* create the response for upgrade */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); /* ... */ /* additional headers, etc. */ /* ... */ ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent In the @code{upgrade_handler} we receive the low-level socket, which is used for the communication with the specific client. In addition to the low-level socket we get: @itemize @bullet @item Some data, which has been read too much while @emph{libmicrohttpd} was switching the protocols. This value is usually empty, because it would mean that the client has sent data before the handshake was complete. @item A @code{struct MHD_UpgradeResponseHandle} which is used to perform special actions like closing, corking or uncorking the socket. These commands are executed by passing the handle to @code{MHD_upgrade_action()}. @end itemize Depending of the flags specified while calling @code{MHD_start_deamon()} our @code{upgrade_handler} is either executed in the same thread as our daemon or in a thread specific for each connection. If it is executed in the same thread then @code{upgrade_handler} is a blocking call for our webserver and we should finish it as fast as possible (i. e. by creating a thread and passing the information there). If @code{MHD_USE_THREAD_PER_CONNECTION} was passed to @code{MHD_start_daemon()} then a separate thread is used and thus our @code{upgrade_handler} needs not to start a separate thread. An @code{upgrade_handler}, which is called with a separate thread per connection, could look like this: @verbatim static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { /* ... */ /* do something with the socket `fd` like `recv()` or `send()` */ /* ... */ /* close the socket when it is not needed anymore */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } @end verbatim @noindent This is all you need to know for upgrading connections with @emph{libmicrohttpd}. The next chapters focus on using the websocket protocol with @emph{libmicrohttpd_ws}. @heading Websocket handshake with libmicrohttpd_ws To request a websocket connection the client must send the following information with the HTTP request: @itemize @bullet @item A @code{GET} request must be sent. @item The version of the HTTP protocol must be 1.1 or higher. @item A @code{Host} header field must be sent @item A @code{Upgrade} header field containing the keyword "websocket" (case-insensitive). Please note that the client could pass multiple protocols separated by comma. @item A @code{Connection} header field that includes the token "Upgrade" (case-insensitive). Please note that the client could pass multiple tokens separated by comma. @item A @code{Sec-WebSocket-Key} header field with a base64-encoded value. The decoded the value is 16 bytes long and has been generated randomly by the client. @item A @code{Sec-WebSocket-Version} header field with the value "13". @end itemize Optionally the client can also send the following information: @itemize @bullet @item A @code{Origin} header field can be used to determine the source of the client (i. e. the website). @item A @code{Sec-WebSocket-Protocol} header field can contain a list of supported protocols by the client, which can be sent over the websocket. @item A @code{Sec-WebSocket-Extensions} header field which may contain extensions to the websocket protocol. The extensions must be registered by IANA. @end itemize A valid example request from the client could look like this: @verbatim GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 @end verbatim @noindent To complete the handshake the server must respond with some specific response headers: @itemize @bullet @item The HTTP response code @code{101 Switching Protocols} must be answered. @item An @code{Upgrade} header field containing the value "websocket" must be sent. @item A @code{Connection} header field containing the value "Upgrade" must be sent. @item A @code{Sec-WebSocket-Accept} header field containing a value, which has been calculated from the @code{Sec-WebSocket-Key} request header field, must be sent. @end itemize Optionally the server may send following headers: @itemize @bullet @item A @code{Sec-WebSocket-Protocol} header field containing a protocol of the list specified in the corresponding request header field. @item A @code{Sec-WebSocket-Extension} header field containing all used extensions of the list specified in the corresponding request header field. @end itemize A valid websocket HTTP response could look like this: @verbatim HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= @end verbatim @noindent To upgrade a connection to a websocket the @emph{libmicrohttpd_ws} provides some helper functions for the @code{access_handler} callback function: @itemize @bullet @item @code{MHD_websocket_check_http_version()} checks whether the HTTP version is 1.1 or above. @item @code{MHD_websocket_check_connection_header()} checks whether the value of the @code{Connection} request header field contains an "Upgrade" token (case-insensitive). @item @code{MHD_websocket_check_upgrade_header()} checks whether the value of the @code{Upgrade} request header field contains the "websocket" keyword (case-insensitive). @item @code{MHD_websocket_check_version_header()} checks whether the value of the @code{Sec-WebSocket-Version} request header field is "13". @item @code{MHD_websocket_create_accept_header()} takes the value from the @code{Sec-WebSocket-Key} request header and calculates the value for the @code{Sec-WebSocket-Accept} response header field. @end itemize The @code{access_handler} example of the previous chapter can now be extended with these helper functions to perform the websocket handshake: @verbatim static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { static int aptr; struct MHD_Response *response; int ret; (void) cls; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *ptr) { /* do never respond on first call */ *ptr = &aptr; return MHD_YES; } *ptr = NULL; /* reset when done */ if (0 == strcmp (url, "/")) { /* Default page for visiting the server */ struct MHD_Response *response = MHD_create_response_from_buffer ( strlen (PAGE), PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else if (0 == strcmp (url, "/chat")) { char is_valid = 1; const char* value = NULL; char sec_websocket_accept[29]; if (0 != MHD_websocket_check_http_version (version)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (0 != MHD_websocket_check_connection_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE); if (0 != MHD_websocket_check_upgrade_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION); if (0 != MHD_websocket_check_version_header (value)) { is_valid = 0; } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY); if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept)) { is_valid = 0; } if (1 == is_valid) { /* upgrade the connection */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "Upgrade"); MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "websocket"); MHD_add_response_header (response, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT, sec_websocket_accept); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); } else { /* return error page */ struct MHD_Response*response = MHD_create_response_from_buffer ( strlen (PAGE_INVALID_WEBSOCKET_REQUEST), PAGE_INVALID_WEBSOCKET_REQUEST, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); } } else { struct MHD_Response*response = MHD_create_response_from_buffer ( strlen (PAGE_NOT_FOUND), PAGE_NOT_FOUND, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } return ret; } @end verbatim @noindent Please note that we skipped the check of the Host header field here, because we don't know the host for this example. @heading Decoding/encoding the websocket protocol with libmicrohttpd_ws Once the websocket connection is established you can receive/send frame data with the low-level socket functions @code{recv()} and @code{send()}. The frame data which goes over the low-level socket is encoded according to the websocket protocol. To use received payload data, you need to decode the frame data first. To send payload data, you need to encode it into frame data first. @emph{libmicrohttpd_ws} provides several functions for encoding of payload data and decoding of frame data: @itemize @bullet @item @code{MHD_websocket_decode()} decodes received frame data. The payload data may be of any kind, depending upon what the client has sent. So this decode function is used for all kind of frames and returns the frame type along with the payload data. @item @code{MHD_websocket_encode_text()} encodes text. The text must be encoded with UTF-8. @item @code{MHD_websocket_encode_binary()} encodes binary data. @item @code{MHD_websocket_encode_ping()} encodes a ping request to check whether the websocket is still valid and to test latency. @item @code{MHD_websocket_encode_ping()} encodes a pong response to answer a received ping request. @item @code{MHD_websocket_encode_close()} encodes a close request. @item @code{MHD_websocket_free()} frees data returned by the encode/decode functions. @end itemize Since you could receive or send fragmented data (i. e. due to a too small buffer passed to @code{recv}) all of these encode/decode functions require a pointer to a @code{struct MHD_WebSocketStream} passed as argument. In this structure @emph{libmicrohttpd_ws} stores information about encoding/decoding of the particular websocket. For each websocket you need a unique @code{struct MHD_WebSocketStream} to encode/decode with this library. To create or destroy @code{struct MHD_WebSocketStream} we have additional functions: @itemize @bullet @item @code{MHD_websocket_stream_init()} allocates and initializes a new @code{struct MHD_WebSocketStream}. You can specify some options here to alter the behavior of the websocket stream. @item @code{MHD_websocket_stream_free()} frees a previously allocated @code{struct MHD_WebSocketStream}. @end itemize With these encode/decode functions we can improve our @code{upgrade_handler} callback function from an earlier example to a working websocket: @verbatim static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket fd, struct MHD_UpgradeResponseHandle *urh) { /* make the socket blocking (operating-system-dependent code) */ make_blocking (fd); /* create a websocket stream for this connection */ struct MHD_WebSocketStream* ws; int result = MHD_websocket_stream_init (&ws, 0, 0); if (0 != result) { /* Couldn't create the websocket stream. * So we close the socket and leave */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return; } /* Let's wait for incoming data */ const size_t buf_len = 256; char buf[buf_len]; ssize_t got; while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws)) { got = recv (fd, buf, buf_len, 0); if (0 >= got) { /* the TCP/IP socket has been closed */ break; } /* parse the entire received data */ size_t buf_offset = 0; while (buf_offset < (size_t) got) { size_t new_offset = 0; char *frame_data = NULL; size_t frame_len = 0; int status = MHD_websocket_decode (ws, buf + buf_offset, ((size_t) got) - buf_offset, &new_offset, &frame_data, &frame_len); if (0 > status) { /* an error occurred and the connection must be closed */ if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } break; } else { buf_offset += new_offset; if (0 < status) { /* the frame is complete */ switch (status) { case MHD_WEBSOCKET_STATUS_TEXT_FRAME: /* The client has sent some text. * We will display it and answer with a text frame. */ if (NULL != frame_data) { printf ("Received message: %s\n", frame_data); MHD_websocket_free (ws, frame_data); frame_data = NULL; } result = MHD_websocket_encode_text (ws, "Hello", 5, /* length of "Hello" */ 0, &frame_data, &frame_len, NULL); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_CLOSE_FRAME: /* if we receive a close frame, we will respond with one */ MHD_websocket_free (ws, frame_data); frame_data = NULL; result = MHD_websocket_encode_close (ws, 0, NULL, 0, &frame_data, &frame_len); if (0 == result) { send_all (fd, frame_data, frame_len); } break; case MHD_WEBSOCKET_STATUS_PING_FRAME: /* if we receive a ping frame, we will respond */ /* with the corresponding pong frame */ { char *pong = NULL; size_t pong_len = 0; result = MHD_websocket_encode_pong (ws, frame_data, frame_len, &pong, &pong_len); if (0 == result) { send_all (fd, pong, pong_len); } MHD_websocket_free (ws, pong); } break; default: /* Other frame types are ignored * in this minimal example. * This is valid, because they become * automatically skipped if we receive them unexpectedly */ break; } } if (NULL != frame_data) { MHD_websocket_free (ws, frame_data); } } } } /* free the websocket stream */ MHD_websocket_stream_free (ws); /* close the socket when it is not needed anymore */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } /* This helper function is used for the case that * we need to resend some data */ static void send_all (MHD_socket fd, const char *buf, size_t len) { ssize_t ret; size_t off; for (off = 0; off < len; off += ret) { ret = send (fd, &buf[off], (int) (len - off), 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } } /* This helper function contains operating-system-dependent code and * is used to make a socket blocking. */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) return; if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; ioctlsocket (fd, FIONBIO, &flags); #endif /* MHD_WINSOCK_SOCKETS */ } @end verbatim @noindent Please note that the websocket in this example is only half-duplex. It waits until the blocking @code{recv()} call returns and only does then something. In this example all frame types are decoded by @emph{libmicrohttpd_ws}, but we only do something when a text, ping or close frame is received. Binary and pong frames are ignored in our code. This is legit, because the server is only required to implement at least support for ping frame or close frame (the other frame types could be skipped in theory, because they don't require an answer). The pong frame doesn't require an answer and whether text frames or binary frames get an answer simply belongs to your server application. So this is a valid minimal example. Until this point you've learned everything you need to basically use websockets with @emph{libmicrohttpd} and @emph{libmicrohttpd_ws}. These libraries offer much more functions for some specific cases. The further chapters of this tutorial focus on some specific problems and the client site programming. @heading Using full-duplex websockets To use full-duplex websockets you can simply create two threads per websocket connection. One of these threads is used for receiving data with a blocking @code{recv()} call and the other thread is triggered by the application internal codes and sends the data. A full-duplex websocket example is implemented in the example file @code{websocket_chatserver_example.c}. @heading Error handling The most functions of @emph{libmicrohttpd_ws} return a value of @code{enum MHD_WEBSOCKET_STATUS}. The values of this enumeration can be converted into an integer and have an easy interpretation: @itemize @bullet @item If the value is less than zero an error occurred and the call has failed. Check the enumeration values for more specific information. @item If the value is equal to zero, the call succeeded. @item If the value is greater than zero, the call succeeded and the value specifies the decoded frame type. Currently positive values are only returned by @code{MHD_websocket_decode()} (of the functions with this return enumeration type). @end itemize A websocket stream can also get broken when invalid frame data is received. Also the other site could send a close frame which puts the stream into a state where it may not be used for regular communication. Whether a stream has become broken, can be checked with @code{MHD_websocket_stream_is_valid()}. @heading Fragmentation In addition to the regular TCP/IP fragmentation the websocket protocol also supports fragmentation. Fragmentation could be used for continuous payload data such as video data from a webcam. Whether or not you want to receive fragmentation is specified upon initialization of the websocket stream. If you pass @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} in the flags parameter of @code{MHD_websocket_stream_init()} then you can receive fragments. If you don't pass this flag (in the most cases you just pass zero as flags) then you don't want to handle fragments on your own. @emph{libmicrohttpd_ws} removes then the fragmentation for you in the background. You only get the completely assembled frames. Upon encoding you specify whether or not you want to create a fragmented frame by passing a flag to the corresponding encode function. Only @code{MHD_websocket_encode_text()} and @code{MHD_websocket_encode_binary()} can be used for fragmentation, because the other frame types may not be fragmented. Encoding fragmented frames is independent of the @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} flag upon initialization. @heading Quick guide to websockets in JavaScript Websockets are supported in all modern web browsers. You initialize a websocket connection by creating an instance of the @code{WebSocket} class provided by the web browser. There are some simple rules for using websockets in the browser: @itemize @bullet @item When you initialize the instance of the websocket class you must pass an URL. The URL must either start with @code{ws://} (for not encrypted websocket protocol) or @code{wss://} (for TLS-encrypted websocket protocol). @strong{IMPORTANT:} If your website is accessed via @code{https://} then you are in a security context, which means that you are only allowed to access other secure protocols. So you can only use @code{wss://} for websocket connections then. If you try to @code{ws://} instead then your websocket connection will automatically fail. @item The WebSocket class uses events to handle the receiving of data. JavaScript is per definition a single-threaded language so the receiving events will never overlap. Sending is done directly by calling a method of the instance of the WebSocket class. @end itemize Here is a short example for receiving/sending data to the same host as the website is running on: @verbatim Websocket Demo @end verbatim @noindent libmicrohttpd-1.0.2/doc/chapters/introduction.inc0000644000175000017500000000225214674632555017113 00000000000000This tutorial is for developers who want to learn how they can add HTTP serving capabilities to their applications with the @emph{GNU libmicrohttpd} library, abbreviated @emph{MHD}. The reader will learn how to implement basic HTTP functions from simple executable sample programs that implement various features. The text is supposed to be a supplement to the API reference manual of @emph{GNU libmicrohttpd} and for that reason does not explain many of the parameters. Therefore, the reader should always consult the manual to find the exact meaning of the functions used in the tutorial. Furthermore, the reader is encouraged to study the relevant @emph{RFCs}, which document the HTTP standard. @emph{GNU libmicrohttpd} is assumed to be already installed. This tutorial is written for version @value{VERSION}. At the time being, this tutorial has only been tested on @emph{GNU/Linux} machines even though efforts were made not to rely on anything that would prevent the samples from being built on similar systems. @section History This tutorial was originally written by Sebastian Gerhardt for MHD 0.4.0. It was slightly polished and updated to MHD 0.9.0 by Christian Grothoff.libmicrohttpd-1.0.2/doc/chapters/sessions.inc0000644000175000017500000000641014674632555016240 00000000000000This chapter discusses how one should manage sessions, that is, share state between multiple HTTP requests from the same user. We use a simple example where the user submits multiple forms and the server is supposed to accumulate state from all of these forms. Naturally, as this is a network protocol, our session mechanism must support having many users with many concurrent sessions at the same time. In order to track users, we use a simple session cookie. A session cookie expires when the user closes the browser. Changing from session cookies to persistent cookies only requires adding an expiration time to the cookie. The server creates a fresh session cookie whenever a request without a cookie is received, or if the supplied session cookie is not known to the server. @heading Looking up the cookie Since MHD parses the HTTP cookie header for us, looking up an existing cookie is straightforward: @verbatim const char *value; value = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "KEY"); @end verbatim Here, "KEY" is the name we chose for our session cookie. @heading Setting the cookie header MHD requires the user to provide the full cookie format string in order to set cookies. In order to generate a unique cookie, our example creates a random 64-character text string to be used as the value of the cookie: @verbatim char value[128]; char raw_value[65]; for (unsigned int i=0;i} consisting of one row and @code{n} columns whose fields contain small images of either a red or a green light. @end itemize libmicrohttpd-1.0.2/doc/chapters/basicauthentication.inc0000644000175000017500000002323014674632555020412 00000000000000With the small exception of IP address based access control, requests from all connecting clients where served equally until now. This chapter discusses a first method of client's authentication and its limits. A very simple approach feasible with the means already discussed would be to expect the password in the @emph{URI} string before granting access to the secured areas. The password could be separated from the actual resource identifier by a certain character, thus the request line might look like @verbatim GET /picture.png?mypassword @end verbatim @noindent In the rare situation where the client is customized enough and the connection occurs through secured lines (e.g., a embedded device directly attached to another via wire) and where the ability to embed a password in the URI or to pass on a URI with a password are desired, this can be a reasonable choice. But when it is assumed that the user connecting does so with an ordinary Internet browser, this implementation brings some problems about. For example, the URI including the password stays in the address field or at least in the history of the browser for anybody near enough to see. It will also be inconvenient to add the password manually to any new URI when the browser does not know how to compose this automatically. At least the convenience issue can be addressed by employing the simplest built-in password facilities of HTTP compliant browsers, hence we want to start there. It will, however, turn out to have still severe weaknesses in terms of security which need consideration. Before we will start implementing @emph{Basic Authentication} as described in @emph{RFC 2617}, we will also abandon the simplistic and generally problematic practice of responding every request the first time our callback is called for a given connection. Queuing a response upon the first request is akin to generating an error response (even if it is a "200 OK" reply!). The reason is that MHD usually calls the callback in three phases: @enumerate @item First, to initially tell the application about the connection and inquire whether it is OK to proceed. This call typically happens before the client could upload the request body, and can be used to tell the client to not proceed with the upload (if the client requested "Expect: 100 Continue"). Applications may queue a reply at this point, but it will force the connection to be closed and thus prevent keep-alive / pipelining, which is generally a bad idea. Applications wanting to proceed with the request throughout the other phases should just return "MHD_YES" and not queue any response. Note that when an application suspends a connection in this callback, the phase does not advance and the application will be called again in this first phase. @item Next, to tell the application about upload data provided by the client. In this phase, the application may not queue replies, and trying to do so will result in MHD returning an error code from @code{MHD_queue_response}. If there is no upload data, this phase is skipped. @item Finally, to obtain a regular response from the application. This can be almost any type of response, including ones indicating failures. The one exception is a "100 Continue" response, which applications must never generate: MHD generates that response automatically when necessary in the first phase. If the application does not queue a response, MHD may call the callback repeatedly (depending a bit on the threading model, the application should suspend the connection). @end enumerate But how can we tell whether the callback has been called before for the particular request? Initially, the pointer this parameter references is set by @emph{MHD} in the callback. But it will also be "remembered" on the next call (for the same request). Thus, we can use the @code{req_cls} location to keep track of the request state. For now, we will simply generate no response until the parameter is non-null---implying the callback was called before at least once. We do not need to share information between different calls of the callback, so we can set the parameter to any address that is assured to be not null. The pointer to the @code{connection} structure will be pointing to a legal address, so we take this. The first time @code{answer_to_connection} is called, we will not even look at the headers. @verbatim static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (0 != strcmp(method, "GET")) return MHD_NO; if (NULL == *req_cls) {*req_cls = connection; return MHD_YES;} ... /* else respond accordingly */ ... } @end verbatim @noindent Note how we lop off the connection on the first condition (no "GET" request), but return asking for more on the other one with @code{MHD_YES}. With this minor change, we can proceed to implement the actual authentication process. @heading Request for authentication Let us assume we had only files not intended to be handed out without the correct username/password, so every "GET" request will be challenged. @emph{RFC 7617} describes how the server shall ask for authentication by adding a @emph{WWW-Authenticate} response header with the name of the @emph{realm} protected. MHD can generate and queue such a failure response for you using the @code{MHD_queue_basic_auth_fail_response} API. The only thing you need to do is construct a response with the error page to be shown to the user if he aborts basic authentication. But first, you should check if the proper credentials were already supplied using the @code{MHD_basic_auth_get_username_password} call. Your code would then look like this: @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_fail_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_fail_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } @end verbatim See the @code{examples} directory for the complete example file. @heading Remarks For a proper server, the conditional statements leading to a return of @code{MHD_NO} should yield a response with a more precise status code instead of silently closing the connection. For example, failures of memory allocation are best reported as @emph{internal server error} and unexpected authentication methods as @emph{400 bad request}. @heading Exercises @itemize @bullet @item Make the server respond to wrong credentials (but otherwise well-formed requests) with the recommended @emph{401 unauthorized} status code. If the client still does not authenticate correctly within the same connection, close it and store the client's IP address for a certain time. (It is OK to check for expiration not until the main thread wakes up again on the next connection.) If the client fails authenticating three times during this period, add it to another list for which the @code{AcceptPolicyCallback} function denies connection (temporally). @item With the network utility @code{netcat} connect and log the response of a "GET" request as you did in the exercise of the first example, this time to a file. Now stop the server and let @emph{netcat} listen on the same port the server used to listen on and have it fake being the proper server by giving the file's content as the response (e.g. @code{cat log | nc -l -p 8888}). Pretending to think your were connecting to the actual server, browse to the eavesdropper and give the correct credentials. Copy and paste the encoded string you see in @code{netcat}'s output to some of the Base64 decode tools available online and see how both the user's name and password could be completely restored. @end itemize libmicrohttpd-1.0.2/doc/chapters/hellobrowser.inc0000644000175000017500000002613214674632555017104 00000000000000The most basic task for a HTTP server is to deliver a static text message to any client connecting to it. Given that this is also easy to implement, it is an excellent problem to start with. For now, the particular URI the client asks for shall have no effect on the message that will be returned. In addition, the server shall end the connection after the message has been sent so that the client will know there is nothing more to expect. The C program @code{hellobrowser.c}, which is to be found in the examples section, does just that. If you are very eager, you can compile and start it right away but it is advisable to type the lines in by yourself as they will be discussed and explained in detail. After the necessary includes and the definition of the port which our server should listen on @verbatim #include #include #include #include #define PORT 8888 @end verbatim @noindent the desired behaviour of our server when HTTP request arrive has to be implemented. We already have agreed that it should not care about the particular details of the request, such as who is requesting what. The server will respond merely with the same small HTML page to every request. The function we are going to write now will be called by @emph{GNU libmicrohttpd} every time an appropriate request comes in. While the name of this callback function is arbitrary, its parameter list has to follow a certain layout. So please, ignore the lot of parameters for now, they will be explained at the point they are needed. We have to use only one of them, @code{struct MHD_Connection *connection}, for the minimalistic functionality we want to achieve at the moment. This parameter is set by the @emph{libmicrohttpd} daemon and holds the necessary information to relate the call with a certain connection. Keep in mind that a server might have to satisfy hundreds of concurrent connections and we have to make sure that the correct data is sent to the destined client. Therefore, this variable is a means to refer to a particular connection if we ask the daemon to sent the reply. Talking about the reply, it is defined as a string right after the function header @verbatim int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; @end verbatim @noindent HTTP is a rather strict protocol and the client would certainly consider it "inappropriate" if we just sent the answer string "as is". Instead, it has to be wrapped with additional information stored in so-called headers and footers. Most of the work in this area is done by the library for us---we just have to ask. Our reply string packed in the necessary layers will be called a "response". To obtain such a response we hand our data (the reply--string) and its size over to the @code{MHD_create_response_from_buffer} function. The last two parameters basically tell @emph{MHD} that we do not want it to dispose the message data for us when it has been sent and there also needs no internal copy to be done because the @emph{constant} string won't change anyway. @verbatim struct MHD_Response *response; int ret; response = MHD_create_response_from_buffer (strlen (page), (void*) page, MHD_RESPMEM_PERSISTENT); @end verbatim @noindent Now that the the response has been laced up, it is ready for delivery and can be queued for sending. This is done by passing it to another @emph{GNU libmicrohttpd} function. As all our work was done in the scope of one function, the recipient is without doubt the one associated with the local variable @code{connection} and consequently this variable is given to the queue function. Every HTTP response is accompanied by a status code, here "OK", so that the client knows this response is the intended result of his request and not due to some error or malfunction. Finally, the packet is destroyed and the return value from the queue returned, already being set at this point to either MHD_YES or MHD_NO in case of success or failure. @verbatim ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent With the primary task of our server implemented, we can start the actual server daemon which will listen on @code{PORT} for connections. This is done in the main function. @verbatim int main () { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; @end verbatim @noindent The first parameter is one of three possible modes of operation. Here we want the daemon to run in a separate thread and to manage all incoming connections in the same thread. This means that while producing the response for one connection, the other connections will be put on hold. In this example, where the reply is already known and therefore the request is served quickly, this poses no problem. We will allow all clients to connect regardless of their name or location, therefore we do not check them on connection and set the third and fourth parameter to NULL. Parameter five is the address of the function we want to be called whenever a new connection has been established. Our @code{answer_to_connection} knows best what the client wants and needs no additional information (which could be passed via the next parameter) so the next (sixth) parameter is NULL. Likewise, we do not need to pass extra options to the daemon so we just write the MHD_OPTION_END as the last parameter. As the server daemon runs in the background in its own thread, the execution flow in our main function will continue right after the call. Because of this, we must delay the execution flow in the main thread or else the program will terminate prematurely. We let it pause in a processing-time friendly manner by waiting for the enter key to be pressed. In the end, we stop the daemon so it can do its cleanup tasks. @verbatim getchar (); MHD_stop_daemon (daemon); return 0; } @end verbatim @noindent The first example is now complete. Compile it with @verbatim cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd @end verbatim with the two paths set accordingly and run it. Now open your favorite Internet browser and go to the address @code{http://localhost:8888/}, provided that 8888 is the port you chose. If everything works as expected, the browser will present the message of the static HTML page it got from our minimal server. @heading Remarks To keep this first example as small as possible, some drastic shortcuts were taken and are to be discussed now. Firstly, there is no distinction made between the kinds of requests a client could send. We implied that the client sends a GET request, that means, that he actually asked for some data. Even when it is not intended to accept POST requests, a good server should at least recognize that this request does not constitute a legal request and answer with an error code. This can be easily implemented by checking if the parameter @code{method} equals the string "GET" and returning a @code{MHD_NO} if not so. Secondly, the above practice of queuing a response upon the first call of the callback function brings with it some limitations. This is because the content of the message body will not be received if a response is queued in the first iteration. Furthermore, the connection will be closed right after the response has been transferred then. This is typically not what you want as it disables HTTP pipelining. The correct approach is to simply not queue a message on the first callback unless there is an error. The @code{void**} argument to the callback provides a location for storing information about the history of the connection; for the first call, the pointer will point to NULL. A simplistic way to differentiate the first call from others is to check if the pointer is NULL and set it to a non-NULL value during the first call. Both of these issues you will find addressed in the official @code{minimal_example.c} residing in the @code{src/examples} directory of the @emph{MHD} package. The source code of this program should look very familiar to you by now and easy to understand. For our example, we create the response from a static (persistent) buffer in memory and thus pass @code{MHD_RESPMEM_PERSISTENT} to the response construction function. In the usual case, responses are not transmitted immediately after being queued. For example, there might be other data on the system that needs to be sent with a higher priority. Nevertheless, the queue function will return successfully---raising the problem that the data we have pointed to may be invalid by the time it is about being sent. This is not an issue here because we can expect the @code{page} string, which is a constant @emph{string literal} here, to be static. That means it will be present and unchanged for as long as the program runs. For dynamic data, one could choose to either have @emph{MHD} free the memory @code{page} points to itself when it is not longer needed (by passing @code{MHD_RESPMEM_MUST_FREE}) or, alternatively, have the library to make and manage its own copy of it (by passing @code{MHD_RESPMEM_MUST_COPY}). Naturally, this last option is the most expensive. @heading Exercises @itemize @bullet @item While the server is running, use a program like @code{telnet} or @code{netcat} to connect to it. Try to form a valid HTTP 1.1 request yourself like @verbatim GET /dontcare HTTP/1.1 Host: itsme @end verbatim @noindent and see what the server returns to you. @item Also, try other requests, like POST, and see how our server does not mind and why. How far in malforming a request can you go before the builtin functionality of @emph{MHD} intervenes and an altered response is sent? Make sure you read about the status codes in the @emph{RFC}. @item Add the option @code{MHD_USE_PEDANTIC_CHECKS} to the start function of the daemon in @code{main}. Mind the special format of the parameter list here which is described in the manual. How indulgent is the server now to your input? @item Let the main function take a string as the first command line argument and pass @code{argv[1]} to the @code{MHD_start_daemon} function as the sixth parameter. The address of this string will be passed to the callback function via the @code{cls} variable. Decorate the text given at the command line when the server is started with proper HTML tags and send it as the response instead of the former static string. @item @emph{Demanding:} Write a separate function returning a string containing some useful information, for example, the time. Pass the function's address as the sixth parameter and evaluate this function on every request anew in @code{answer_to_connection}. Remember to free the memory of the string every time after satisfying the request. @end itemize libmicrohttpd-1.0.2/doc/chapters/largerpost.inc0000644000175000017500000002577414674632555016572 00000000000000The previous chapter introduced a way to upload data to the server, but the developed example program has some shortcomings, such as not being able to handle larger chunks of data. In this chapter, we are going to discuss a more advanced server program that allows clients to upload a file in order to have it stored on the server's filesystem. The server shall also watch and limit the number of clients concurrently uploading, responding with a proper busy message if necessary. @heading Prepared answers We choose to operate the server with the @code{SELECT_INTERNALLY} method. This makes it easier to synchronize the global states at the cost of possible delays for other connections if the processing of a request is too slow. One of these variables that needs to be shared for all connections is the total number of clients that are uploading. @verbatim #define MAXCLIENTS 2 static unsigned int nr_of_uploading_clients = 0; @end verbatim @noindent If there are too many clients uploading, we want the server to respond to all requests with a busy message. @verbatim const char* busypage = "This server is busy, please try again later."; @end verbatim @noindent Otherwise, the server will send a @emph{form} that informs the user of the current number of uploading clients, and ask her to pick a file on her local filesystem which is to be uploaded. @verbatim const char* askpage = "\n\ Upload a file, please!
    \n\ There are %u clients uploading at the moment.
    \n\ \n\ \n\ \n\ "; @end verbatim @noindent If the upload has succeeded, the server will respond with a message saying so. @verbatim const char* completepage = "The upload has been completed."; @end verbatim @noindent We want the server to report internal errors, such as memory shortage or file access problems, adequately. @verbatim const char* servererrorpage = "An internal server error has occurred."; const char* fileexistspage = "This file already exists."; @end verbatim @noindent It would be tolerable to send all these responses undifferentiated with a @code{200 HTTP_OK} status code but in order to improve the @code{HTTP} conformance of our server a bit, we extend the @code{send_page} function so that it accepts individual status codes. @verbatim static int send_page (struct MHD_Connection *connection, const char* page, int status_code) { int ret; struct MHD_Response *response; response = MHD_create_response_from_buffer (strlen (page), (void*) page, MHD_RESPMEM_MUST_COPY); if (!response) return MHD_NO; ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent Note how we ask @emph{MHD} to make its own copy of the message data. The reason behind this will become clear later. @heading Connection cycle The decision whether the server is busy or not is made right at the beginning of the connection. To do that at this stage is especially important for @emph{POST} requests because if no response is queued at this point, and @code{MHD_YES} returned, @emph{MHD} will not sent any queued messages until a postprocessor has been created and the post iterator is called at least once. @verbatim static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (NULL == *req_cls) { struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page(connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); @end verbatim @noindent If the server is not busy, the @code{connection_info} structure is initialized as usual, with the addition of a filepointer for each connection. @verbatim con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->fp = 0; if (0 == strcmp (method, "POST")) { ... } else con_info->connectiontype = GET; *req_cls = (void*) con_info; return MHD_YES; } @end verbatim @noindent For @emph{POST} requests, the postprocessor is created and we register a new uploading client. From this point on, there are many possible places for errors to occur that make it necessary to interrupt the uploading process. We need a means of having the proper response message ready at all times. Therefore, the @code{connection_info} structure is extended to hold the most current response message so that whenever a response is sent, the client will get the most informative message. Here, the structure is initialized to "no error". @verbatim if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; con_info->answercode = MHD_HTTP_OK; con_info->answerstring = completepage; } else con_info->connectiontype = GET; @end verbatim @noindent If the connection handler is called for the second time, @emph{GET} requests will be answered with the @emph{form}. We can keep the buffer under function scope, because we asked @emph{MHD} to make its own copy of it for as long as it is needed. @verbatim if (0 == strcmp (method, "GET")) { int ret; char buffer[1024]; sprintf (buffer, askpage, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } @end verbatim @noindent The rest of the @code{answer_to_connection} function is very similar to the @code{simplepost.c} example, except the more flexible content of the responses. The @emph{POST} data is processed until there is none left and the execution falls through to return an error page if the connection constituted no expected request method. @verbatim if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else return send_page (connection, con_info->answerstring, con_info->answercode); } return send_page(connection, errorpage, MHD_HTTP_BAD_REQUEST); } @end verbatim @noindent @heading Storing to data Unlike the @code{simplepost.c} example, here it is to be expected that post iterator will be called several times now. This means that for any given connection (there might be several concurrent of them) the posted data has to be written to the correct file. That is why we store a file handle in every @code{connection_info}, so that the it is preserved between successive iterations. @verbatim static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; @end verbatim @noindent Because the following actions depend heavily on correct file processing, which might be error prone, we default to reporting internal errors in case anything will go wrong. @verbatim con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; @end verbatim @noindent In the "askpage" @emph{form}, we told the client to label its post data with the "file" key. Anything else would be an error. @verbatim if (0 != strcmp (key, "file")) return MHD_NO; @end verbatim @noindent If the iterator is called for the first time, no file will have been opened yet. The @code{filename} string contains the name of the file (without any paths) the user selected on his system. We want to take this as the name the file will be stored on the server and make sure no file of that name exists (or is being uploaded) before we create one (note that the code below technically contains a race between the two "fopen" calls, but we will overlook this for portability sake). @verbatim if (!con_info->fp) { if (NULL != (fp = fopen (filename, "rb")) ) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_NO; } con_info->fp = fopen (filename, "ab"); if (!con_info->fp) return MHD_NO; } @end verbatim @noindent Occasionally, the iterator function will be called even when there are 0 new bytes to process. The server only needs to write data to the file if there is some. @verbatim if (size > 0) { if (!fwrite (data, size, sizeof(char), con_info->fp)) return MHD_NO; } @end verbatim @noindent If this point has been reached, everything worked well for this iteration and the response can be set to success again. If the upload has finished, this iterator function will not be called again. @verbatim con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; return MHD_YES; } @end verbatim @noindent The new client was registered when the postprocessor was created. Likewise, we unregister the client on destroying the postprocessor when the request is completed. @verbatim void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } @end verbatim @noindent This is essentially the whole example @code{largepost.c}. @heading Remarks Now that the clients are able to create files on the server, security aspects are becoming even more important than before. Aside from proper client authentication, the server should always make sure explicitly that no files will be created outside of a dedicated upload directory. In particular, filenames must be checked to not contain strings like "../". libmicrohttpd-1.0.2/doc/chapters/processingpost.inc0000644000175000017500000002147014674632555017457 00000000000000The previous chapters already have demonstrated a variety of possibilities to send information to the HTTP server, but it is not recommended that the @emph{GET} method is used to alter the way the server operates. To induce changes on the server, the @emph{POST} method is preferred over and is much more powerful than @emph{GET} and will be introduced in this chapter. We are going to write an application that asks for the visitor's name and, after the user has posted it, composes an individual response text. Even though it was not mandatory to use the @emph{POST} method here, as there is no permanent change caused by the POST, it is an illustrative example on how to share data between different functions for the same connection. Furthermore, the reader should be able to extend it easily. @heading GET request When the first @emph{GET} request arrives, the server shall respond with a HTML page containing an edit field for the name. @verbatim const char* askpage = "\ What's your name, Sir?
    \
    \ \ "; @end verbatim @noindent The @code{action} entry is the @emph{URI} to be called by the browser when posting, and the @code{name} will be used later to be sure it is the editbox's content that has been posted. We also prepare the answer page, where the name is to be filled in later, and an error page as the response for anything but proper @emph{GET} and @emph{POST} requests: @verbatim const char* greatingpage="

    Welcome, %s!

    "; const char* errorpage="This doesn't seem to be right."; @end verbatim @noindent Whenever we need to send a page, we use an extra function @code{int send_page(struct MHD_Connection *connection, const char* page)} for this, which does not contain anything new and whose implementation is therefore not discussed further in the tutorial. @heading POST request Posted data can be of arbitrary and considerable size; for example, if a user uploads a big image to the server. Similar to the case of the header fields, there may also be different streams of posted data, such as one containing the text of an editbox and another the state of a button. Likewise, we will have to register an iterator function that is going to be called maybe several times not only if there are different POSTs but also if one POST has only been received partly yet and needs processing before another chunk can be received. Such an iterator function is called by a @emph{postprocessor}, which must be created upon arriving of the post request. We want the iterator function to read the first post data which is tagged @code{name} and to create an individual greeting string based on the template and the name. But in order to pass this string to other functions and still be able to differentiate different connections, we must first define a structure to share the information, holding the most import entries. @verbatim struct connection_info_struct { int connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; @end verbatim @noindent With these information available to the iterator function, it is able to fulfill its task. Once it has composed the greeting string, it returns @code{MHD_NO} to inform the post processor that it does not need to be called again. Note that this function does not handle processing of data for the same @code{key}. If we were to expect that the name will be posted in several chunks, we had to expand the namestring dynamically as additional parts of it with the same @code{key} came in. But in this example, the name is assumed to fit entirely inside one single packet. @verbatim static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; if (0 == strcmp (key, "name")) { if ((size > 0) && (size <= MAXNAMESIZE)) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (!answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, greatingpage, data); con_info->answerstring = answerstring; } else con_info->answerstring = NULL; return MHD_NO; } return MHD_YES; } @end verbatim @noindent Once a connection has been established, it can be terminated for many reasons. As these reasons include unexpected events, we have to register another function that cleans up any resources that might have been allocated for that connection by us, namely the post processor and the greetings string. This cleanup function must take into account that it will also be called for finished requests other than @emph{POST} requests. @verbatim void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } @end verbatim @noindent @emph{GNU libmicrohttpd} is informed that it shall call the above function when the daemon is started in the main function. @verbatim ... daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); ... @end verbatim @noindent @heading Request handling With all other functions prepared, we can now discuss the actual request handling. On the first iteration for a new request, we start by allocating a new instance of a @code{struct connection_info_struct} structure, which will store all necessary information for later iterations and other functions. @verbatim static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if(NULL == *req_cls) { struct connection_info_struct *con_info; con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; @end verbatim @noindent If the new request is a @emph{POST}, the postprocessor must be created now. In addition, the type of the request is stored for convenience. @verbatim if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else con_info->connectiontype = GET; @end verbatim @noindent The address of our structure will both serve as the indicator for successive iterations and to remember the particular details about the connection. @verbatim *req_cls = (void*) con_info; return MHD_YES; } @end verbatim @noindent The rest of the function will not be executed on the first iteration. A @emph{GET} request is easily satisfied by sending the question form. @verbatim if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } @end verbatim @noindent In case of @emph{POST}, we invoke the post processor for as long as data keeps incoming, setting @code{*upload_data_size} to zero in order to indicate that we have processed---or at least have considered---all of it. @verbatim if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (*upload_data_size != 0) { MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } @end verbatim @noindent Finally, if they are neither @emph{GET} nor @emph{POST} requests, the error page is returned. @verbatim return send_page(connection, errorpage); } @end verbatim @noindent These were the important parts of the program @code{simplepost.c}. libmicrohttpd-1.0.2/doc/chapters/bibliography.inc0000644000175000017500000000220414674632555017042 00000000000000@heading API reference @itemize @bullet @item The @emph{GNU libmicrohttpd} manual by Marco Maggi and Christian Grothoff 2008 @uref{http://gnunet.org/libmicrohttpd/microhttpd.html} @item All referenced RFCs can be found on the website of @emph{The Internet Engineering Task Force} @uref{http://www.ietf.org/} @item @emph{RFC 2616}: Fielding, R., Gettys, J., Mogul, J., Frystyk, H., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", RFC 2016, January 1997. @item @emph{RFC 2617}: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", RFC 2617, June 1999. @item @emph{RFC 6455}: Fette, I., Melnikov, A., "The WebSocket Protocol", RFC 6455, December 2011. @item A well--structured @emph{HTML} reference can be found on @uref{http://www.echoecho.com/html.htm} For those readers understanding German or French, there is an excellent document both for learning @emph{HTML} and for reference, whose English version unfortunately has been discontinued. @uref{http://de.selfhtml.org/} and @uref{http://fr.selfhtml.org/} @end itemize libmicrohttpd-1.0.2/doc/doxygen/0000755000175000017500000000000015035216653013607 500000000000000libmicrohttpd-1.0.2/doc/doxygen/libmicrohttpd.doxy.in0000644000175000017500000032217414674632555017731 00000000000000# Doxyfile 1.8.13 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all text # before the first occurrence of this tag. Doxygen uses libiconv (or the iconv # built into libc) for the transcoding. See http://www.gnu.org/software/libiconv # for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = "GNU libmicrohttpd" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = @PACKAGE_VERSION@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = . # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and # will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. # The default value is: NO. CREATE_SUBDIRS = YES # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. ALLOW_UNICODE_NAMES = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, # Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, # Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, # Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, # Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = YES # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = ../.. # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = ../../src/include \ src/include # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = NO # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:\n" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, # C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: # FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: # Fortran. In the later case the parser tries to guess whether the code is fixed # or free formatted code, this is the default for Fortran type files), VHDL. For # instance to make doxygen treat .inc files as Fortran files (default is PHP), # and .f files as C (default is Fortran), use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = YES # When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up # to that level are automatically included in the table of contents, even if # they do not have an id attribute. # Note: This feature currently applies only to Markdown headings. # Minimum value: 0, maximum value: 99, default value: 0. # This tag requires that the tag MARKDOWN_SUPPORT is set to YES. TOC_INCLUDE_HEADINGS = 0 # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = NO # If one adds a struct or class to a group and this option is enabled, then also # any nested class or struct is added to the same group. By default this option # is disabled and one has to add nested compounds explicitly via \ingroup. # The default value is: NO. GROUP_NESTED_COMPOUNDS = NO # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = YES # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # (class|struct|union) declarations. If set to NO, these declarations will be # included in the documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. # The default value is: system dependent. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = NO # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. HIDE_COMPOUND_REFERENCE= NO # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = YES # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = NO # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = NO # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= NO # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if ... \endif and \cond # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = YES # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong or incomplete # parameter documentation, but not about the absence of documentation. # The default value is: NO. WARN_NO_PARAMDOC = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. # The default value is: NO. WARN_AS_ERROR = NO # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. INPUT = ../.. # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: http://www.gnu.org/software/libiconv) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, # *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. FILE_PATTERNS = *.c \ *.h # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = */test_* \ */.svn/* \ */perf_* \ */tls_test_* \ */examples/* \ */testcurl/* \ */testzzuf/* \ */platform/* \ */symbian/* \ MHD_config.h \ microhttpd2.h # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = MHD_DLOG # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # # # where is the value of the INPUT_FILTER tag, and is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # function all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = YES # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = YES # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see http://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the config file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = NO # If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the # clang parser (see: http://clang.llvm.org/) for more accurate parsing at the # cost of reduced performance. This can be particularly helpful with template # rich C++ code for which doxygen's built-in parser lacks the necessary type # information. # Note: The availability of this option depends on whether or not doxygen was # generated with the -Duse-libclang=ON option for CMake. # The default value is: NO. CLANG_ASSISTED_PARSING = NO # If clang assisted parsing is enabled you can provide the compiler with command # line options that you would normally use when invoking the compiler. Note that # the include paths will already be set by doxygen for the files and directories # specified with INPUT and INCLUDE_PATH. # This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. CLANG_OPTIONS = #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = YES # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a colorwheel, see # http://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use grayscales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: http://developer.apple.com/tools/xcode/), introduced with # OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a # Makefile in the HTML output directory. Running make will produce the docset in # that directory and running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- # folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine-tune the look of the index. As an example, the default style # sheet generated by doxygen has an example that shows how to put an image at # the root of the tree instead of the PROJECT_NAME. Since the tree basically has # the same information as the tab index, you could consider setting # DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # http://www.mathjax.org) which uses client side Javascript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from http://www.mathjax.org before deployment. # The default value is: http://cdn.mathjax.org/mathjax/latest. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use + S # (what the is depends on the OS and browser, but it is typically # , /