response.c (77851B)
1 /* 2 This file is part of libmicrohttpd 3 Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff 4 Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) 5 6 This library is free software; you can redistribute it and/or 7 modify it under the terms of the GNU Lesser General Public 8 License as published by the Free Software Foundation; either 9 version 2.1 of the License, or (at your option) any later version. 10 11 This library is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 Lesser General Public License for more details. 15 16 You should have received a copy of the GNU Lesser General Public 17 License along with this library; if not, write to the Free Software 18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 19 */ 20 /** 21 * @file response.c 22 * @brief Methods for managing response objects 23 * @author Daniel Pittman 24 * @author Christian Grothoff 25 * @author Karlson2k (Evgeny Grin) 26 */ 27 28 #define MHD_NO_DEPRECATION 1 29 30 #include "mhd_options.h" 31 #ifdef HAVE_SYS_IOCTL_H 32 #include <sys/ioctl.h> 33 #endif /* HAVE_SYS_IOCTL_H */ 34 #if defined(_WIN32) && ! defined(__CYGWIN__) 35 #include <windows.h> 36 #endif /* _WIN32 && !__CYGWIN__ */ 37 38 #include "internal.h" 39 #include "response.h" 40 #include "mhd_limits.h" 41 #include "mhd_sockets.h" 42 #include "mhd_itc.h" 43 #include "mhd_str.h" 44 #include "connection.h" 45 #include "memorypool.h" 46 #include "mhd_send.h" 47 #include "mhd_compat.h" 48 #include "mhd_assert.h" 49 50 51 #if defined(MHD_W32_MUTEX_) 52 #ifndef WIN32_LEAN_AND_MEAN 53 #define WIN32_LEAN_AND_MEAN 1 54 #endif /* !WIN32_LEAN_AND_MEAN */ 55 #include <windows.h> 56 #endif /* MHD_W32_MUTEX_ */ 57 #if defined(_WIN32) 58 #include <io.h> /* for lseek(), read() */ 59 #endif /* _WIN32 */ 60 61 62 /** 63 * Size of single file read operation for 64 * file-backed responses. 65 */ 66 #ifndef MHD_FILE_READ_BLOCK_SIZE 67 #ifdef _WIN32 68 #define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */ 69 #else /* _WIN32 */ 70 #define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */ 71 #endif /* _WIN32 */ 72 #endif /* !MHD_FD_BLOCK_SIZE */ 73 74 /** 75 * Insert a new header at the first position of the response 76 */ 77 #define _MHD_insert_header_first(presponse, phdr) do { \ 78 mhd_assert (NULL == phdr->next); \ 79 mhd_assert (NULL == phdr->prev); \ 80 if (NULL == presponse->first_header) \ 81 { \ 82 mhd_assert (NULL == presponse->last_header); \ 83 presponse->first_header = phdr; \ 84 presponse->last_header = phdr; \ 85 } \ 86 else \ 87 { \ 88 mhd_assert (NULL != presponse->last_header); \ 89 presponse->first_header->prev = phdr; \ 90 phdr->next = presponse->first_header; \ 91 presponse->first_header = phdr; \ 92 } \ 93 } while (0) 94 95 /** 96 * Insert a new header at the last position of the response 97 */ 98 #define _MHD_insert_header_last(presponse, phdr) do { \ 99 mhd_assert (NULL == phdr->next); \ 100 mhd_assert (NULL == phdr->prev); \ 101 if (NULL == presponse->last_header) \ 102 { \ 103 mhd_assert (NULL == presponse->first_header); \ 104 presponse->last_header = phdr; \ 105 presponse->first_header = phdr; \ 106 } \ 107 else \ 108 { \ 109 mhd_assert (NULL != presponse->first_header); \ 110 presponse->last_header->next = phdr; \ 111 phdr->prev = presponse->last_header; \ 112 presponse->last_header = phdr; \ 113 } \ 114 } while (0) 115 116 117 /** 118 * Remove a header from the response 119 */ 120 #define _MHD_remove_header(presponse, phdr) do { \ 121 mhd_assert (NULL != presponse->first_header); \ 122 mhd_assert (NULL != presponse->last_header); \ 123 if (NULL == phdr->prev) \ 124 { \ 125 mhd_assert (phdr == presponse->first_header); \ 126 presponse->first_header = phdr->next; \ 127 } \ 128 else \ 129 { \ 130 mhd_assert (phdr != presponse->first_header); \ 131 mhd_assert (phdr == phdr->prev->next); \ 132 phdr->prev->next = phdr->next; \ 133 } \ 134 if (NULL == phdr->next) \ 135 { \ 136 mhd_assert (phdr == presponse->last_header); \ 137 presponse->last_header = phdr->prev; \ 138 } \ 139 else \ 140 { \ 141 mhd_assert (phdr != presponse->last_header); \ 142 mhd_assert (phdr == phdr->next->prev); \ 143 phdr->next->prev = phdr->prev; \ 144 } \ 145 } while (0) 146 147 /** 148 * Add preallocated strings a header or footer line to the response without 149 * checking. 150 * 151 * Header/footer strings are not checked and assumed to be correct. 152 * 153 * The string must not be statically allocated! 154 * The strings must be malloc()'ed and zero terminated. The strings will 155 * be free()'ed when the response is destroyed. 156 * 157 * @param response response to add a header to 158 * @param kind header or footer 159 * @param name the header name string to add, must be malloc()'ed and 160 * zero-terminated 161 * @param name_len the length of the @a name 162 * @param value the header value string to add, must be malloc()'ed and 163 * zero-terminated 164 * @param value_len the length of the @a value 165 */ 166 bool 167 MHD_add_response_entry_no_alloc_ (struct MHD_Response *response, 168 enum MHD_ValueKind kind, 169 char *name, 170 size_t name_len, 171 char *value, 172 size_t value_len) 173 { 174 struct MHD_HTTP_Res_Header *hdr; 175 176 mhd_assert (0 != name_len); 177 if (NULL == (hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)))) 178 return false; 179 180 hdr->header = name; 181 hdr->header_size = name_len; 182 hdr->value = value; 183 hdr->value_size = value_len; 184 hdr->kind = kind; 185 _MHD_insert_header_last (response, hdr); 186 187 return true; /* Success exit point */ 188 } 189 190 191 /** 192 * Add a header or footer line to the response without checking. 193 * 194 * It is assumed that parameters are correct. 195 * 196 * @param response response to add a header to 197 * @param kind header or footer 198 * @param name the header name to add, does not need to be zero-terminated 199 * @param name_len the length of the @a name 200 * @param value the header value to add, does not need to be zero-terminated 201 * @param value_len the length of the @a value 202 * @return false on error (like out-of-memory), 203 * true if succeed 204 */ 205 bool 206 MHD_add_response_entry_no_check_ (struct MHD_Response *response, 207 enum MHD_ValueKind kind, 208 const char *name, 209 size_t name_len, 210 const char *value, 211 size_t value_len) 212 { 213 char *name_malloced; 214 char *value_malloced; 215 216 mhd_assert (0 != name_len); 217 name_malloced = malloc (name_len + 1); 218 if (NULL == name_malloced) 219 return false; 220 221 memcpy (name_malloced, name, name_len); 222 name_malloced[name_len] = 0; 223 224 value_malloced = malloc (value_len + 1); 225 if (NULL != value_malloced) 226 { 227 memcpy (value_malloced, value, value_len); 228 value_malloced[value_len] = 0; 229 230 if (MHD_add_response_entry_no_alloc_ (response, kind, 231 name_malloced, name_len, 232 value_malloced, value_len)) 233 return true; /* Success exit point */ 234 235 free (value_malloced); 236 } 237 free (name_malloced); 238 239 return false; /* Failure exit point */ 240 } 241 242 243 /** 244 * Add a header or footer line to the response. 245 * 246 * @param name the header name to add, does not need to be zero-terminated 247 * @param name_len the length of the @a name 248 * @param value the header value to add, does not need to be zero-terminated 249 * @param value_len the length of the @a value 250 * @return false on error (out-of-memory, invalid name or value), 251 * true if succeed 252 */ 253 static bool 254 add_response_entry_n (struct MHD_Response *response, 255 enum MHD_ValueKind kind, 256 const char *name, 257 size_t name_len, 258 const char *value, 259 size_t value_len) 260 { 261 if (NULL == response) 262 return false; 263 if (0 == name_len) 264 return false; 265 if (NULL != memchr (name, '\t', name_len)) 266 return false; 267 if (NULL != memchr (name, ' ', name_len)) 268 return false; 269 if (NULL != memchr (name, ':', name_len)) 270 return false; 271 if (NULL != memchr (name, '\r', name_len)) 272 return false; 273 if (NULL != memchr (name, '\n', name_len)) 274 return false; 275 if (NULL != memchr (value, '\r', value_len)) 276 return false; 277 if (NULL != memchr (value, '\n', value_len)) 278 return false; 279 280 return MHD_add_response_entry_no_check_ (response, kind, name, name_len, 281 value, value_len); 282 } 283 284 285 /** 286 * Add a header or footer line to the response. 287 * 288 * @param response response to add a header to 289 * @param kind header or footer 290 * @param name the header name to add 291 * @param value the header value to add 292 * @return #MHD_NO on error (i.e. invalid name or value format). 293 */ 294 static enum MHD_Result 295 add_response_entry (struct MHD_Response *response, 296 enum MHD_ValueKind kind, 297 const char *name, 298 const char *value) 299 { 300 size_t name_len; 301 size_t value_len; 302 303 name_len = strlen (name); 304 value_len = strlen (value); 305 return add_response_entry_n (response, kind, name, 306 name_len, value, 307 value_len) ? MHD_YES : MHD_NO; 308 } 309 310 311 /** 312 * Add "Connection:" header to the response with special processing. 313 * 314 * "Connection:" header value will be combined with any existing "Connection:" 315 * header, "close" token (if any) will be de-duplicated and moved to the first 316 * position. 317 * 318 * @param response the response to add a header to 319 * @param value the value to add 320 * @return #MHD_NO on error (no memory). 321 */ 322 static enum MHD_Result 323 add_response_header_connection (struct MHD_Response *response, 324 const char *value) 325 { 326 static const char *key = MHD_HTTP_HEADER_CONNECTION; 327 /** the length of the "Connection" key */ 328 static const size_t key_len = 329 MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION); 330 size_t value_len; /**< the length of the @a value */ 331 size_t old_value_len; /**< the length of the existing "Connection" value */ 332 size_t buf_size; /**< the size of the buffer */ 333 size_t norm_len; /**< the length of the normalised value */ 334 char *buf; /**< the temporal buffer */ 335 struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ 336 bool value_has_close; /**< the @a value has "close" token */ 337 bool already_has_close; /**< existing "Connection" header has "close" token */ 338 size_t pos = 0; /**< position of addition in the @a buf */ 339 340 if ( (NULL != strchr (value, '\r')) || 341 (NULL != strchr (value, '\n')) ) 342 return MHD_NO; 343 344 if (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) 345 { 346 hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, 347 key, key_len); 348 already_has_close = 349 (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); 350 mhd_assert (NULL != hdr); 351 mhd_assert (already_has_close == (0 == memcmp (hdr->value, "close", 5))); 352 } 353 else 354 { 355 hdr = NULL; 356 already_has_close = false; 357 mhd_assert (NULL == MHD_get_response_element_n_ (response, 358 MHD_HEADER_KIND, 359 key, key_len)); 360 mhd_assert (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); 361 } 362 if (NULL != hdr) 363 old_value_len = hdr->value_size + 2; /* additional size for ", " */ 364 else 365 old_value_len = 0; 366 367 value_len = strlen (value); 368 if (value_len >= SSIZE_MAX) 369 return MHD_NO; 370 /* Additional space for normalisation and zero-termination */ 371 norm_len = value_len + value_len / 2 + 1; 372 if (norm_len >= SSIZE_MAX) 373 return MHD_NO; 374 buf_size = old_value_len + (size_t) norm_len; 375 376 buf = malloc (buf_size); 377 if (NULL == buf) 378 return MHD_NO; 379 if (1) 380 { /* local scope */ 381 ssize_t norm_len_s = (ssize_t) norm_len; 382 /* Remove "close" token (if any), it will be moved to the front */ 383 value_has_close = MHD_str_remove_token_caseless_ (value, value_len, "close", 384 MHD_STATICSTR_LEN_ ( \ 385 "close"), 386 buf + old_value_len, 387 &norm_len_s); 388 mhd_assert (0 <= norm_len_s); 389 if (0 > norm_len_s) 390 { 391 /* Must never happen with realistic sizes */ 392 free (buf); 393 return MHD_NO; 394 } 395 else 396 norm_len = (size_t) norm_len_s; 397 } 398 #ifdef UPGRADE_SUPPORT 399 if ( (NULL != response->upgrade_handler) && value_has_close) 400 { /* The "close" token cannot be used with connection "upgrade" */ 401 free (buf); 402 return MHD_NO; 403 } 404 #endif /* UPGRADE_SUPPORT */ 405 if (0 != norm_len) 406 MHD_str_remove_tokens_caseless_ (buf + old_value_len, &norm_len, 407 "keep-alive", 408 MHD_STATICSTR_LEN_ ("keep-alive")); 409 if (0 == norm_len) 410 { /* New value is empty after normalisation */ 411 if (! value_has_close) 412 { /* The new value had no tokens */ 413 free (buf); 414 return MHD_NO; 415 } 416 if (already_has_close) 417 { /* The "close" token is already present, nothing to modify */ 418 free (buf); 419 return MHD_YES; 420 } 421 } 422 /* Add "close" token if required */ 423 if (value_has_close && ! already_has_close) 424 { 425 /* Need to insert "close" token at the first position */ 426 mhd_assert (buf_size >= old_value_len + norm_len \ 427 + MHD_STATICSTR_LEN_ ("close, ") + 1); 428 if (0 != norm_len) 429 memmove (buf + MHD_STATICSTR_LEN_ ("close, ") + old_value_len, 430 buf + old_value_len, norm_len + 1); 431 memcpy (buf, "close", MHD_STATICSTR_LEN_ ("close")); 432 pos += MHD_STATICSTR_LEN_ ("close"); 433 } 434 /* Add old value tokens (if any) */ 435 if (0 != old_value_len) 436 { 437 if (0 != pos) 438 { 439 buf[pos++] = ','; 440 buf[pos++] = ' '; 441 } 442 memcpy (buf + pos, hdr->value, 443 hdr->value_size); 444 pos += hdr->value_size; 445 } 446 /* Add new value token (if any) */ 447 if (0 != norm_len) 448 { 449 if (0 != pos) 450 { 451 buf[pos++] = ','; 452 buf[pos++] = ' '; 453 } 454 /* The new value tokens must be already at the correct position */ 455 mhd_assert ((value_has_close && ! already_has_close) ? \ 456 (MHD_STATICSTR_LEN_ ("close, ") + old_value_len == pos) : \ 457 (old_value_len == pos)); 458 pos += norm_len; 459 } 460 mhd_assert (buf_size > pos); 461 buf[pos] = 0; /* Null terminate the result */ 462 463 if (NULL == hdr) 464 { 465 struct MHD_HTTP_Res_Header *new_hdr; /**< new "Connection" header */ 466 /* Create new response header entry */ 467 new_hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)); 468 if (NULL != new_hdr) 469 { 470 new_hdr->header = malloc (key_len + 1); 471 if (NULL != new_hdr->header) 472 { 473 memcpy (new_hdr->header, key, key_len + 1); 474 new_hdr->header_size = key_len; 475 new_hdr->value = buf; 476 new_hdr->value_size = pos; 477 new_hdr->kind = MHD_HEADER_KIND; 478 if (value_has_close) 479 response->flags_auto = (MHD_RAF_HAS_CONNECTION_HDR 480 | MHD_RAF_HAS_CONNECTION_CLOSE); 481 else 482 response->flags_auto = MHD_RAF_HAS_CONNECTION_HDR; 483 _MHD_insert_header_first (response, new_hdr); 484 return MHD_YES; 485 } 486 free (new_hdr); 487 } 488 free (buf); 489 return MHD_NO; 490 } 491 492 /* Update existing header entry */ 493 free (hdr->value); 494 hdr->value = buf; 495 hdr->value_size = pos; 496 if (value_has_close && ! already_has_close) 497 response->flags_auto |= MHD_RAF_HAS_CONNECTION_CLOSE; 498 return MHD_YES; 499 } 500 501 502 /** 503 * Remove tokens from "Connection:" header of the response. 504 * 505 * Provided tokens will be removed from "Connection:" header value. 506 * 507 * @param response the response to manipulate "Connection:" header 508 * @param value the tokens to remove 509 * @return #MHD_NO on error (no headers or tokens found). 510 */ 511 static enum MHD_Result 512 del_response_header_connection (struct MHD_Response *response, 513 const char *value) 514 { 515 struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ 516 517 hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, 518 MHD_HTTP_HEADER_CONNECTION, 519 MHD_STATICSTR_LEN_ ( \ 520 MHD_HTTP_HEADER_CONNECTION)); 521 if (NULL == hdr) 522 return MHD_NO; 523 524 if (! MHD_str_remove_tokens_caseless_ (hdr->value, 525 &hdr->value_size, 526 value, 527 strlen (value))) 528 return MHD_NO; 529 if (0 == hdr->value_size) 530 { 531 _MHD_remove_header (response, hdr); 532 free (hdr->value); 533 free (hdr->header); 534 free (hdr); 535 response->flags_auto &= 536 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_HDR 537 | (enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); 538 } 539 else 540 { 541 hdr->value[hdr->value_size] = 0; /* Null-terminate the result */ 542 if (0 != (response->flags_auto 543 & ((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE))) 544 { 545 if (MHD_STATICSTR_LEN_ ("close") == hdr->value_size) 546 { 547 if (0 != memcmp (hdr->value, 548 "close", 549 MHD_STATICSTR_LEN_ ("close"))) 550 response->flags_auto &= 551 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); 552 } 553 else if (MHD_STATICSTR_LEN_ ("close, ") < hdr->value_size) 554 { 555 if (0 != memcmp (hdr->value, "close, ", 556 MHD_STATICSTR_LEN_ ("close, "))) 557 response->flags_auto &= 558 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); 559 } 560 else 561 response->flags_auto &= 562 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); 563 } 564 } 565 return MHD_YES; 566 } 567 568 569 /** 570 * Add a header line to the response. 571 * 572 * The strings @a header and @a content are copied to the response. 573 * 574 * When reply is generated with queued response, some headers are generated 575 * automatically. Automatically generated headers are only sent to the client, 576 * but not added back to the response object. 577 * 578 * The list of automatic headers: 579 * + "Date" header is added automatically unless already set by 580 * this function 581 * @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK 582 * + "Content-Length" is added automatically when required, attempt to set 583 * it manually by this function is ignored. 584 * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH 585 * + "Transfer-Encoding" with value "chunked" is added automatically, 586 * when chunked transfer encoding is used automatically. Same header with 587 * the same value can be set manually by this function to enforce chunked 588 * encoding, however for HTTP/1.0 clients chunked encoding will not be used 589 * and manually set "Transfer-Encoding" header is automatically removed 590 * for HTTP/1.0 clients 591 * + "Connection" may be added automatically with value "Keep-Alive" (only 592 * for HTTP/1.0 clients) or "Close". The header "Connection" with value 593 * "Close" could be set by this function to enforce closure of 594 * the connection after sending this response. "Keep-Alive" cannot be 595 * enforced and will be removed automatically. 596 * @see #MHD_RF_SEND_KEEP_ALIVE_HEADER 597 * 598 * Some headers are pre-processed by this function: 599 * * "Connection" headers are combined into single header entry, value is 600 * normilised, "Keep-Alive" tokens are removed. 601 * * "Transfer-Encoding" header: the only one header is allowed, the only 602 * allowed value is "chunked". 603 * * "Date" header: the only one header is allowed, the second added header 604 * replaces the first one. 605 * * "Content-Length" application-defined header is not allowed. 606 * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH 607 * 608 * Empty value is not accepted for these pre-processed headers. 609 * 610 * Headers are used in order as they were added. 611 * 612 * @param response the response to add a header to 613 * @param header the header name to add 614 * @param content the header value to add, can be an empty string 615 * @return #MHD_YES on success, 616 * #MHD_NO on error (i.e. invalid header or content format), 617 * or out of memory 618 * @ingroup response 619 */ 620 _MHD_EXTERN enum MHD_Result 621 MHD_add_response_header (struct MHD_Response *response, 622 const char *header, 623 const char *content) 624 { 625 if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONNECTION)) 626 return add_response_header_connection (response, content); 627 628 if (MHD_str_equal_caseless_ (header, 629 MHD_HTTP_HEADER_TRANSFER_ENCODING)) 630 { 631 if (! MHD_str_equal_caseless_ (content, "chunked")) 632 return MHD_NO; /* Only "chunked" encoding is allowed */ 633 if (0 != (response->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) 634 return MHD_YES; /* Already has "chunked" encoding header */ 635 if ( (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) && 636 (0 == (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) ) 637 return MHD_NO; /* Has "Content-Length" header and no "Insanity" flag */ 638 if (MHD_NO != add_response_entry (response, 639 MHD_HEADER_KIND, 640 header, 641 content)) 642 { 643 response->flags_auto |= MHD_RAF_HAS_TRANS_ENC_CHUNKED; 644 return MHD_YES; 645 } 646 return MHD_NO; 647 } 648 if (MHD_str_equal_caseless_ (header, 649 MHD_HTTP_HEADER_DATE)) 650 { 651 struct MHD_HTTP_Res_Header *old_hdr; 652 653 /* The value is HTTP-date and cannot be empty. 654 See RFC 9110, Section 6.6.1 */ 655 if ('\0' == content[0]) 656 return MHD_NO; 657 658 old_hdr = NULL; 659 if (0 != (response->flags_auto & MHD_RAF_HAS_DATE_HDR)) 660 { 661 old_hdr = 662 MHD_get_response_element_n_ (response, MHD_HEADER_KIND, 663 MHD_HTTP_HEADER_DATE, 664 MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_DATE)); 665 mhd_assert (NULL != old_hdr); 666 } 667 668 if (MHD_NO == add_response_entry (response, 669 MHD_HEADER_KIND, 670 header, 671 content)) 672 return MHD_NO; 673 674 response->flags_auto |= MHD_RAF_HAS_DATE_HDR; 675 676 if (NULL != old_hdr) 677 { 678 _MHD_remove_header (response, old_hdr); 679 if (NULL != old_hdr->value) 680 free (old_hdr->value); 681 free (old_hdr->header); 682 free (old_hdr); 683 } 684 return MHD_YES; 685 } 686 687 if (MHD_str_equal_caseless_ (header, 688 MHD_HTTP_HEADER_CONTENT_LENGTH)) 689 { 690 /* Generally MHD sets automatically correct "Content-Length" always when 691 * needed. 692 * Custom "Content-Length" header is allowed only in special cases. */ 693 if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) || 694 ((0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) && 695 (0 == (response->flags_auto & (MHD_RAF_HAS_TRANS_ENC_CHUNKED 696 | MHD_RAF_HAS_CONTENT_LENGTH)))) ) 697 { 698 /* The value is 1*DIGIT and cannot be empty. 699 See RFC 9110, Section 8.6 */ 700 if ('\0' == content[0]) 701 return MHD_NO; 702 if (MHD_NO != add_response_entry (response, 703 MHD_HEADER_KIND, 704 header, 705 content)) 706 { 707 response->flags_auto |= MHD_RAF_HAS_CONTENT_LENGTH; 708 return MHD_YES; 709 } 710 } 711 return MHD_NO; 712 } 713 714 return add_response_entry (response, 715 MHD_HEADER_KIND, 716 header, 717 content); 718 } 719 720 721 /** 722 * Add a footer line to the response. 723 * 724 * The strings @a footer and @a content are copied to the response. 725 * 726 * @param response the response to add the footer to 727 * @param footer the footer name to add 728 * @param content the footer value to add, can be an empty string 729 * @return #MHD_NO on error (i.e. invalid footer or content format). 730 * @ingroup response 731 */ 732 _MHD_EXTERN enum MHD_Result 733 MHD_add_response_footer (struct MHD_Response *response, 734 const char *footer, 735 const char *content) 736 { 737 return add_response_entry (response, 738 MHD_FOOTER_KIND, 739 footer, 740 content); 741 } 742 743 744 /** 745 * Delete a header (or footer) line from the response. 746 * 747 * For a "Connection" header, @a content lists the tokens to remove. 748 * The header is deleted if no tokens remain. 749 * 750 * @param response the response to remove a header from 751 * @param header the name of the header (or footer) to delete 752 * @param content the value of the header (or footer) to delete 753 * @return #MHD_YES if the header (or footer) or at least one "Connection" 754 * token has been removed, 755 * #MHD_NO if no such header (or footer) or token is found 756 * @ingroup response 757 */ 758 _MHD_EXTERN enum MHD_Result 759 MHD_del_response_header (struct MHD_Response *response, 760 const char *header, 761 const char *content) 762 { 763 struct MHD_HTTP_Res_Header *pos; 764 size_t header_len; 765 size_t content_len; 766 767 header_len = strlen (header); 768 769 if ((0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) && 770 (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION) == header_len) && 771 MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONNECTION, 772 header_len)) 773 return del_response_header_connection (response, content); 774 775 content_len = strlen (content); 776 pos = response->first_header; 777 while (NULL != pos) 778 { 779 if ((header_len == pos->header_size) && 780 (content_len == pos->value_size) && 781 (0 == memcmp (header, 782 pos->header, 783 header_len)) && 784 (0 == memcmp (content, 785 pos->value, 786 content_len))) 787 { 788 _MHD_remove_header (response, pos); 789 if (MHD_HEADER_KIND == pos->kind) 790 { 791 if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) == 792 header_len) && 793 MHD_str_equal_caseless_bin_n_ (header, 794 MHD_HTTP_HEADER_TRANSFER_ENCODING, 795 header_len) ) 796 response->flags_auto &= 797 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_TRANS_ENC_CHUNKED); 798 else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_DATE) == 799 header_len) && 800 MHD_str_equal_caseless_bin_n_ (header, 801 MHD_HTTP_HEADER_DATE, 802 header_len) ) 803 response->flags_auto &= 804 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_DATE_HDR); 805 else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) == 806 header_len) && 807 MHD_str_equal_caseless_bin_n_ ( 808 header, 809 MHD_HTTP_HEADER_CONTENT_LENGTH, 810 header_len) ) 811 { 812 if (NULL 813 == MHD_get_response_element_n_ (response, 814 MHD_HEADER_KIND, 815 MHD_HTTP_HEADER_CONTENT_LENGTH, 816 header_len)) 817 response->flags_auto &= 818 ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONTENT_LENGTH); 819 } 820 } 821 free (pos->header); 822 free (pos->value); 823 free (pos); 824 return MHD_YES; 825 } 826 pos = pos->next; 827 } 828 return MHD_NO; 829 } 830 831 832 /** 833 * Get all of the headers (and footers) added to a response. 834 * 835 * @param response response to query 836 * @param iterator callback to call on each header; 837 * maybe NULL (then just count headers) 838 * @param iterator_cls extra argument to @a iterator 839 * @return number of entries iterated over 840 * @ingroup response 841 */ 842 _MHD_EXTERN int 843 MHD_get_response_headers (struct MHD_Response *response, 844 MHD_KeyValueIterator iterator, 845 void *iterator_cls) 846 { 847 int numHeaders = 0; 848 struct MHD_HTTP_Res_Header *pos; 849 850 for (pos = response->first_header; 851 NULL != pos; 852 pos = pos->next) 853 { 854 numHeaders++; 855 if ((NULL != iterator) && 856 (MHD_NO == iterator (iterator_cls, 857 pos->kind, 858 pos->header, 859 pos->value))) 860 break; 861 } 862 return numHeaders; 863 } 864 865 866 /** 867 * Get a particular header (or footer) from the response. 868 * 869 * @param response response to query 870 * @param key which header to get 871 * @return NULL if header does not exist 872 * @ingroup response 873 */ 874 _MHD_EXTERN const char * 875 MHD_get_response_header (struct MHD_Response *response, 876 const char *key) 877 { 878 struct MHD_HTTP_Res_Header *pos; 879 size_t key_size; 880 881 if (NULL == key) 882 return NULL; 883 884 key_size = strlen (key); 885 for (pos = response->first_header; 886 NULL != pos; 887 pos = pos->next) 888 { 889 if ((pos->header_size == key_size) && 890 (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) 891 return pos->value; 892 } 893 return NULL; 894 } 895 896 897 /** 898 * Get a particular header (or footer) element from the response. 899 * 900 * Function returns the first found element. 901 * @param response response to query 902 * @param kind the kind of element: header or footer 903 * @param key the key which header to get 904 * @param key_len the length of the @a key 905 * @return NULL if header element does not exist 906 * @ingroup response 907 */ 908 struct MHD_HTTP_Res_Header * 909 MHD_get_response_element_n_ (struct MHD_Response *response, 910 enum MHD_ValueKind kind, 911 const char *key, 912 size_t key_len) 913 { 914 struct MHD_HTTP_Res_Header *pos; 915 916 mhd_assert (NULL != key); 917 mhd_assert (0 != key[0]); 918 mhd_assert (0 != key_len); 919 920 for (pos = response->first_header; 921 NULL != pos; 922 pos = pos->next) 923 { 924 if ((pos->header_size == key_len) && 925 (kind == pos->kind) && 926 (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) 927 return pos; 928 } 929 return NULL; 930 } 931 932 933 /** 934 * Check whether response header contains particular token. 935 * 936 * Token could be surrounded by spaces and tabs and delimited by comma. 937 * Case-insensitive match used for header names and tokens. 938 * 939 * @param response the response to query 940 * @param key header name 941 * @param key_len the length of @a key, not including optional 942 * terminating null-character. 943 * @param token the token to find 944 * @param token_len the length of @a token, not including optional 945 * terminating null-character. 946 * @return true if token is found in specified header, 947 * false otherwise 948 */ 949 bool 950 MHD_check_response_header_token_ci (const struct MHD_Response *response, 951 const char *key, 952 size_t key_len, 953 const char *token, 954 size_t token_len) 955 { 956 struct MHD_HTTP_Res_Header *pos; 957 958 if ( (NULL == key) || 959 ('\0' == key[0]) || 960 (NULL == token) || 961 ('\0' == token[0]) ) 962 return false; 963 964 /* Token must not contain binary zero! */ 965 mhd_assert (strlen (token) == token_len); 966 967 for (pos = response->first_header; 968 NULL != pos; 969 pos = pos->next) 970 { 971 if ( (pos->kind == MHD_HEADER_KIND) && 972 (key_len == pos->header_size) && 973 MHD_str_equal_caseless_bin_n_ (pos->header, 974 key, 975 key_len) && 976 MHD_str_has_token_caseless_ (pos->value, 977 token, 978 token_len) ) 979 return true; 980 } 981 return false; 982 } 983 984 985 /** 986 * Create a response object. 987 * The response object can be extended with header information and then be used 988 * any number of times. 989 * 990 * If response object is used to answer HEAD request then the body of the 991 * response is not used, while all headers (including automatic headers) are 992 * used. 993 * 994 * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown 995 * @param block_size preferred block size for querying crc (advisory only, 996 * MHD may still call @a crc using smaller chunks); this 997 * is essentially the buffer size used for IO, clients 998 * should pick a value that is appropriate for IO and 999 * memory performance requirements 1000 * @param crc callback to use to obtain response data 1001 * @param crc_cls extra argument to @a crc 1002 * @param crfc callback to call to free @a crc_cls resources 1003 * @return NULL on error (i.e. invalid arguments, out of memory) 1004 * @ingroup response 1005 */ 1006 _MHD_EXTERN struct MHD_Response * 1007 MHD_create_response_from_callback (uint64_t size, 1008 size_t block_size, 1009 MHD_ContentReaderCallback crc, 1010 void *crc_cls, 1011 MHD_ContentReaderFreeCallback crfc) 1012 { 1013 struct MHD_Response *response; 1014 1015 if ((NULL == crc) || (0 == block_size)) 1016 return NULL; 1017 if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response) 1018 + block_size))) 1019 return NULL; 1020 response->fd = -1; 1021 response->data = (void *) &response[1]; 1022 response->data_buffer_size = block_size; 1023 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 1024 if (! MHD_mutex_init_ (&response->mutex)) 1025 { 1026 free (response); 1027 return NULL; 1028 } 1029 #endif 1030 response->crc = crc; 1031 response->crfc = crfc; 1032 response->crc_cls = crc_cls; 1033 response->reference_count = 1; 1034 response->total_size = size; 1035 return response; 1036 } 1037 1038 1039 /** 1040 * Set special flags and options for a response. 1041 * 1042 * @param response the response to modify 1043 * @param flags to set for the response 1044 * @param ... #MHD_RO_END terminated list of options 1045 * @return #MHD_YES on success, #MHD_NO on error 1046 */ 1047 _MHD_EXTERN enum MHD_Result 1048 MHD_set_response_options (struct MHD_Response *response, 1049 enum MHD_ResponseFlags flags, 1050 ...) 1051 { 1052 va_list ap; 1053 enum MHD_Result ret; 1054 enum MHD_ResponseOptions ro; 1055 1056 if (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) 1057 { /* Response has custom "Content-Lengh" header */ 1058 if ( (0 != (response->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) && 1059 (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH))) 1060 { /* Request to remove MHD_RF_INSANITY_HEADER_CONTENT_LENGTH flag */ 1061 return MHD_NO; 1062 } 1063 if ( (0 != (response->flags & MHD_RF_HEAD_ONLY_RESPONSE)) && 1064 (0 == (flags & MHD_RF_HEAD_ONLY_RESPONSE))) 1065 { /* Request to remove MHD_RF_HEAD_ONLY_RESPONSE flag */ 1066 if (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) 1067 return MHD_NO; 1068 } 1069 } 1070 1071 if ( (0 != (flags & MHD_RF_HEAD_ONLY_RESPONSE)) && 1072 (0 != response->total_size) ) 1073 return MHD_NO; 1074 1075 ret = MHD_YES; 1076 response->flags = flags; 1077 1078 va_start (ap, flags); 1079 while (MHD_RO_END != (ro = va_arg (ap, enum MHD_ResponseOptions))) 1080 { 1081 switch (ro) 1082 { 1083 case MHD_RO_END: /* Not possible */ 1084 break; 1085 default: 1086 ret = MHD_NO; 1087 break; 1088 } 1089 } 1090 va_end (ap); 1091 return ret; 1092 } 1093 1094 1095 /** 1096 * Given a file descriptor, read data from the file 1097 * to generate the response. 1098 * 1099 * @param cls pointer to the response 1100 * @param pos offset in the file to access 1101 * @param buf where to write the data 1102 * @param max number of bytes to write at most 1103 * @return number of bytes written 1104 */ 1105 static ssize_t 1106 file_reader (void *cls, 1107 uint64_t pos, 1108 char *buf, 1109 size_t max) 1110 { 1111 struct MHD_Response *response = cls; 1112 #if ! defined(_WIN32) || defined(__CYGWIN__) 1113 ssize_t n; 1114 #else /* _WIN32 && !__CYGWIN__ */ 1115 const HANDLE fh = (HANDLE) (uintptr_t) _get_osfhandle (response->fd); 1116 #endif /* _WIN32 && !__CYGWIN__ */ 1117 const int64_t offset64 = (int64_t) (pos + response->fd_off); 1118 1119 if (offset64 < 0) 1120 return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ 1121 1122 #if ! defined(_WIN32) || defined(__CYGWIN__) 1123 if (max > SSIZE_MAX) 1124 max = SSIZE_MAX; /* Clamp to maximum return value. */ 1125 1126 #if defined(HAVE_PREAD64) 1127 n = pread64 (response->fd, buf, max, offset64); 1128 #elif defined(HAVE_PREAD) 1129 if ( (sizeof(off_t) < sizeof (uint64_t)) && 1130 (offset64 > (uint64_t) INT32_MAX) ) 1131 return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */ 1132 1133 n = pread (response->fd, buf, max, (off_t) offset64); 1134 #else /* ! HAVE_PREAD */ 1135 #if defined(HAVE_LSEEK64) 1136 if (lseek64 (response->fd, 1137 offset64, 1138 SEEK_SET) != offset64) 1139 return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ 1140 #else /* ! HAVE_LSEEK64 */ 1141 if ( (sizeof(off_t) < sizeof (uint64_t)) && 1142 (offset64 > (uint64_t) INT32_MAX) ) 1143 return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ 1144 1145 if (lseek (response->fd, 1146 (off_t) offset64, 1147 SEEK_SET) != (off_t) offset64) 1148 return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ 1149 #endif /* ! HAVE_LSEEK64 */ 1150 n = read (response->fd, 1151 buf, 1152 max); 1153 1154 #endif /* ! HAVE_PREAD */ 1155 if (0 == n) 1156 return MHD_CONTENT_READER_END_OF_STREAM; 1157 if (n < 0) 1158 return MHD_CONTENT_READER_END_WITH_ERROR; 1159 return n; 1160 #else /* _WIN32 && !__CYGWIN__ */ 1161 if (INVALID_HANDLE_VALUE == fh) 1162 return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */ 1163 else 1164 { 1165 OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0}; /* Initialize to zero. */ 1166 ULARGE_INTEGER pos_uli; 1167 DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max; 1168 DWORD resRead; 1169 1170 pos_uli.QuadPart = (uint64_t) offset64; /* Simple transformation 64bit -> 2x32bit. */ 1171 f_ol.Offset = pos_uli.LowPart; 1172 f_ol.OffsetHigh = pos_uli.HighPart; 1173 if (! ReadFile (fh, (void *) buf, toRead, &resRead, &f_ol)) 1174 return MHD_CONTENT_READER_END_WITH_ERROR; /* Read error. */ 1175 if (0 == resRead) 1176 return MHD_CONTENT_READER_END_OF_STREAM; 1177 return (ssize_t) resRead; 1178 } 1179 #endif /* _WIN32 && !__CYGWIN__ */ 1180 } 1181 1182 1183 /** 1184 * Given a pipe descriptor, read data from the pipe 1185 * to generate the response. 1186 * 1187 * @param cls pointer to the response 1188 * @param pos offset in the pipe to access (ignored) 1189 * @param buf where to write the data 1190 * @param max number of bytes to write at most 1191 * @return number of bytes written 1192 */ 1193 static ssize_t 1194 pipe_reader (void *cls, 1195 uint64_t pos, 1196 char *buf, 1197 size_t max) 1198 { 1199 struct MHD_Response *response = cls; 1200 ssize_t n; 1201 1202 (void) pos; 1203 1204 #ifndef _WIN32 1205 if (SSIZE_MAX < max) 1206 max = SSIZE_MAX; 1207 n = read (response->fd, 1208 buf, 1209 (MHD_SCKT_SEND_SIZE_) max); 1210 #else /* _WIN32 */ 1211 if (INT_MAX < max) 1212 max = INT_MAX; 1213 n = read (response->fd, 1214 buf, 1215 (unsigned int) max); 1216 #endif /* _WIN32 */ 1217 1218 if (0 == n) 1219 return MHD_CONTENT_READER_END_OF_STREAM; 1220 if (n < 0) 1221 return MHD_CONTENT_READER_END_WITH_ERROR; 1222 return n; 1223 } 1224 1225 1226 /** 1227 * Destroy file reader context. Closes the file 1228 * descriptor. 1229 * 1230 * @param cls pointer to file descriptor 1231 */ 1232 static void 1233 free_callback (void *cls) 1234 { 1235 struct MHD_Response *response = cls; 1236 1237 (void) close (response->fd); 1238 response->fd = -1; 1239 } 1240 1241 1242 #undef MHD_create_response_from_fd_at_offset 1243 1244 /** 1245 * Create a response object with the content of provided file with 1246 * specified offset used as the response body. 1247 * 1248 * The response object can be extended with header information and then 1249 * be used any number of times. 1250 * 1251 * If response object is used to answer HEAD request then the body 1252 * of the response is not used, while all headers (including automatic 1253 * headers) are used. 1254 * 1255 * @param size size of the data portion of the response 1256 * @param fd file descriptor referring to a file on disk with the 1257 * data; will be closed when response is destroyed; 1258 * fd should be in 'blocking' mode 1259 * @param offset offset to start reading from in the file; 1260 * Be careful! `off_t` may have been compiled to be a 1261 * 64-bit variable for MHD, in which case your application 1262 * also has to be compiled using the same options! Read 1263 * the MHD manual for more details. 1264 * @return NULL on error (i.e. invalid arguments, out of memory) 1265 * @ingroup response 1266 */ 1267 _MHD_EXTERN struct MHD_Response * 1268 MHD_create_response_from_fd_at_offset (size_t size, 1269 int fd, 1270 off_t offset) 1271 { 1272 if (0 > offset) 1273 return NULL; 1274 return MHD_create_response_from_fd_at_offset64 (size, 1275 fd, 1276 (uint64_t) offset); 1277 } 1278 1279 1280 /** 1281 * Create a response object with the content of provided file with 1282 * specified offset used as the response body. 1283 * 1284 * The response object can be extended with header information and then 1285 * be used any number of times. 1286 * 1287 * If response object is used to answer HEAD request then the body 1288 * of the response is not used, while all headers (including automatic 1289 * headers) are used. 1290 * 1291 * @param size size of the data portion of the response; 1292 * sizes larger than 2 GiB may be not supported by OS or 1293 * MHD build; see ::MHD_FEATURE_LARGE_FILE 1294 * @param fd file descriptor referring to a file on disk with the 1295 * data; will be closed when response is destroyed; 1296 * fd should be in 'blocking' mode 1297 * @param offset offset to start reading from in the file; 1298 * reading file beyond 2 GiB may be not supported by OS or 1299 * MHD build; see ::MHD_FEATURE_LARGE_FILE 1300 * @return NULL on error (i.e. invalid arguments, out of memory) 1301 * @ingroup response 1302 */ 1303 _MHD_EXTERN struct MHD_Response * 1304 MHD_create_response_from_fd_at_offset64 (uint64_t size, 1305 int fd, 1306 uint64_t offset) 1307 { 1308 struct MHD_Response *response; 1309 1310 #if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64) 1311 if ( (sizeof(uint64_t) > sizeof(off_t)) && 1312 ( (size > (uint64_t) INT32_MAX) || 1313 (offset > (uint64_t) INT32_MAX) || 1314 ((size + offset) >= (uint64_t) INT32_MAX) ) ) 1315 return NULL; 1316 #endif 1317 if ( ((int64_t) size < 0) || 1318 ((int64_t) offset < 0) || 1319 ((int64_t) (size + offset) < 0) ) 1320 return NULL; 1321 1322 response = MHD_create_response_from_callback (size, 1323 MHD_FILE_READ_BLOCK_SIZE, 1324 &file_reader, 1325 NULL, 1326 &free_callback); 1327 if (NULL == response) 1328 return NULL; 1329 response->fd = fd; 1330 response->is_pipe = false; 1331 response->fd_off = offset; 1332 response->crc_cls = response; 1333 return response; 1334 } 1335 1336 1337 /** 1338 * Create a response object with the response body created by reading 1339 * the provided pipe. 1340 * 1341 * The response object can be extended with header information and 1342 * then be used ONLY ONCE. 1343 * 1344 * If response object is used to answer HEAD request then the body 1345 * of the response is not used, while all headers (including automatic 1346 * headers) are used. 1347 * 1348 * @param fd file descriptor referring to a read-end of a pipe with the 1349 * data; will be closed when response is destroyed; 1350 * fd should be in 'blocking' mode 1351 * @return NULL on error (i.e. invalid arguments, out of memory) 1352 * @ingroup response 1353 */ 1354 _MHD_EXTERN struct MHD_Response * 1355 MHD_create_response_from_pipe (int fd) 1356 { 1357 struct MHD_Response *response; 1358 1359 response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1360 MHD_FILE_READ_BLOCK_SIZE, 1361 &pipe_reader, 1362 NULL, 1363 &free_callback); 1364 if (NULL == response) 1365 return NULL; 1366 response->fd = fd; 1367 response->is_pipe = true; 1368 response->crc_cls = response; 1369 return response; 1370 } 1371 1372 1373 /** 1374 * Create a response object with the content of provided file used as 1375 * the response body. 1376 * 1377 * The response object can be extended with header information and then 1378 * be used any number of times. 1379 * 1380 * If response object is used to answer HEAD request then the body 1381 * of the response is not used, while all headers (including automatic 1382 * headers) are used. 1383 * 1384 * @param size size of the data portion of the response 1385 * @param fd file descriptor referring to a file on disk with the data 1386 * @return NULL on error (i.e. invalid arguments, out of memory) 1387 * @ingroup response 1388 */ 1389 _MHD_EXTERN struct MHD_Response * 1390 MHD_create_response_from_fd (size_t size, 1391 int fd) 1392 { 1393 return MHD_create_response_from_fd_at_offset64 (size, 1394 fd, 1395 0); 1396 } 1397 1398 1399 /** 1400 * Create a response object with the content of provided file used as 1401 * the response body. 1402 * 1403 * The response object can be extended with header information and then 1404 * be used any number of times. 1405 * 1406 * If response object is used to answer HEAD request then the body 1407 * of the response is not used, while all headers (including automatic 1408 * headers) are used. 1409 * 1410 * @param size size of the data portion of the response; 1411 * sizes larger than 2 GiB may be not supported by OS or 1412 * MHD build; see ::MHD_FEATURE_LARGE_FILE 1413 * @param fd file descriptor referring to a file on disk with the 1414 * data; will be closed when response is destroyed; 1415 * fd should be in 'blocking' mode 1416 * @return NULL on error (i.e. invalid arguments, out of memory) 1417 * @ingroup response 1418 */ 1419 _MHD_EXTERN struct MHD_Response * 1420 MHD_create_response_from_fd64 (uint64_t size, 1421 int fd) 1422 { 1423 return MHD_create_response_from_fd_at_offset64 (size, 1424 fd, 1425 0); 1426 } 1427 1428 1429 /** 1430 * Create a response object. 1431 * The response object can be extended with header information and then be used 1432 * any number of times. 1433 * 1434 * If response object is used to answer HEAD request then the body of the 1435 * response is not used, while all headers (including automatic headers) are 1436 * used. 1437 * 1438 * @param size size of the @a data portion of the response 1439 * @param data the data itself 1440 * @param must_free libmicrohttpd should free data when done 1441 * @param must_copy libmicrohttpd must make a copy of @a data 1442 * right away, the data may be released anytime after 1443 * this call returns 1444 * @return NULL on error (i.e. invalid arguments, out of memory) 1445 * @deprecated use #MHD_create_response_from_buffer instead 1446 * @ingroup response 1447 */ 1448 _MHD_EXTERN struct MHD_Response * 1449 MHD_create_response_from_data (size_t size, 1450 void *data, 1451 int must_free, 1452 int must_copy) 1453 { 1454 enum MHD_ResponseMemoryMode mode; 1455 1456 if (0 != must_copy) 1457 mode = MHD_RESPMEM_MUST_COPY; 1458 else if (0 != must_free) 1459 mode = MHD_RESPMEM_MUST_FREE; 1460 else 1461 mode = MHD_RESPMEM_PERSISTENT; 1462 1463 return MHD_create_response_from_buffer (size, data, mode); 1464 } 1465 1466 1467 /** 1468 * Create a response object with the content of provided buffer used as 1469 * the response body. 1470 * 1471 * The response object can be extended with header information and then 1472 * be used any number of times. 1473 * 1474 * If response object is used to answer HEAD request then the body 1475 * of the response is not used, while all headers (including automatic 1476 * headers) are used. 1477 * 1478 * @param size size of the data portion of the response 1479 * @param buffer size bytes containing the response's data portion 1480 * @param mode flags for buffer management 1481 * @return NULL on error (i.e. invalid arguments, out of memory) 1482 * @ingroup response 1483 */ 1484 _MHD_EXTERN struct MHD_Response * 1485 MHD_create_response_from_buffer (size_t size, 1486 void *buffer, 1487 enum MHD_ResponseMemoryMode mode) 1488 { 1489 if (MHD_RESPMEM_MUST_FREE == mode) 1490 return MHD_create_response_from_buffer_with_free_callback_cls (size, 1491 buffer, 1492 &free, 1493 buffer); 1494 if (MHD_RESPMEM_MUST_COPY == mode) 1495 return MHD_create_response_from_buffer_copy (size, 1496 buffer); 1497 1498 return MHD_create_response_from_buffer_with_free_callback_cls (size, 1499 buffer, 1500 NULL, 1501 NULL); 1502 } 1503 1504 1505 /** 1506 * Create a response object with the content of provided statically allocated 1507 * buffer used as the response body. 1508 * 1509 * The buffer must be valid for the lifetime of the response. The easiest way 1510 * to achieve this is to use a statically allocated buffer. 1511 * 1512 * The response object can be extended with header information and then 1513 * be used any number of times. 1514 * 1515 * If response object is used to answer HEAD request then the body 1516 * of the response is not used, while all headers (including automatic 1517 * headers) are used. 1518 * 1519 * @param size the size of the data in @a buffer, can be zero 1520 * @param buffer the buffer with the data for the response body, can be NULL 1521 * if @a size is zero 1522 * @return NULL on error (i.e. invalid arguments, out of memory) 1523 * @note Available since #MHD_VERSION 0x00097701 1524 * @ingroup response 1525 */ 1526 _MHD_EXTERN struct MHD_Response * 1527 MHD_create_response_from_buffer_static (size_t size, 1528 const void *buffer) 1529 { 1530 return MHD_create_response_from_buffer_with_free_callback_cls (size, 1531 buffer, 1532 NULL, 1533 NULL); 1534 } 1535 1536 1537 /** 1538 * Create a response object with the content of provided temporal buffer 1539 * used as the response body. 1540 * 1541 * An internal copy of the buffer will be made automatically, so buffer have 1542 * to be valid only during the call of this function (as a typical example: 1543 * buffer is a local (non-static) array). 1544 * 1545 * The response object can be extended with header information and then 1546 * be used any number of times. 1547 * 1548 * If response object is used to answer HEAD request then the body 1549 * of the response is not used, while all headers (including automatic 1550 * headers) are used. 1551 * 1552 * @param size the size of the data in @a buffer, can be zero 1553 * @param buffer the buffer with the data for the response body, can be NULL 1554 * if @a size is zero 1555 * @return NULL on error (i.e. invalid arguments, out of memory) 1556 * @note Available since #MHD_VERSION 0x00097701 1557 * @ingroup response 1558 */ 1559 _MHD_EXTERN struct MHD_Response * 1560 MHD_create_response_from_buffer_copy (size_t size, 1561 const void *buffer) 1562 { 1563 struct MHD_Response *r; 1564 void *mhd_copy; 1565 1566 if (0 == size) 1567 return MHD_create_response_from_buffer_with_free_callback_cls (0, 1568 NULL, 1569 NULL, 1570 NULL); 1571 if (NULL == buffer) 1572 return NULL; 1573 1574 mhd_copy = malloc (size); 1575 if (NULL == mhd_copy) 1576 return NULL; 1577 memcpy (mhd_copy, buffer, size); 1578 1579 r = MHD_create_response_from_buffer_with_free_callback_cls (size, 1580 mhd_copy, 1581 &free, 1582 mhd_copy); 1583 if (NULL == r) 1584 free (mhd_copy); 1585 else 1586 { 1587 /* TODO: remove the next assignment, the buffer should not be modifiable */ 1588 r->data_buffer_size = size; 1589 } 1590 1591 return r; 1592 } 1593 1594 1595 /** 1596 * Create a response object with the content of provided buffer used as 1597 * the response body. 1598 * 1599 * The response object can be extended with header information and then 1600 * be used any number of times. 1601 * 1602 * If response object is used to answer HEAD request then the body 1603 * of the response is not used, while all headers (including automatic 1604 * headers) are used. 1605 * 1606 * @param size size of the data portion of the response 1607 * @param buffer size bytes containing the response's data portion 1608 * @param crfc function to call to free the @a buffer 1609 * @return NULL on error (i.e. invalid arguments, out of memory) 1610 * @ingroup response 1611 */ 1612 _MHD_EXTERN struct MHD_Response * 1613 MHD_create_response_from_buffer_with_free_callback (size_t size, 1614 void *buffer, 1615 MHD_ContentReaderFreeCallback 1616 crfc) 1617 { 1618 return MHD_create_response_from_buffer_with_free_callback_cls (size, 1619 buffer, 1620 crfc, 1621 buffer); 1622 } 1623 1624 1625 /** 1626 * Create a response object with the content of provided buffer used as 1627 * the response body. 1628 * 1629 * The response object can be extended with header information and then 1630 * be used any number of times. 1631 * 1632 * If response object is used to answer HEAD request then the body 1633 * of the response is not used, while all headers (including automatic 1634 * headers) are used. 1635 * 1636 * @param size size of the data portion of the response 1637 * @param buffer size bytes containing the response's data portion 1638 * @param crfc function to call to cleanup, if set to NULL then callback 1639 * is not called 1640 * @param crfc_cls an argument for @a crfc 1641 * @return NULL on error (i.e. invalid arguments, out of memory) 1642 * @note Available since #MHD_VERSION 0x00097302 1643 * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097701 1644 * @ingroup response 1645 */ 1646 _MHD_EXTERN struct MHD_Response * 1647 MHD_create_response_from_buffer_with_free_callback_cls (size_t size, 1648 const void *buffer, 1649 MHD_ContentReaderFreeCallback 1650 crfc, 1651 void *crfc_cls) 1652 { 1653 struct MHD_Response *r; 1654 1655 if ((NULL == buffer) && (size > 0)) 1656 return NULL; 1657 #if SIZEOF_SIZE_T >= SIZEOF_UINT64_T 1658 if (MHD_SIZE_UNKNOWN == size) 1659 return NULL; 1660 #endif /* SIZEOF_SIZE_T >= SIZEOF_UINT64_T */ 1661 r = MHD_calloc_ (1, sizeof (struct MHD_Response)); 1662 if (NULL == r) 1663 return NULL; 1664 #if defined(MHD_USE_THREADS) 1665 if (! MHD_mutex_init_ (&r->mutex)) 1666 { 1667 free (r); 1668 return NULL; 1669 } 1670 #endif 1671 r->fd = -1; 1672 r->reference_count = 1; 1673 r->total_size = size; 1674 r->data = buffer; 1675 r->data_size = size; 1676 r->crfc = crfc; 1677 r->crc_cls = crfc_cls; 1678 return r; 1679 } 1680 1681 1682 /** 1683 * Create a response object with an array of memory buffers 1684 * used as the response body. 1685 * 1686 * The response object can be extended with header information and then 1687 * be used any number of times. 1688 * 1689 * If response object is used to answer HEAD request then the body 1690 * of the response is not used, while all headers (including automatic 1691 * headers) are used. 1692 * 1693 * @param iov the array for response data buffers, an internal copy of this 1694 * will be made 1695 * @param iovcnt the number of elements in @a iov 1696 * @param free_cb the callback to clean up any data associated with @a iov when 1697 * the response is destroyed. 1698 * @param cls the argument passed to @a free_cb 1699 * @return NULL on error (i.e. invalid arguments, out of memory) 1700 */ 1701 _MHD_EXTERN struct MHD_Response * 1702 MHD_create_response_from_iovec (const struct MHD_IoVec *iov, 1703 unsigned int iovcnt, 1704 MHD_ContentReaderFreeCallback free_cb, 1705 void *cls) 1706 { 1707 struct MHD_Response *response; 1708 unsigned int i; 1709 int i_cp = 0; /**< Index in the copy of iov */ 1710 uint64_t total_size = 0; 1711 const void *last_valid_buffer = NULL; 1712 1713 if ((NULL == iov) && (0 < iovcnt)) 1714 return NULL; 1715 1716 response = MHD_calloc_ (1, sizeof (struct MHD_Response)); 1717 if (NULL == response) 1718 return NULL; 1719 if (! MHD_mutex_init_ (&response->mutex)) 1720 { 1721 free (response); 1722 return NULL; 1723 } 1724 /* Calculate final size, number of valid elements, and check 'iov' */ 1725 for (i = 0; i < iovcnt; ++i) 1726 { 1727 if (0 == iov[i].iov_len) 1728 continue; /* skip zero-sized elements */ 1729 if (NULL == iov[i].iov_base) 1730 { 1731 i_cp = -1; /* error */ 1732 break; 1733 } 1734 if ( (total_size > (total_size + iov[i].iov_len)) || 1735 (INT_MAX == i_cp) || 1736 (SSIZE_MAX < (total_size + iov[i].iov_len)) ) 1737 { 1738 i_cp = -1; /* overflow */ 1739 break; 1740 } 1741 last_valid_buffer = iov[i].iov_base; 1742 total_size += iov[i].iov_len; 1743 #if defined(MHD_POSIX_SOCKETS) || ! defined(_WIN64) 1744 i_cp++; 1745 #else /* ! MHD_POSIX_SOCKETS && _WIN64 */ 1746 { 1747 int64_t i_add; 1748 1749 i_add = (int64_t) (iov[i].iov_len / ULONG_MAX); 1750 if (0 != iov[i].iov_len % ULONG_MAX) 1751 i_add++; 1752 if (INT_MAX < (i_add + i_cp)) 1753 { 1754 i_cp = -1; /* overflow */ 1755 break; 1756 } 1757 i_cp += (int) i_add; 1758 } 1759 #endif /* ! MHD_POSIX_SOCKETS && _WIN64 */ 1760 } 1761 if (-1 == i_cp) 1762 { 1763 /* Some error condition */ 1764 MHD_mutex_destroy_chk_ (&response->mutex); 1765 free (response); 1766 return NULL; 1767 } 1768 response->fd = -1; 1769 response->reference_count = 1; 1770 response->total_size = total_size; 1771 response->crc_cls = cls; 1772 response->crfc = free_cb; 1773 if (0 == i_cp) 1774 { 1775 mhd_assert (0 == total_size); 1776 return response; 1777 } 1778 if (1 == i_cp) 1779 { 1780 mhd_assert (NULL != last_valid_buffer); 1781 response->data = last_valid_buffer; 1782 response->data_size = (size_t) total_size; 1783 return response; 1784 } 1785 mhd_assert (1 < i_cp); 1786 if (1) 1787 { /* for local variables local scope only */ 1788 MHD_iovec_ *iov_copy; 1789 int num_copy_elements = i_cp; 1790 1791 iov_copy = MHD_calloc_ ((size_t) num_copy_elements, \ 1792 sizeof(MHD_iovec_)); 1793 if (NULL == iov_copy) 1794 { 1795 MHD_mutex_destroy_chk_ (&response->mutex); 1796 free (response); 1797 return NULL; 1798 } 1799 i_cp = 0; 1800 for (i = 0; i < iovcnt; ++i) 1801 { 1802 size_t element_size = iov[i].iov_len; 1803 const uint8_t *buf = (const uint8_t *) iov[i].iov_base; 1804 1805 if (0 == element_size) 1806 continue; /* skip zero-sized elements */ 1807 #if defined(MHD_WINSOCK_SOCKETS) && defined(_WIN64) 1808 while (MHD_IOV_ELMN_MAX_SIZE < element_size) 1809 { 1810 iov_copy[i_cp].iov_base = (char *) _MHD_DROP_CONST (buf); 1811 iov_copy[i_cp].iov_len = ULONG_MAX; 1812 buf += ULONG_MAX; 1813 element_size -= ULONG_MAX; 1814 i_cp++; 1815 } 1816 #endif /* MHD_WINSOCK_SOCKETS && _WIN64 */ 1817 iov_copy[i_cp].iov_base = _MHD_DROP_CONST (buf); 1818 iov_copy[i_cp].iov_len = (MHD_iov_size_) element_size; 1819 i_cp++; 1820 } 1821 mhd_assert (num_copy_elements == i_cp); 1822 mhd_assert (0 <= i_cp); 1823 response->data_iov = iov_copy; 1824 response->data_iovcnt = (unsigned int) i_cp; 1825 } 1826 return response; 1827 } 1828 1829 1830 /** 1831 * Create a response object with empty (zero size) body. 1832 * 1833 * The response object can be extended with header information and then be used 1834 * any number of times. 1835 * 1836 * This function is a faster equivalent of #MHD_create_response_from_buffer call 1837 * with zero size combined with call of #MHD_set_response_options. 1838 * 1839 * @param flags the flags for the new response object 1840 * @return NULL on error (i.e. invalid arguments, out of memory), 1841 * the pointer to the created response object otherwise 1842 * @note Available since #MHD_VERSION 0x00097701 1843 * @ingroup response 1844 */ 1845 _MHD_EXTERN struct MHD_Response * 1846 MHD_create_response_empty (enum MHD_ResponseFlags flags) 1847 { 1848 struct MHD_Response *r; 1849 r = (struct MHD_Response *) MHD_calloc_ (1, sizeof (struct MHD_Response)); 1850 if (NULL != r) 1851 { 1852 if (MHD_mutex_init_ (&r->mutex)) 1853 { 1854 r->fd = -1; 1855 r->reference_count = 1; 1856 /* If any flags combination will be not allowed, replace the next 1857 * assignment with MHD_set_response_options() call. */ 1858 r->flags = flags; 1859 1860 return r; /* Successful result */ 1861 } 1862 free (r); 1863 } 1864 return NULL; /* Something failed */ 1865 } 1866 1867 1868 #ifdef UPGRADE_SUPPORT 1869 /** 1870 * This connection-specific callback is provided by MHD to 1871 * applications (unusual) during the #MHD_UpgradeHandler. 1872 * It allows applications to perform 'special' actions on 1873 * the underlying socket from the upgrade. 1874 * 1875 * @param urh the handle identifying the connection to perform 1876 * the upgrade @a action on. 1877 * @param action which action should be performed 1878 * @param ... arguments to the action (depends on the action) 1879 * @return #MHD_NO on error, #MHD_YES on success 1880 */ 1881 _MHD_EXTERN enum MHD_Result 1882 MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, 1883 enum MHD_UpgradeAction action, 1884 ...) 1885 { 1886 struct MHD_Connection *connection; 1887 struct MHD_Daemon *daemon; 1888 1889 if (NULL == urh) 1890 return MHD_NO; 1891 connection = urh->connection; 1892 1893 /* Precaution checks on external data. */ 1894 if (NULL == connection) 1895 return MHD_NO; 1896 daemon = connection->daemon; 1897 if (NULL == daemon) 1898 return MHD_NO; 1899 1900 switch (action) 1901 { 1902 case MHD_UPGRADE_ACTION_CLOSE: 1903 if (urh->was_closed) 1904 return MHD_NO; /* Already closed. */ 1905 1906 /* transition to special 'closed' state for start of cleanup */ 1907 #ifdef HTTPS_SUPPORT 1908 if (0 != (daemon->options & MHD_USE_TLS) ) 1909 { 1910 /* signal that app is done by shutdown() of 'app' socket */ 1911 /* Application will not use anyway this socket after this command. */ 1912 shutdown (urh->app.socket, 1913 SHUT_RDWR); 1914 } 1915 #endif /* HTTPS_SUPPORT */ 1916 mhd_assert (MHD_CONNECTION_UPGRADE == connection->state); 1917 /* The next function will mark the connection as closed by application 1918 * by setting 'urh->was_closed'. 1919 * As soon as connection will be marked with BOTH 1920 * 'urh->was_closed' AND 'urh->clean_ready', it will 1921 * be moved to cleanup list by MHD_resume_connection(). */ 1922 MHD_upgraded_connection_mark_app_closed_ (connection); 1923 return MHD_YES; 1924 case MHD_UPGRADE_ACTION_CORK_ON: 1925 /* Unportable API. TODO: replace with portable action. */ 1926 return MHD_connection_set_cork_state_ (connection, 1927 true) ? MHD_YES : MHD_NO; 1928 case MHD_UPGRADE_ACTION_CORK_OFF: 1929 /* Unportable API. TODO: replace with portable action. */ 1930 return MHD_connection_set_cork_state_ (connection, 1931 false) ? MHD_YES : MHD_NO; 1932 default: 1933 /* we don't understand this one */ 1934 return MHD_NO; 1935 } 1936 } 1937 1938 1939 /** 1940 * We are done sending the header of a given response to the client. 1941 * Now it is time to perform the upgrade and hand over the connection 1942 * to the application. 1943 * @remark To be called only from thread that process connection's 1944 * recv(), send() and response. Must be called right after sending 1945 * response headers. 1946 * 1947 * @param response the response that was created for an upgrade 1948 * @param connection the specific connection we are upgrading 1949 * @return #MHD_YES on success, #MHD_NO on failure (will cause 1950 * connection to be closed) 1951 */ 1952 enum MHD_Result 1953 MHD_response_execute_upgrade_ (struct MHD_Response *response, 1954 struct MHD_Connection *connection) 1955 { 1956 #if defined(HTTPS_SUPPORT) || defined(_DEBUG) || defined(HAVE_MESSAGES) 1957 struct MHD_Daemon *const daemon = connection->daemon; 1958 #endif /* HTTPS_SUPPORT || _DEBUG || HAVE_MESSAGES */ 1959 struct MHD_UpgradeResponseHandle *urh; 1960 size_t rbo; 1961 1962 #ifdef MHD_USE_THREADS 1963 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 1964 MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); 1965 #endif /* MHD_USE_THREADS */ 1966 1967 /* "Upgrade" responses accepted only if MHD_ALLOW_UPGRADE is enabled */ 1968 mhd_assert (0 != (daemon->options & MHD_ALLOW_UPGRADE)); 1969 /* The header was checked when response queued */ 1970 mhd_assert (NULL != \ 1971 MHD_get_response_element_n_ (response, MHD_HEADER_KIND, 1972 MHD_HTTP_HEADER_UPGRADE, 1973 MHD_STATICSTR_LEN_ ( \ 1974 MHD_HTTP_HEADER_UPGRADE))); 1975 1976 if (! connection->sk_nonblck) 1977 { 1978 #ifdef HAVE_MESSAGES 1979 MHD_DLOG (daemon, 1980 _ ("Cannot execute \"upgrade\" as the socket is in " \ 1981 "the blocking mode.\n")); 1982 #endif 1983 return MHD_NO; 1984 } 1985 urh = MHD_calloc_ (1, sizeof (struct MHD_UpgradeResponseHandle)); 1986 if (NULL == urh) 1987 return MHD_NO; 1988 urh->connection = connection; 1989 rbo = connection->read_buffer_offset; 1990 connection->read_buffer_offset = 0; 1991 MHD_connection_set_nodelay_state_ (connection, false); 1992 MHD_connection_set_cork_state_ (connection, false); 1993 #ifdef HTTPS_SUPPORT 1994 if (0 != (daemon->options & MHD_USE_TLS) ) 1995 { 1996 MHD_socket sv[2]; 1997 #if defined(MHD_socket_nosignal_) || ! defined(MHD_socket_pair_nblk_) 1998 int res1; 1999 int res2; 2000 #endif /* MHD_socket_nosignal_ || !MHD_socket_pair_nblk_ */ 2001 2002 #ifdef MHD_socket_pair_nblk_ 2003 if (! MHD_socket_pair_nblk_ (sv)) 2004 { 2005 free (urh); 2006 return MHD_NO; 2007 } 2008 #else /* !MHD_socket_pair_nblk_ */ 2009 if (! MHD_socket_pair_ (sv)) 2010 { 2011 free (urh); 2012 return MHD_NO; 2013 } 2014 res1 = MHD_socket_nonblocking_ (sv[0]); 2015 res2 = MHD_socket_nonblocking_ (sv[1]); 2016 if ( (! res1) || (! res2) ) 2017 { 2018 #ifdef HAVE_MESSAGES 2019 MHD_DLOG (daemon, 2020 _ ("Failed to make loopback sockets non-blocking.\n")); 2021 #endif 2022 if (! res2) 2023 { 2024 /* Socketpair cannot be used. */ 2025 MHD_socket_close_chk_ (sv[0]); 2026 MHD_socket_close_chk_ (sv[1]); 2027 free (urh); 2028 return MHD_NO; 2029 } 2030 } 2031 #endif /* !MHD_socket_pair_nblk_ */ 2032 #ifdef MHD_socket_nosignal_ 2033 res1 = MHD_socket_nosignal_ (sv[0]); 2034 res2 = MHD_socket_nosignal_ (sv[1]); 2035 if ( (! res1) || (! res2) ) 2036 { 2037 #ifdef HAVE_MESSAGES 2038 MHD_DLOG (daemon, 2039 _ ("Failed to set SO_NOSIGPIPE on loopback sockets.\n")); 2040 #endif 2041 #ifndef MSG_NOSIGNAL 2042 if (! res2) 2043 { 2044 /* Socketpair cannot be used. */ 2045 MHD_socket_close_chk_ (sv[0]); 2046 MHD_socket_close_chk_ (sv[1]); 2047 free (urh); 2048 return MHD_NO; 2049 } 2050 #endif /* ! MSG_NOSIGNAL */ 2051 } 2052 #endif /* MHD_socket_nosignal_ */ 2053 if (MHD_D_IS_USING_SELECT_ (daemon) && 2054 (! MHD_D_DOES_SCKT_FIT_FDSET_ (sv[1], daemon)) ) 2055 { 2056 #ifdef HAVE_MESSAGES 2057 MHD_DLOG (daemon, 2058 _ ("Socketpair descriptor is not less than FD_SETSIZE: " \ 2059 "%d >= %d\n"), 2060 (int) sv[1], 2061 (int) MHD_D_GET_FD_SETSIZE_ (daemon)); 2062 #endif 2063 MHD_socket_close_chk_ (sv[0]); 2064 MHD_socket_close_chk_ (sv[1]); 2065 free (urh); 2066 return MHD_NO; 2067 } 2068 urh->app.socket = sv[0]; 2069 urh->app.urh = urh; 2070 urh->app.celi = MHD_EPOLL_STATE_UNREADY; 2071 urh->mhd.socket = sv[1]; 2072 urh->mhd.urh = urh; 2073 urh->mhd.celi = MHD_EPOLL_STATE_UNREADY; 2074 #ifdef EPOLL_SUPPORT 2075 /* Launch IO processing by the event loop */ 2076 if (MHD_D_IS_USING_EPOLL_ (daemon)) 2077 { 2078 /* We're running with epoll(), need to add the sockets 2079 to the event set of the daemon's `epoll_upgrade_fd` */ 2080 struct epoll_event event; 2081 2082 mhd_assert (-1 != daemon->epoll_upgrade_fd); 2083 /* First, add network socket */ 2084 event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; 2085 event.data.ptr = &urh->app; 2086 if (0 != epoll_ctl (daemon->epoll_upgrade_fd, 2087 EPOLL_CTL_ADD, 2088 connection->socket_fd, 2089 &event)) 2090 { 2091 #ifdef HAVE_MESSAGES 2092 MHD_DLOG (daemon, 2093 _ ("Call to epoll_ctl failed: %s\n"), 2094 MHD_socket_last_strerr_ ()); 2095 #endif 2096 MHD_socket_close_chk_ (sv[0]); 2097 MHD_socket_close_chk_ (sv[1]); 2098 free (urh); 2099 return MHD_NO; 2100 } 2101 2102 /* Second, add our end of the UNIX socketpair() */ 2103 event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; 2104 event.data.ptr = &urh->mhd; 2105 if (0 != epoll_ctl (daemon->epoll_upgrade_fd, 2106 EPOLL_CTL_ADD, 2107 urh->mhd.socket, 2108 &event)) 2109 { 2110 event.events = EPOLLIN | EPOLLOUT | EPOLLPRI; 2111 event.data.ptr = &urh->app; 2112 if (0 != epoll_ctl (daemon->epoll_upgrade_fd, 2113 EPOLL_CTL_DEL, 2114 connection->socket_fd, 2115 &event)) 2116 MHD_PANIC (_ ("Error cleaning up while handling epoll error.\n")); 2117 #ifdef HAVE_MESSAGES 2118 MHD_DLOG (daemon, 2119 _ ("Call to epoll_ctl failed: %s\n"), 2120 MHD_socket_last_strerr_ ()); 2121 #endif 2122 MHD_socket_close_chk_ (sv[0]); 2123 MHD_socket_close_chk_ (sv[1]); 2124 free (urh); 2125 return MHD_NO; 2126 } 2127 EDLL_insert (daemon->eready_urh_head, 2128 daemon->eready_urh_tail, 2129 urh); 2130 urh->in_eready_list = true; 2131 } 2132 #endif /* EPOLL_SUPPORT */ 2133 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 2134 { 2135 /* This takes care of further processing for most event loops: 2136 simply add to DLL for bi-direcitonal processing */ 2137 DLL_insert (daemon->urh_head, 2138 daemon->urh_tail, 2139 urh); 2140 } 2141 /* In thread-per-connection mode, thread will switch to forwarding once 2142 * connection.urh is not NULL and connection.state == MHD_CONNECTION_UPGRADE. 2143 */ 2144 } 2145 else 2146 { 2147 urh->app.socket = MHD_INVALID_SOCKET; 2148 urh->mhd.socket = MHD_INVALID_SOCKET; 2149 /* Non-TLS connection do not hold any additional resources. */ 2150 urh->clean_ready = true; 2151 } 2152 #else /* ! HTTPS_SUPPORT */ 2153 urh->clean_ready = true; 2154 #endif /* ! HTTPS_SUPPORT */ 2155 connection->urh = urh; 2156 /* As far as MHD's event loops are concerned, this connection is 2157 suspended; it will be resumed once application is done by the 2158 #MHD_upgrade_action() function */ 2159 internal_suspend_connection_ (connection); 2160 2161 /* hand over socket to application */ 2162 response->upgrade_handler (response->upgrade_handler_cls, 2163 connection, 2164 connection->rq.client_context, 2165 connection->read_buffer, 2166 rbo, 2167 #ifdef HTTPS_SUPPORT 2168 (0 == (daemon->options & MHD_USE_TLS) ) ? 2169 connection->socket_fd : urh->app.socket, 2170 #else /* ! HTTPS_SUPPORT */ 2171 connection->socket_fd, 2172 #endif /* ! HTTPS_SUPPORT */ 2173 urh); 2174 2175 #ifdef HTTPS_SUPPORT 2176 if (0 != (daemon->options & MHD_USE_TLS)) 2177 { 2178 struct MemoryPool *const pool = connection->pool; 2179 size_t avail; 2180 char *buf; 2181 2182 /* All data should be sent already */ 2183 mhd_assert (connection->write_buffer_send_offset == \ 2184 connection->write_buffer_append_offset); 2185 MHD_pool_deallocate (pool, connection->write_buffer, 2186 connection->write_buffer_size); 2187 connection->write_buffer_append_offset = 0; 2188 connection->write_buffer_send_offset = 0; 2189 connection->write_buffer_size = 0; 2190 connection->write_buffer = NULL; 2191 2192 /* Extra read data should be processed already by the application */ 2193 MHD_pool_deallocate (pool, connection->read_buffer, 2194 connection->read_buffer_size); 2195 connection->read_buffer_offset = 0; 2196 connection->read_buffer_size = 0; 2197 connection->read_buffer = NULL; 2198 2199 avail = MHD_pool_get_free (pool); 2200 if (avail < RESERVE_EBUF_SIZE) 2201 { 2202 /* connection's pool is totally at the limit, 2203 use our 'emergency' buffer of #RESERVE_EBUF_SIZE bytes. */ 2204 avail = RESERVE_EBUF_SIZE; 2205 buf = urh->e_buf; 2206 #ifdef HAVE_MESSAGES 2207 MHD_DLOG (daemon, 2208 _ ("Memory shortage in connection's memory pool. " \ 2209 "The \"upgraded\" communication will be inefficient.\n")); 2210 #endif 2211 } 2212 else 2213 { 2214 /* Normal case: grab all remaining memory from the 2215 connection's pool for the IO buffers; the connection 2216 certainly won't need it anymore as we've upgraded 2217 to another protocol. */ 2218 buf = MHD_pool_allocate (pool, 2219 avail, 2220 false); 2221 } 2222 /* use half the buffer for inbound, half for outbound */ 2223 urh->in_buffer_size = avail / 2; 2224 urh->out_buffer_size = avail - urh->in_buffer_size; 2225 urh->in_buffer = buf; 2226 urh->out_buffer = buf + urh->in_buffer_size; 2227 } 2228 #endif /* HTTPS_SUPPORT */ 2229 return MHD_YES; 2230 } 2231 2232 2233 /** 2234 * Create a response object that can be used for 101 UPGRADE 2235 * responses, for example to implement WebSockets. After sending the 2236 * response, control over the data stream is given to the callback (which 2237 * can then, for example, start some bi-directional communication). 2238 * If the response is queued for multiple connections, the callback 2239 * will be called for each connection. The callback 2240 * will ONLY be called after the response header was successfully passed 2241 * to the OS; if there are communication errors before, the usual MHD 2242 * connection error handling code will be performed. 2243 * 2244 * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS) 2245 * and setting correct HTTP headers for the upgrade must be done 2246 * manually (this way, it is possible to implement most existing 2247 * WebSocket versions using this API; in fact, this API might be useful 2248 * for any protocol switch, not just WebSockets). Note that 2249 * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this 2250 * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" 2251 * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 2252 * Switching Protocols" (if the response code 101 is used). 2253 * 2254 * As usual, the response object can be extended with header 2255 * information and then be used any number of times (as long as the 2256 * header information is not connection-specific). 2257 * 2258 * @param upgrade_handler function to call with the 'upgraded' socket 2259 * @param upgrade_handler_cls closure for @a upgrade_handler 2260 * @return NULL on error (i.e. invalid arguments, out of memory) 2261 */ 2262 _MHD_EXTERN struct MHD_Response * 2263 MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, 2264 void *upgrade_handler_cls) 2265 { 2266 struct MHD_Response *response; 2267 2268 if (NULL == upgrade_handler) 2269 return NULL; /* invalid request */ 2270 response = MHD_calloc_ (1, sizeof (struct MHD_Response)); 2271 if (NULL == response) 2272 return NULL; 2273 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2274 if (! MHD_mutex_init_ (&response->mutex)) 2275 { 2276 free (response); 2277 return NULL; 2278 } 2279 #endif 2280 response->upgrade_handler = upgrade_handler; 2281 response->upgrade_handler_cls = upgrade_handler_cls; 2282 response->total_size = 0; 2283 response->reference_count = 1; 2284 if (MHD_NO == 2285 MHD_add_response_header (response, 2286 MHD_HTTP_HEADER_CONNECTION, 2287 "Upgrade")) 2288 { 2289 MHD_destroy_response (response); 2290 return NULL; 2291 } 2292 return response; 2293 } 2294 2295 2296 #endif /* UPGRADE_SUPPORT */ 2297 2298 2299 /** 2300 * Destroy a response object and associated resources. Note that 2301 * libmicrohttpd may keep some of the resources around if the response 2302 * is still in the queue for some clients, so the memory may not 2303 * necessarily be freed immediately. 2304 * 2305 * @param response response to destroy 2306 * @ingroup response 2307 */ 2308 _MHD_EXTERN void 2309 MHD_destroy_response (struct MHD_Response *response) 2310 { 2311 struct MHD_HTTP_Res_Header *pos; 2312 2313 if (NULL == response) 2314 return; 2315 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2316 MHD_mutex_lock_chk_ (&response->mutex); 2317 #endif 2318 if (0 != --(response->reference_count)) 2319 { 2320 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2321 MHD_mutex_unlock_chk_ (&response->mutex); 2322 #endif 2323 return; 2324 } 2325 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2326 MHD_mutex_unlock_chk_ (&response->mutex); 2327 MHD_mutex_destroy_chk_ (&response->mutex); 2328 #endif 2329 if (NULL != response->crfc) 2330 response->crfc (response->crc_cls); 2331 2332 if (NULL != response->data_iov) 2333 { 2334 free (response->data_iov); 2335 } 2336 2337 while (NULL != response->first_header) 2338 { 2339 pos = response->first_header; 2340 response->first_header = pos->next; 2341 free (pos->header); 2342 free (pos->value); 2343 free (pos); 2344 } 2345 free (response); 2346 } 2347 2348 2349 /** 2350 * Increments the reference counter for the @a response. 2351 * 2352 * @param response object to modify 2353 */ 2354 void 2355 MHD_increment_response_rc (struct MHD_Response *response) 2356 { 2357 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2358 MHD_mutex_lock_chk_ (&response->mutex); 2359 #endif 2360 (response->reference_count)++; 2361 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2362 MHD_mutex_unlock_chk_ (&response->mutex); 2363 #endif 2364 } 2365 2366 2367 /* end of response.c */