Debian Codegraph @

src/microhttpd/internal.h

raw
1 /*
2 This file is part of libmicrohttpd
3 Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
4 Copyright (C) 2014-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 /**
22 * @file microhttpd/internal.h
23 * @brief MHD internal shared structures
24 * @author Daniel Pittman
25 * @author Christian Grothoff
26 * @author Karlson2k (Evgeny Grin)
27 */
28
29 #ifndef INTERNAL_H
30 #define INTERNAL_H
31
32 #include "mhd_options.h"
33 #include "platform.h"
34 #include "microhttpd.h"
35 #include "mhd_assert.h"
36
37 #ifdef HTTPS_SUPPORT
38 #include <gnutls/gnutls.h>
39 #if GNUTLS_VERSION_MAJOR >= 3
40 #include <gnutls/abstract.h>
41 #endif
42 #endif /* HTTPS_SUPPORT */
43
44 #ifdef HAVE_STDBOOL_H
45 #include <stdbool.h>
46 #endif
47
48 #ifdef HAVE_INTTYPES_H
49 #include <inttypes.h>
50 #endif /* HAVE_INTTYPES_H */
51
52 #ifndef PRIu64
53 #define PRIu64 "llu"
54 #endif /* ! PRIu64 */
55
56 /* Must be included before other internal headers! */
57 #include "mhd_panic.h"
58
59 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
60 #include "mhd_threads.h"
61 #endif
62 #include "mhd_locks.h"
63 #include "mhd_sockets.h"
64 #include "mhd_itc_types.h"
65 #include "mhd_str_types.h"
66 #if defined(BAUTH_SUPPORT) || defined(DAUTH_SUPPORT)
67 #include "gen_auth.h"
68 #endif /* BAUTH_SUPPORT || DAUTH_SUPPORT*/
69
70
71 /**
72 * Macro to drop 'const' qualifier from pointer without compiler warning.
73 * To be used *only* to deal with broken external APIs, which require non-const
74 * pointer to unmodifiable data.
75 * Must not be used to transform pointers for MHD needs.
76 */
77 #define _MHD_DROP_CONST(ptr) ((void *) ((uintptr_t) ((const void *) (ptr))))
78
79 /**
80 * @def _MHD_MACRO_NO
81 * "Negative answer"/"false" for use in macros, meaningful for precompiler
82 */
83 #define _MHD_MACRO_NO 0
84
85 /**
86 * @def _MHD_MACRO_YES
87 * "Positive answer"/"true" for use in macros, meaningful for precompiler
88 */
89 #define _MHD_MACRO_YES 1
90
91 /**
92 * Close FD and abort execution if error is detected.
93 * @param fd the FD to close
94 */
95 #define MHD_fd_close_chk_(fd) do { \
96 if ( (0 != close ((fd)) && (EBADF == errno)) ) { \
97 MHD_PANIC (_ ("Failed to close FD.\n")); \
98 } \
99 } while (0)
100
101 /*
102 #define EXTRA_CHECKS _MHD_MACRO_NO
103 * Not used. Behaviour is controlled by _DEBUG/NDEBUG macros.
104 */
105
106 #ifndef _MHD_DEBUG_CONNECT
107 /**
108 * Print extra messages when establishing
109 * connections? (only adds non-error messages).
110 */
111 #define _MHD_DEBUG_CONNECT _MHD_MACRO_NO
112 #endif /* ! _MHD_DEBUG_CONNECT */
113
114 #ifndef _MHD_DEBUG_SEND_DATA
115 /**
116 * Should all data send be printed to stderr?
117 */
118 #define _MHD_DEBUG_SEND_DATA _MHD_MACRO_NO
119 #endif /* ! _MHD_DEBUG_SEND_DATA */
120
121 #ifndef _MHD_DEBUG_CLOSE
122 /**
123 * Add extra debug messages with reasons for closing connections
124 * (non-error reasons).
125 */
126 #define _MHD_DEBUG_CLOSE _MHD_MACRO_NO
127 #endif /* ! _MHD_DEBUG_CLOSE */
128
129 #define MHD_MAX(a,b) (((a)<(b)) ? (b) : (a))
130 #define MHD_MIN(a,b) (((a)<(b)) ? (a) : (b))
131
132
133 /**
134 * Minimum reasonable size by which MHD tries to increment read/write buffers.
135 * We usually begin with half the available pool space for the
136 * IO-buffer, but if absolutely needed we additively grow by the
137 * number of bytes given here (up to -- theoretically -- the full pool
138 * space).
139 *
140 * Currently set to reasonable maximum MSS size.
141 */
142 #define MHD_BUF_INC_SIZE 1500
143
144 #ifndef MHD_STATICSTR_LEN_
145 /**
146 * Determine length of static string / macro strings at compile time.
147 */
148 #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
149 #endif /* ! MHD_STATICSTR_LEN_ */
150
151
152 /**
153 * Tri-state on/off/unknown
154 */
155 enum MHD_tristate
156 {
157 _MHD_UNKNOWN = -1, /**< State is not yet checked nor set */
158 _MHD_OFF = false, /**< State is "off" / "disabled" */
159 _MHD_NO = false, /**< State is "off" / "disabled" */
160 _MHD_ON = true, /**< State is "on" / "enabled" */
161 _MHD_YES = true /**< State is "on" / "enabled" */
162 } _MHD_FIXED_ENUM;
163
164
165 /**
166 * State of the socket with respect to epoll (bitmask).
167 */
168 enum MHD_EpollState
169 {
170
171 /**
172 * The socket is not involved with a defined state in epoll() right
173 * now.
174 */
175 MHD_EPOLL_STATE_UNREADY = 0,
176
177 /**
178 * epoll() told us that data was ready for reading, and we did
179 * not consume all of it yet.
180 */
181 MHD_EPOLL_STATE_READ_READY = 1,
182
183 /**
184 * epoll() told us that space was available for writing, and we did
185 * not consume all of it yet.
186 */
187 MHD_EPOLL_STATE_WRITE_READY = 2,
188
189 /**
190 * Is this connection currently in the 'eready' EDLL?
191 */
192 MHD_EPOLL_STATE_IN_EREADY_EDLL = 4,
193
194 /**
195 * Is this connection currently in the epoll() set?
196 */
197 MHD_EPOLL_STATE_IN_EPOLL_SET = 8,
198
199 /**
200 * Is this connection currently suspended?
201 */
202 MHD_EPOLL_STATE_SUSPENDED = 16,
203
204 /**
205 * Is this connection in some error state?
206 */
207 MHD_EPOLL_STATE_ERROR = 128
208 } _MHD_FIXED_FLAGS_ENUM;
209
210
211 /**
212 * What is this connection waiting for?
213 */
214 enum MHD_ConnectionEventLoopInfo
215 {
216 /**
217 * We are waiting to be able to read.
218 */
219 MHD_EVENT_LOOP_INFO_READ = 1 << 0,
220
221 /**
222 * We are waiting to be able to write.
223 */
224 MHD_EVENT_LOOP_INFO_WRITE = 1 << 1,
225
226 /**
227 * We are waiting for the application to provide data.
228 */
229 MHD_EVENT_LOOP_INFO_PROCESS = 1 << 2,
230
231 /**
232 * Some data is ready to be processed, but more data could
233 * be read.
234 */
235 MHD_EVENT_LOOP_INFO_PROCESS_READ =
236 MHD_EVENT_LOOP_INFO_READ | MHD_EVENT_LOOP_INFO_PROCESS,
237
238 /**
239 * We are finished and are awaiting cleanup.
240 */
241 MHD_EVENT_LOOP_INFO_CLEANUP = 1 << 3
242 } _MHD_FIXED_ENUM;
243
244
245 /**
246 * Additional test value for enum MHD_FLAG to check only for MHD_ALLOW_SUSPEND_RESUME and
247 * NOT for MHD_USE_ITC.
248 */
249 #define MHD_TEST_ALLOW_SUSPEND_RESUME 8192
250
251 /**
252 * Maximum length of a nonce in digest authentication. 64(SHA-256 Hex) +
253 * 12(Timestamp Hex) + 1(NULL); hence 77 should suffice, but Opera
254 * (already) takes more (see Mantis #1633), so we've increased the
255 * value to support something longer...
256 */
257 #define MAX_CLIENT_NONCE_LENGTH 129
258
259 /**
260 * The maximum size of MHD-generated nonce when printed with hexadecimal chars.
261 *
262 * This is equal to "(32 bytes for SHA-256 (or SHA-512/256) nonce plus 6 bytes
263 * for timestamp) multiplied by two hex chars per byte".
264 * Please keep it in sync with digestauth.c
265 */
266 #if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT)
267 #define MAX_DIGEST_NONCE_LENGTH ((32 + 6) * 2)
268 #else /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */
269 #define MAX_DIGEST_NONCE_LENGTH ((16 + 6) * 2)
270 #endif /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */
271
272 /**
273 * A structure representing the internal holder of the
274 * nonce-nc map.
275 */
276 struct MHD_NonceNc
277 {
278
279 /**
280 * Nonce counter, a value that increases for each subsequent
281 * request for the same nonce. Matches the largest last received
282 * 'nc' value.
283 * This 'nc' value was already used by the client.
284 */
285 uint32_t nc;
286
287 /**
288 * Bitmask over the previous 64 nonce counter values (down to to nc-64).
289 * Used to allow out-of-order 'nc'.
290 * If bit in the bitmask is set to one, then this 'nc' value was already used
291 * by the client.
292 */
293 uint64_t nmask;
294
295 /**
296 * Nonce value
297 */
298 char nonce[MAX_DIGEST_NONCE_LENGTH + 1];
299
300 };
301
302 #ifdef HAVE_MESSAGES
303 /**
304 * fprintf()-like helper function for logging debug
305 * messages.
306 */
307 void
308 MHD_DLOG (const struct MHD_Daemon *daemon,
309 const char *format,
310 ...);
311
312 #endif
313
314
315 /**
316 * Header or footer for HTTP response.
317 */
318 struct MHD_HTTP_Res_Header
319 {
320 /**
321 * Headers are kept in a double-linked list.
322 */
323 struct MHD_HTTP_Res_Header *next;
324
325 /**
326 * Headers are kept in a double-linked list.
327 */
328 struct MHD_HTTP_Res_Header *prev;
329
330 /**
331 * The name of the header (key), without the colon.
332 */
333 char *header;
334
335 /**
336 * The length of the @a header, not including the final zero termination.
337 */
338 size_t header_size;
339
340 /**
341 * The value of the header.
342 */
343 char *value;
344
345 /**
346 * The length of the @a value, not including the final zero termination.
347 */
348 size_t value_size;
349
350 /**
351 * Type of the value.
352 */
353 enum MHD_ValueKind kind;
354
355 };
356
357
358 /**
359 * Header, footer, or cookie for HTTP request.
360 */
361 struct MHD_HTTP_Req_Header
362 {
363 /**
364 * Headers are kept in a double-linked list.
365 */
366 struct MHD_HTTP_Req_Header *next;
367
368 /**
369 * Headers are kept in a double-linked list.
370 */
371 struct MHD_HTTP_Req_Header *prev;
372
373 /**
374 * The name of the header (key), without the colon.
375 */
376 const char *header;
377
378 /**
379 * The length of the @a header, not including the final zero termination.
380 */
381 size_t header_size;
382
383 /**
384 * The value of the header.
385 */
386 const char *value;
387
388 /**
389 * The length of the @a value, not including the final zero termination.
390 */
391 size_t value_size;
392
393 /**
394 * Type of the value.
395 */
396 enum MHD_ValueKind kind;
397
398 };
399
400
401 /**
402 * Automatically assigned flags
403 */
404 enum MHD_ResponseAutoFlags
405 {
406 MHD_RAF_NO_FLAGS = 0, /**< No auto flags */
407 MHD_RAF_HAS_CONNECTION_HDR = 1 << 0, /**< Has "Connection" header */
408 MHD_RAF_HAS_CONNECTION_CLOSE = 1 << 1, /**< Has "Connection: close" */
409 MHD_RAF_HAS_TRANS_ENC_CHUNKED = 1 << 2, /**< Has "Transfer-Encoding: chunked" */
410 MHD_RAF_HAS_CONTENT_LENGTH = 1 << 3, /**< Has "Content-Length" header */
411 MHD_RAF_HAS_DATE_HDR = 1 << 4 /**< Has "Date" header */
412 } _MHD_FIXED_FLAGS_ENUM;
413
414
415 #if defined(MHD_WINSOCK_SOCKETS)
416 /**
417 * Internally used I/O vector type for use with winsock.
418 * Binary matches system "WSABUF".
419 */
420 typedef struct _MHD_W32_iovec
421 {
422 unsigned long iov_len;
423 char *iov_base;
424 } MHD_iovec_;
425 #define MHD_IOV_ELMN_MAX_SIZE ULONG_MAX
426 typedef unsigned long MHD_iov_size_;
427 #elif defined(HAVE_SENDMSG) || defined(HAVE_WRITEV)
428 /**
429 * Internally used I/O vector type for use when writev or sendmsg
430 * is available. Matches system "struct iovec".
431 */
432 typedef struct iovec MHD_iovec_;
433 #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX
434 typedef size_t MHD_iov_size_;
435 #else
436 /**
437 * Internally used I/O vector type for use when writev or sendmsg
438 * is not available.
439 */
440 typedef struct MHD_IoVec MHD_iovec_;
441 #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX
442 typedef size_t MHD_iov_size_;
443 #endif
444
445
446 struct MHD_iovec_track_
447 {
448 /**
449 * The copy of array of iovec elements.
450 * The copy of elements are updated during sending.
451 * The number of elements is not changed during lifetime.
452 */
453 MHD_iovec_ *iov;
454
455 /**
456 * The number of elements in @a iov.
457 * This value is not changed during lifetime.
458 */
459 size_t cnt;
460
461 /**
462 * The number of sent elements.
463 * At the same time, it is the index of the next (or current) element
464 * to send.
465 */
466 size_t sent;
467 };
468
469 /**
470 * Representation of a response.
471 */
472 struct MHD_Response
473 {
474
475 /**
476 * Head of double-linked list of headers to send for the response.
477 */
478 struct MHD_HTTP_Res_Header *first_header;
479
480 /**
481 * Tail of double-linked list of headers to send for the response.
482 */
483 struct MHD_HTTP_Res_Header *last_header;
484
485 /**
486 * Buffer pointing to data that we are supposed
487 * to send as a response.
488 */
489 const char *data;
490
491 /**
492 * Closure to give to the content reader @e crc
493 * and content reader free callback @e crfc.
494 */
495 void *crc_cls;
496
497 /**
498 * How do we get more data? NULL if we are
499 * given all of the data up front.
500 */
501 MHD_ContentReaderCallback crc;
502
503 /**
504 * NULL if data must not be freed, otherwise
505 * either user-specified callback or "&free".
506 */
507 MHD_ContentReaderFreeCallback crfc;
508
509 #ifdef UPGRADE_SUPPORT
510 /**
511 * Application function to call once we are done sending the headers
512 * of the response; NULL unless this is a response created with
513 * #MHD_create_response_for_upgrade().
514 */
515 MHD_UpgradeHandler upgrade_handler;
516
517 /**
518 * Closure for @e uh.
519 */
520 void *upgrade_handler_cls;
521 #endif /* UPGRADE_SUPPORT */
522
523 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
524 /**
525 * Mutex to synchronize access to @e data, @e size and
526 * @e reference_count.
527 */
528 MHD_mutex_ mutex;
529 #endif
530
531 /**
532 * The size of the response body.
533 * Set to #MHD_SIZE_UNKNOWN if size is not known.
534 */
535 uint64_t total_size;
536
537 /**
538 * At what offset in the stream is the
539 * beginning of @e data located?
540 */
541 uint64_t data_start;
542
543 /**
544 * Offset to start reading from when using @e fd.
545 */
546 uint64_t fd_off;
547
548 /**
549 * Number of bytes ready in @e data (buffer may be larger
550 * than what is filled with payload).
551 */
552 size_t data_size;
553
554 /**
555 * Size of the writable data buffer @e data.
556 */
557 size_t data_buffer_size;
558
559 /**
560 * Reference count for this response. Free once the counter hits
561 * zero.
562 */
563 unsigned int reference_count;
564
565 /**
566 * File-descriptor if this response is FD-backed.
567 */
568 int fd;
569
570 /**
571 * Flags set for the MHD response.
572 */
573 enum MHD_ResponseFlags flags;
574
575 /**
576 * Automatic flags set for the MHD response.
577 */
578 enum MHD_ResponseAutoFlags flags_auto;
579
580 /**
581 * If the @e fd is a pipe (no sendfile()).
582 */
583 bool is_pipe;
584
585 /**
586 * I/O vector used with MHD_create_response_from_iovec.
587 */
588 MHD_iovec_ *data_iov;
589
590 /**
591 * Number of elements in data_iov.
592 */
593 unsigned int data_iovcnt;
594 };
595
596
597 /**
598 * States in a state machine for a connection.
599 *
600 * The main transitions are any-state to #MHD_CONNECTION_CLOSED, any
601 * state to state+1, #MHD_CONNECTION_FOOTERS_SENT to
602 * #MHD_CONNECTION_INIT. #MHD_CONNECTION_CLOSED is the terminal state
603 * and #MHD_CONNECTION_INIT the initial state.
604 *
605 * Note that transitions for *reading* happen only after the input has
606 * been processed; transitions for *writing* happen after the
607 * respective data has been put into the write buffer (the write does
608 * not have to be completed yet). A transition to
609 * #MHD_CONNECTION_CLOSED or #MHD_CONNECTION_INIT requires the write
610 * to be complete.
611 */
612 enum MHD_CONNECTION_STATE
613 {
614 /**
615 * Connection just started (no headers received).
616 * Waiting for the line with the request type, URL and version.
617 */
618 MHD_CONNECTION_INIT = 0,
619
620 /**
621 * Part of the request line was received.
622 * Wait for complete line.
623 */
624 MHD_CONNECTION_REQ_LINE_RECEIVING = MHD_CONNECTION_INIT + 1,
625
626 /**
627 * We got the URL (and request type and version). Wait for a header line.
628 *
629 * A milestone state. No received data is processed in this state.
630 */
631 MHD_CONNECTION_REQ_LINE_RECEIVED = MHD_CONNECTION_REQ_LINE_RECEIVING + 1,
632
633 /**
634 * Receiving request headers. Wait for the rest of the headers.
635 */
636 MHD_CONNECTION_REQ_HEADERS_RECEIVING = MHD_CONNECTION_REQ_LINE_RECEIVED + 1,
637
638 /**
639 * We got the request headers. Process them.
640 */
641 MHD_CONNECTION_HEADERS_RECEIVED = MHD_CONNECTION_REQ_HEADERS_RECEIVING + 1,
642
643 /**
644 * We have processed the request headers. Call application callback.
645 */
646 MHD_CONNECTION_HEADERS_PROCESSED = MHD_CONNECTION_HEADERS_RECEIVED + 1,
647
648 /**
649 * We have processed the headers and need to send 100 CONTINUE.
650 */
651 MHD_CONNECTION_CONTINUE_SENDING = MHD_CONNECTION_HEADERS_PROCESSED + 1,
652
653 /**
654 * We have sent 100 CONTINUE (or do not need to). Read the message body.
655 */
656 MHD_CONNECTION_BODY_RECEIVING = MHD_CONNECTION_CONTINUE_SENDING + 1,
657
658 /**
659 * We got the request body.
660 *
661 * A milestone state. No received data is processed in this state.
662 */
663 MHD_CONNECTION_BODY_RECEIVED = MHD_CONNECTION_BODY_RECEIVING + 1,
664
665 /**
666 * We are reading the request footers.
667 */
668 MHD_CONNECTION_FOOTERS_RECEIVING = MHD_CONNECTION_BODY_RECEIVED + 1,
669
670 /**
671 * We received the entire footer.
672 *
673 * A milestone state. No received data is processed in this state.
674 */
675 MHD_CONNECTION_FOOTERS_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVING + 1,
676
677 /**
678 * We received the entire request.
679 * Wait for a response to be queued.
680 */
681 MHD_CONNECTION_FULL_REQ_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVED + 1,
682
683 /**
684 * Finished reading of the request and the response is ready.
685 * Switch internal logic from receiving to sending, prepare connection
686 * sending the reply and build the reply header.
687 */
688 MHD_CONNECTION_START_REPLY = MHD_CONNECTION_FULL_REQ_RECEIVED + 1,
689
690 /**
691 * We have prepared the response headers in the write buffer.
692 * Send the response headers.
693 */
694 MHD_CONNECTION_HEADERS_SENDING = MHD_CONNECTION_START_REPLY + 1,
695
696 /**
697 * We have sent the response headers. Get ready to send the body.
698 */
699 MHD_CONNECTION_HEADERS_SENT = MHD_CONNECTION_HEADERS_SENDING + 1,
700
701 /**
702 * We are waiting for the client to provide more
703 * data of a non-chunked body.
704 */
705 MHD_CONNECTION_NORMAL_BODY_UNREADY = MHD_CONNECTION_HEADERS_SENT + 1,
706
707 /**
708 * We are ready to send a part of a non-chunked body. Send it.
709 */
710 MHD_CONNECTION_NORMAL_BODY_READY = MHD_CONNECTION_NORMAL_BODY_UNREADY + 1,
711
712 /**
713 * We are waiting for the client to provide a chunk of the body.
714 */
715 MHD_CONNECTION_CHUNKED_BODY_UNREADY = MHD_CONNECTION_NORMAL_BODY_READY + 1,
716
717 /**
718 * We are ready to send a chunk.
719 */
720 MHD_CONNECTION_CHUNKED_BODY_READY = MHD_CONNECTION_CHUNKED_BODY_UNREADY + 1,
721
722 /**
723 * We have sent the chunked response body. Prepare the footers.
724 */
725 MHD_CONNECTION_CHUNKED_BODY_SENT = MHD_CONNECTION_CHUNKED_BODY_READY + 1,
726
727 /**
728 * We have prepared the response footer. Send it.
729 */
730 MHD_CONNECTION_FOOTERS_SENDING = MHD_CONNECTION_CHUNKED_BODY_SENT + 1,
731
732 /**
733 * We have sent the entire reply.
734 * Shutdown connection or restart processing to get a new request.
735 */
736 MHD_CONNECTION_FULL_REPLY_SENT = MHD_CONNECTION_FOOTERS_SENDING + 1,
737
738 /**
739 * This connection is to be closed.
740 */
741 MHD_CONNECTION_CLOSED = MHD_CONNECTION_FULL_REPLY_SENT + 1
742
743 #ifdef UPGRADE_SUPPORT
744 ,
745 /**
746 * Connection was "upgraded" and socket is now under the
747 * control of the application.
748 */
749 MHD_CONNECTION_UPGRADE = MHD_CONNECTION_CLOSED + 1
750 #endif /* UPGRADE_SUPPORT */
751
752 } _MHD_FIXED_ENUM;
753
754
755 /**
756 * States of TLS transport layer.
757 */
758 enum MHD_TLS_CONN_STATE
759 {
760 MHD_TLS_CONN_NO_TLS = 0, /**< Not a TLS connection (plain socket). */
761 MHD_TLS_CONN_INIT, /**< TLS connection is not established yet. */
762 MHD_TLS_CONN_HANDSHAKING, /**< TLS is in handshake process. */
763 MHD_TLS_CONN_CONNECTED, /**< TLS is established. */
764 MHD_TLS_CONN_WR_CLOSING, /**< Closing WR side of TLS layer. */
765 MHD_TLS_CONN_WR_CLOSED, /**< WR side of TLS layer is closed. */
766 MHD_TLS_CONN_TLS_CLOSING, /**< TLS session is terminating. */
767 MHD_TLS_CONN_TLS_CLOSED, /**< TLS session is terminated. */
768 MHD_TLS_CONN_TLS_FAILED, /**< TLS session failed. */
769 MHD_TLS_CONN_INVALID_STATE/**< Sentinel. Not a valid value. */
770 } _MHD_FIXED_ENUM;
771
772 /**
773 * Should all state transitions be printed to stderr?
774 */
775 #define DEBUG_STATES _MHD_MACRO_NO
776
777
778 #ifdef HAVE_MESSAGES
779 #if DEBUG_STATES
780 const char *
781 MHD_state_to_string (enum MHD_CONNECTION_STATE state);
782
783 #endif
784 #endif
785
786 /**
787 * Function to receive plaintext data.
788 *
789 * @param conn the connection struct
790 * @param write_to where to write received data
791 * @param max_bytes maximum number of bytes to receive
792 * @return number of bytes written to @a write_to
793 */
794 typedef ssize_t
795 (*ReceiveCallback) (struct MHD_Connection *conn,
796 void *write_to,
797 size_t max_bytes);
798
799
800 /**
801 * Function to transmit plaintext data.
802 *
803 * @param conn the connection struct
804 * @param read_from where to read data to transmit
805 * @param max_bytes maximum number of bytes to transmit
806 * @return number of bytes transmitted
807 */
808 typedef ssize_t
809 (*TransmitCallback) (struct MHD_Connection *conn,
810 const void *read_from,
811 size_t max_bytes);
812
813
814 /**
815 * Ability to use same connection for next request
816 */
817 enum MHD_ConnKeepAlive
818 {
819 /**
820 * Connection must be closed after sending response.
821 */
822 MHD_CONN_MUST_CLOSE = -1,
823
824 /**
825 * KeelAlive state is not yet determined
826 */
827 MHD_CONN_KEEPALIVE_UNKOWN = 0,
828
829 /**
830 * Connection can be used for serving next request
831 */
832 MHD_CONN_USE_KEEPALIVE = 1,
833
834 /**
835 * Connection will be upgraded
836 */
837 MHD_CONN_MUST_UPGRADE = 2
838 } _MHD_FIXED_ENUM;
839
840 enum MHD_HTTP_Version
841 {
842 /**
843 * Not a HTTP protocol or HTTP version is invalid.
844 */
845 MHD_HTTP_VER_INVALID = -1,
846
847 /**
848 * HTTP version is not yet received from the client.
849 */
850 MHD_HTTP_VER_UNKNOWN = 0,
851
852 /**
853 * HTTP version before 1.0, unsupported.
854 */
855 MHD_HTTP_VER_TOO_OLD = 1,
856
857 /**
858 * HTTP version 1.0
859 */
860 MHD_HTTP_VER_1_0 = 2,
861
862 /**
863 * HTTP version 1.1
864 */
865 MHD_HTTP_VER_1_1 = 3,
866
867 /**
868 * HTTP version 1.2-1.9, must be used as 1.1
869 */
870 MHD_HTTP_VER_1_2__1_9 = 4,
871
872 /**
873 * HTTP future version. Unsupported.
874 */
875 MHD_HTTP_VER_FUTURE = 100
876 } _MHD_FIXED_ENUM;
877
878 /**
879 * Returns boolean 'true' if HTTP version is supported by MHD
880 */
881 #define MHD_IS_HTTP_VER_SUPPORTED(ver) (MHD_HTTP_VER_1_0 <= (ver) && \
882 MHD_HTTP_VER_1_2__1_9 >= (ver))
883
884 /**
885 * Protocol should be used as HTTP/1.1 protocol.
886 *
887 * See the last paragraph of
888 * https://datatracker.ietf.org/doc/html/rfc7230#section-2.6
889 */
890 #define MHD_IS_HTTP_VER_1_1_COMPAT(ver) (MHD_HTTP_VER_1_1 == (ver) || \
891 MHD_HTTP_VER_1_2__1_9 == (ver))
892
893 /**
894 * The HTTP method.
895 *
896 * Only primary methods (specified in RFC9110) are defined here.
897 */
898 enum MHD_HTTP_Method
899 {
900 /**
901 * No request string has been received yet
902 */
903 MHD_HTTP_MTHD_NO_METHOD = 0,
904 /**
905 * HTTP method GET
906 */
907 MHD_HTTP_MTHD_GET = 1,
908 /**
909 * HTTP method HEAD
910 */
911 MHD_HTTP_MTHD_HEAD = 2,
912 /**
913 * HTTP method POST
914 */
915 MHD_HTTP_MTHD_POST = 3,
916 /**
917 * HTTP method PUT
918 */
919 MHD_HTTP_MTHD_PUT = 4,
920 /**
921 * HTTP method DELETE
922 */
923 MHD_HTTP_MTHD_DELETE = 5,
924 /**
925 * HTTP method CONNECT
926 */
927 MHD_HTTP_MTHD_CONNECT = 6,
928 /**
929 * HTTP method OPTIONS
930 */
931 MHD_HTTP_MTHD_OPTIONS = 7,
932 /**
933 * HTTP method TRACE
934 */
935 MHD_HTTP_MTHD_TRACE = 8,
936 /**
937 * Other HTTP method. Check the string value.
938 */
939 MHD_HTTP_MTHD_OTHER = 1000
940 } _MHD_FIXED_ENUM;
941
942
943 /**
944 * The request line processing data
945 */
946 struct MHD_RequestLineProcessing
947 {
948 /**
949 * The position of the next character to be processed
950 */
951 size_t proc_pos;
952 /**
953 * The number of empty lines skipped
954 */
955 unsigned int skipped_empty_lines;
956 /**
957 * The position of the start of the current/last found whitespace block,
958 * zero if not found yet.
959 */
960 size_t last_ws_start;
961 /**
962 * The position of the next character after the last known whitespace
963 * character in the current/last found whitespace block,
964 * zero if not found yet.
965 */
966 size_t last_ws_end;
967 /**
968 * The pointer to the request target.
969 * The request URI will be formed based on it.
970 */
971 char *rq_tgt;
972 /**
973 * The pointer to the first question mark in the @a rq_tgt.
974 */
975 char *rq_tgt_qmark;
976 /**
977 * The number of whitespace characters in the request URI
978 */
979 size_t num_ws_in_uri;
980 };
981
982 /**
983 * The request header processing data
984 */
985 struct MHD_HeaderProcessing
986 {
987 /**
988 * The position of the last processed character
989 */
990 size_t proc_pos;
991
992 /**
993 * The position of the first whitespace character in current contiguous
994 * whitespace block.
995 * Zero when no whitespace found or found non-whitespace character after
996 * whitespace.
997 * Must be zero, if the current character is not whitespace.
998 */
999 size_t ws_start;
1000
1001 /**
1002 * Indicates that end of the header (field) name found.
1003 * Must be false until the first colon in line is found.
1004 */
1005 bool name_end_found;
1006
1007 /**
1008 * The length of the header name.
1009 * Must be zero until the first colon in line is found.
1010 * Name always starts at zero position.
1011 */
1012 size_t name_len;
1013
1014 /**
1015 * The position of the first character of the header value.
1016 * Zero when the first character has not been found yet.
1017 */
1018 size_t value_start;
1019
1020 /**
1021 * Line starts with whitespace.
1022 * It's meaningful only for the first line, as other lines should be handled
1023 * as "folded".
1024 */
1025 bool starts_with_ws;
1026 };
1027
1028 /**
1029 * The union of request line and header processing data
1030 */
1031 union MHD_HeadersProcessing
1032 {
1033 /**
1034 * The request line processing data
1035 */
1036 struct MHD_RequestLineProcessing rq_line;
1037
1038 /**
1039 * The request header processing data
1040 */
1041 struct MHD_HeaderProcessing hdr;
1042 };
1043
1044
1045 /**
1046 * The union of text staring point and the size of the text
1047 */
1048 union MHD_StartOrSize
1049 {
1050 /**
1051 * The starting point of the text.
1052 * Valid when the text is being processed and the end of the text
1053 * is not yet determined.
1054 */
1055 const char *start;
1056 /**
1057 * The size of the text.
1058 * Valid when the text has been processed and the end of the text
1059 * is known.
1060 */
1061 size_t size;
1062 };
1063
1064 /**
1065 * Request-specific values.
1066 *
1067 * Meaningful for the current request only.
1068 */
1069 struct MHD_Request
1070 {
1071 /**
1072 * HTTP version string (i.e. http/1.1). Allocated
1073 * in pool.
1074 */
1075 const char *version;
1076
1077 /**
1078 * HTTP protocol version as enum.
1079 */
1080 enum MHD_HTTP_Version http_ver;
1081
1082 /**
1083 * Request method. Should be GET/POST/etc. Allocated in pool.
1084 */
1085 const char *method;
1086
1087 /**
1088 * The request method as enum.
1089 */
1090 enum MHD_HTTP_Method http_mthd;
1091
1092 /**
1093 * Requested URL (everything after "GET" only). Allocated
1094 * in pool.
1095 */
1096 const char *url;
1097
1098 /**
1099 * The length of the @a url in characters, not including the terminating zero.
1100 */
1101 size_t url_len;
1102
1103 /**
1104 * The original length of the request target.
1105 */
1106 size_t req_target_len;
1107
1108 /**
1109 * Requested URL (everything after "GET" only).
1110 * Depending on daemon setting either the same as @a URL or NULL.
1111 */
1112 const char *url_for_callback;
1113
1114 /**
1115 * Linked list of parsed headers.
1116 */
1117 struct MHD_HTTP_Req_Header *headers_received;
1118
1119 /**
1120 * Tail of linked list of parsed headers.
1121 */
1122 struct MHD_HTTP_Req_Header *headers_received_tail;
1123
1124 /**
1125 * Number of bytes we had in the HTTP header, set once we
1126 * pass #MHD_CONNECTION_HEADERS_RECEIVED.
1127 * This includes the request line, all request headers, the header section
1128 * terminating empty line, with all CRLF (or LF) characters.
1129 */
1130 size_t header_size;
1131
1132 /**
1133 * The union of the size of all request field lines (headers) and
1134 * the starting point of the first request field line (the first header).
1135 * Until #MHD_CONNECTION_HEADERS_RECEIVED the @a start member is valid,
1136 * staring with #MHD_CONNECTION_HEADERS_RECEIVED the @a size member is valid.
1137 * The size includes CRLF (or LR) characters, but does not include
1138 * the terminating empty line.
1139 */
1140 union MHD_StartOrSize field_lines;
1141
1142 /**
1143 * How many more bytes of the body do we expect
1144 * to read? #MHD_SIZE_UNKNOWN for unknown.
1145 */
1146 uint64_t remaining_upload_size;
1147
1148 /**
1149 * Are we receiving with chunked encoding?
1150 * This will be set to #MHD_YES after we parse the headers and
1151 * are processing the body with chunks.
1152 * After we are done with the body and we are processing the footers;
1153 * once the footers are also done, this will be set to #MHD_NO again
1154 * (before the final call to the handler).
1155 * It is used only for requests, chunked encoding for response is
1156 * indicated by @a rp_props.
1157 */
1158 bool have_chunked_upload;
1159
1160 /**
1161 * If we are receiving with chunked encoding, where are we right
1162 * now?
1163 * Set to 0 if we are waiting to receive the chunk size;
1164 * otherwise, this is the size of the current chunk.
1165 * A value of zero is also used when we're at the end of the chunks.
1166 */
1167 uint64_t current_chunk_size;
1168
1169 /**
1170 * If we are receiving with chunked encoding, where are we currently
1171 * with respect to the current chunk (at what offset / position)?
1172 */
1173 uint64_t current_chunk_offset;
1174
1175 /**
1176 * Indicate that some of the upload payload data (from the currently
1177 * processed chunk for chunked uploads) have been processed by the
1178 * last call of the connection handler.
1179 * If any data have been processed, but some data left in the buffer
1180 * for further processing, then MHD will use zero timeout before the
1181 * next data processing round. This allow the application handler
1182 * process the data by the fixed portions or other way suitable for
1183 * application developer.
1184 * If no data have been processed, than MHD will wait for more data
1185 * to come (as it makes no sense to call the same connection handler
1186 * under the same conditions). However this is dangerous as if buffer
1187 * is completely used then connection is aborted. Connection
1188 * suspension should be used in such case.
1189 */
1190 bool some_payload_processed;
1191
1192 /**
1193 * We allow the main application to associate some pointer with the
1194 * HTTP request, which is passed to each #MHD_AccessHandlerCallback
1195 * and some other API calls. Here is where we store it. (MHD does
1196 * not know or care what it is).
1197 */
1198 void *client_context;
1199
1200 /**
1201 * Did we ever call the "default_handler" on this request?
1202 * This flag determines if we have called the #MHD_OPTION_NOTIFY_COMPLETED
1203 * handler when the request finishes.
1204 */
1205 bool client_aware;
1206
1207 #ifdef BAUTH_SUPPORT
1208 /**
1209 * Basic Authorization parameters.
1210 * The result of Basic Authorization header parsing.
1211 * Allocated in the connection's pool.
1212 */
1213 const struct MHD_RqBAuth *bauth;
1214
1215 /**
1216 * Set to true if current request headers are checked for Basic Authorization
1217 */
1218 bool bauth_tried;
1219 #endif /* BAUTH_SUPPORT */
1220 #ifdef DAUTH_SUPPORT
1221 /**
1222 * Digest Authorization parameters.
1223 * The result of Digest Authorization header parsing.
1224 * Allocated in the connection's pool.
1225 */
1226 const struct MHD_RqDAuth *dauth;
1227
1228 /**
1229 * Set to true if current request headers are checked for Digest Authorization
1230 */
1231 bool dauth_tried;
1232 #endif /* DAUTH_SUPPORT */
1233 /**
1234 * Number of bare CR characters that were replaced with space characters
1235 * in the request line or in the headers (field lines).
1236 */
1237 size_t num_cr_sp_replaced;
1238
1239 /**
1240 * The number of header lines skipped because they have no colon
1241 */
1242 size_t skipped_broken_lines;
1243
1244 /**
1245 * The data of the request line / request headers processing
1246 */
1247 union MHD_HeadersProcessing hdrs;
1248 };
1249
1250
1251 /**
1252 * Reply-specific properties.
1253 */
1254 struct MHD_Reply_Properties
1255 {
1256 #ifdef _DEBUG
1257 bool set; /**< Indicates that other members are set and valid */
1258 #endif /* _DEBUG */
1259 bool use_reply_body_headers; /**< Use reply body-specific headers */
1260 bool send_reply_body; /**< Send reply body (can be zero-sized) */
1261 bool chunked; /**< Use chunked encoding for reply */
1262 };
1263
1264 #if defined(_MHD_HAVE_SENDFILE)
1265 enum MHD_resp_sender_
1266 {
1267 MHD_resp_sender_std = 0,
1268 MHD_resp_sender_sendfile
1269 };
1270 #endif /* _MHD_HAVE_SENDFILE */
1271
1272 /**
1273 * Reply-specific values.
1274 *
1275 * Meaningful for the current reply only.
1276 */
1277 struct MHD_Reply
1278 {
1279 /**
1280 * Response to transmit (initially NULL).
1281 */
1282 struct MHD_Response *response;
1283
1284 /**
1285 * HTTP response code. Only valid if response object
1286 * is already set.
1287 */
1288 unsigned int responseCode;
1289
1290 /**
1291 * The "ICY" response.
1292 * Reply begins with the SHOUTcast "ICY" line instead of "HTTP".
1293 */
1294 bool responseIcy;
1295
1296 /**
1297 * Current write position in the actual response
1298 * (excluding headers, content only; should be 0
1299 * while sending headers).
1300 */
1301 uint64_t rsp_write_position;
1302
1303 /**
1304 * The copy of iov response.
1305 * Valid if iovec response is used.
1306 * Updated during send.
1307 * Members are allocated in the pool.
1308 */
1309 struct MHD_iovec_track_ resp_iov;
1310
1311 #if defined(_MHD_HAVE_SENDFILE)
1312 enum MHD_resp_sender_ resp_sender;
1313 #endif /* _MHD_HAVE_SENDFILE */
1314
1315 /**
1316 * Reply-specific properties
1317 */
1318 struct MHD_Reply_Properties props;
1319 };
1320
1321 /**
1322 * State kept for each HTTP request.
1323 */
1324 struct MHD_Connection
1325 {
1326
1327 #ifdef EPOLL_SUPPORT
1328 /**
1329 * Next pointer for the EDLL listing connections that are epoll-ready.
1330 */
1331 struct MHD_Connection *nextE;
1332
1333 /**
1334 * Previous pointer for the EDLL listing connections that are epoll-ready.
1335 */
1336 struct MHD_Connection *prevE;
1337 #endif
1338
1339 /**
1340 * Next pointer for the DLL describing our IO state.
1341 */
1342 struct MHD_Connection *next;
1343
1344 /**
1345 * Previous pointer for the DLL describing our IO state.
1346 */
1347 struct MHD_Connection *prev;
1348
1349 /**
1350 * Next pointer for the XDLL organizing connections by timeout.
1351 * This DLL can be either the
1352 * 'manual_timeout_head/manual_timeout_tail' or the
1353 * 'normal_timeout_head/normal_timeout_tail', depending on whether a
1354 * custom timeout is set for the connection.
1355 */
1356 struct MHD_Connection *nextX;
1357
1358 /**
1359 * Previous pointer for the XDLL organizing connections by timeout.
1360 */
1361 struct MHD_Connection *prevX;
1362
1363 /**
1364 * Reference to the MHD_Daemon struct.
1365 */
1366 struct MHD_Daemon *daemon;
1367
1368 /**
1369 * Request-specific data
1370 */
1371 struct MHD_Request rq;
1372
1373 /**
1374 * Reply-specific data
1375 */
1376 struct MHD_Reply rp;
1377
1378 /**
1379 * The memory pool is created whenever we first read from the TCP
1380 * stream and destroyed at the end of each request (and re-created
1381 * for the next request). In the meantime, this pointer is NULL.
1382 * The pool is used for all connection-related data except for the
1383 * response (which maybe shared between connections) and the IP
1384 * address (which persists across individual requests).
1385 */
1386 struct MemoryPool *pool;
1387
1388 /**
1389 * We allow the main application to associate some pointer with the
1390 * TCP connection (which may span multiple HTTP requests). Here is
1391 * where we store it. (MHD does not know or care what it is).
1392 * The location is given to the #MHD_NotifyConnectionCallback and
1393 * also accessible via #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
1394 */
1395 void *socket_context;
1396
1397 /**
1398 * Close connection after sending response?
1399 * Functions may change value from "Unknown" or "KeepAlive" to "Must close",
1400 * but no functions reset value "Must Close" to any other value.
1401 */
1402 enum MHD_ConnKeepAlive keepalive;
1403
1404 /**
1405 * Buffer for reading requests. Allocated in pool. Actually one
1406 * byte larger than @e read_buffer_size (if non-NULL) to allow for
1407 * 0-termination.
1408 */
1409 char *read_buffer;
1410
1411 /**
1412 * Buffer for writing response (headers only). Allocated
1413 * in pool.
1414 */
1415 char *write_buffer;
1416
1417 /**
1418 * Foreign address (of length @e addr_len). MALLOCED (not
1419 * in pool!).
1420 */
1421 struct sockaddr_storage *addr;
1422
1423 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
1424 /**
1425 * Thread handle for this connection (if we are using
1426 * one thread per connection).
1427 */
1428 MHD_thread_handle_ID_ tid;
1429 #endif
1430
1431 /**
1432 * Size of @e read_buffer (in bytes).
1433 * This value indicates how many bytes we're willing to read
1434 * into the buffer.
1435 */
1436 size_t read_buffer_size;
1437
1438 /**
1439 * Position where we currently append data in @e read_buffer (the
1440 * next char after the last valid position).
1441 */
1442 size_t read_buffer_offset;
1443
1444 /**
1445 * Size of @e write_buffer (in bytes).
1446 */
1447 size_t write_buffer_size;
1448
1449 /**
1450 * Offset where we are with sending from @e write_buffer.
1451 */
1452 size_t write_buffer_send_offset;
1453
1454 /**
1455 * Last valid location in write_buffer (where do we
1456 * append and up to where is it safe to send?)
1457 */
1458 size_t write_buffer_append_offset;
1459
1460 /**
1461 * Position in the 100 CONTINUE message that
1462 * we need to send when receiving http 1.1 requests.
1463 */
1464 size_t continue_message_write_offset;
1465
1466 /**
1467 * Length of the foreign address.
1468 */
1469 socklen_t addr_len;
1470
1471 /**
1472 * Last time this connection had any activity
1473 * (reading or writing).
1474 */
1475 uint64_t last_activity;
1476
1477 /**
1478 * After how many milliseconds of inactivity should
1479 * this connection time out?
1480 * Zero for no timeout.
1481 */
1482 uint64_t connection_timeout_ms;
1483
1484 /**
1485 * Socket for this connection. Set to #MHD_INVALID_SOCKET if
1486 * this connection has died (daemon should clean
1487 * up in that case).
1488 */
1489 MHD_socket socket_fd;
1490
1491 /**
1492 * true if @e socket_fd is not TCP/IP (a UNIX domain socket, a pipe),
1493 * false (TCP/IP) otherwise.
1494 */
1495 enum MHD_tristate is_nonip;
1496
1497 /**
1498 * true if #socket_fd is non-blocking, false otherwise.
1499 */
1500 bool sk_nonblck;
1501
1502 /**
1503 * true if connection socket has set SIGPIPE suppression
1504 */
1505 bool sk_spipe_suppress;
1506
1507 /**
1508 * Tracks TCP_CORK / TCP_NOPUSH of the connection socket.
1509 */
1510 enum MHD_tristate sk_corked;
1511
1512 /**
1513 * Tracks TCP_NODELAY state of the connection socket.
1514 */
1515 enum MHD_tristate sk_nodelay;
1516
1517 /**
1518 * Has this socket been closed for reading (i.e. other side closed
1519 * the connection)? If so, we must completely close the connection
1520 * once we are done sending our response (and stop trying to read
1521 * from this socket).
1522 */
1523 bool read_closed;
1524
1525 /**
1526 * Some error happens during processing the connection therefore this
1527 * connection must be closed.
1528 * The error may come from the client side (like wrong request format),
1529 * from the application side (like data callback returned error), or from
1530 * the OS side (like out-of-memory).
1531 */
1532 bool stop_with_error;
1533
1534 /**
1535 * Response queued early, before the request is fully processed,
1536 * the client upload is rejected.
1537 * The connection cannot be reused for additional requests as the current
1538 * request is incompletely read and it is unclear where is the initial
1539 * byte of the next request.
1540 */
1541 bool discard_request;
1542
1543 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
1544 /**
1545 * Set to `true` if the thread has been joined.
1546 */
1547 bool thread_joined;
1548 #endif
1549
1550 /**
1551 * Are we currently inside the "idle" handler (to avoid recursively
1552 * invoking it).
1553 */
1554 bool in_idle;
1555
1556 /**
1557 * Connection is in the cleanup DL-linked list.
1558 */
1559 bool in_cleanup;
1560
1561 #ifdef EPOLL_SUPPORT
1562 /**
1563 * What is the state of this socket in relation to epoll?
1564 */
1565 enum MHD_EpollState epoll_state;
1566 #endif
1567
1568 /**
1569 * State in the FSM for this connection.
1570 */
1571 enum MHD_CONNECTION_STATE state;
1572
1573 /**
1574 * What is this connection waiting for?
1575 */
1576 enum MHD_ConnectionEventLoopInfo event_loop_info;
1577
1578 /**
1579 * Function used for reading HTTP request stream.
1580 */
1581 ReceiveCallback recv_cls;
1582
1583 #ifdef UPGRADE_SUPPORT
1584 /**
1585 * If this connection was upgraded, this points to
1586 * the upgrade response details such that the
1587 * #thread_main_connection_upgrade()-logic can perform the
1588 * bi-directional forwarding.
1589 */
1590 struct MHD_UpgradeResponseHandle *urh;
1591 #endif /* UPGRADE_SUPPORT */
1592
1593 #ifdef HTTPS_SUPPORT
1594
1595 /**
1596 * State required for HTTPS/SSL/TLS support.
1597 */
1598 gnutls_session_t tls_session;
1599
1600 /**
1601 * State of connection's TLS layer
1602 */
1603 enum MHD_TLS_CONN_STATE tls_state;
1604
1605 /**
1606 * Could it be that we are ready to read due to TLS buffers
1607 * even though the socket is not?
1608 */
1609 bool tls_read_ready;
1610 #endif /* HTTPS_SUPPORT */
1611
1612 /**
1613 * Is the connection suspended?
1614 */
1615 bool suspended;
1616
1617 /**
1618 * Are we currently in the #MHD_AccessHandlerCallback
1619 * for this connection (and thus eligible to receive
1620 * calls to #MHD_queue_response()?).
1621 */
1622 bool in_access_handler;
1623
1624 /**
1625 * Is the connection wanting to resume?
1626 */
1627 volatile bool resuming;
1628
1629 /**
1630 * Special member to be returned by #MHD_get_connection_info()
1631 */
1632 union MHD_ConnectionInfo connection_info_dummy;
1633 };
1634
1635
1636 #ifdef UPGRADE_SUPPORT
1637 /**
1638 * Buffer we use for upgrade response handling in the unlikely
1639 * case where the memory pool was so small it had no buffer
1640 * capacity left. Note that we don't expect to _ever_ use this
1641 * buffer, so it's mostly wasted memory (except that it allows
1642 * us to handle a tricky error condition nicely). So no need to
1643 * make this one big. Applications that want to perform well
1644 * should just pick an adequate size for the memory pools.
1645 */
1646 #define RESERVE_EBUF_SIZE 8
1647
1648 /**
1649 * Context we pass to epoll() for each of the two sockets
1650 * of a `struct MHD_UpgradeResponseHandle`. We need to do
1651 * this so we can distinguish the two sockets when epoll()
1652 * gives us event notifications.
1653 */
1654 struct UpgradeEpollHandle
1655 {
1656 /**
1657 * Reference to the overall response handle this struct is
1658 * included within.
1659 */
1660 struct MHD_UpgradeResponseHandle *urh;
1661
1662 /**
1663 * The socket this event is kind-of about. Note that this is NOT
1664 * necessarily the socket we are polling on, as for when we read
1665 * from TLS, we epoll() on the connection's socket
1666 * (`urh->connection->socket_fd`), while this then the application's
1667 * socket (where the application will read from). Nevertheless, for
1668 * the application to read, we need to first read from TLS, hence
1669 * the two are related.
1670 *
1671 * Similarly, for writing to TLS, this epoll() will be on the
1672 * connection's `socket_fd`, and this will merely be the FD which
1673 * the application would write to. Hence this struct must always be
1674 * interpreted based on which field in `struct
1675 * MHD_UpgradeResponseHandle` it is (`app` or `mhd`).
1676 */
1677 MHD_socket socket;
1678
1679 /**
1680 * IO-state of the @e socket (or the connection's `socket_fd`).
1681 */
1682 enum MHD_EpollState celi;
1683
1684 };
1685
1686
1687 /**
1688 * Handle given to the application to manage special
1689 * actions relating to MHD responses that "upgrade"
1690 * the HTTP protocol (i.e. to WebSockets).
1691 */
1692 struct MHD_UpgradeResponseHandle
1693 {
1694 /**
1695 * The connection for which this is an upgrade handle. Note that
1696 * because a response may be shared over many connections, this may
1697 * not be the only upgrade handle for the response of this connection.
1698 */
1699 struct MHD_Connection *connection;
1700
1701 #ifdef HTTPS_SUPPORT
1702 /**
1703 * Kept in a DLL per daemon.
1704 */
1705 struct MHD_UpgradeResponseHandle *next;
1706
1707 /**
1708 * Kept in a DLL per daemon.
1709 */
1710 struct MHD_UpgradeResponseHandle *prev;
1711
1712 #ifdef EPOLL_SUPPORT
1713 /**
1714 * Next pointer for the EDLL listing urhs that are epoll-ready.
1715 */
1716 struct MHD_UpgradeResponseHandle *nextE;
1717
1718 /**
1719 * Previous pointer for the EDLL listing urhs that are epoll-ready.
1720 */
1721 struct MHD_UpgradeResponseHandle *prevE;
1722
1723 /**
1724 * Specifies whether urh already in EDLL list of ready connections.
1725 */
1726 bool in_eready_list;
1727 #endif
1728
1729 /**
1730 * The buffer for receiving data from TLS to
1731 * be passed to the application. Contains @e in_buffer_size
1732 * bytes (unless @e in_buffer_size is zero). Do not free!
1733 */
1734 char *in_buffer;
1735
1736 /**
1737 * The buffer for receiving data from the application to
1738 * be passed to TLS. Contains @e out_buffer_size
1739 * bytes (unless @e out_buffer_size is zero). Do not free!
1740 */
1741 char *out_buffer;
1742
1743 /**
1744 * Size of the @e in_buffer.
1745 * Set to 0 if the TLS connection went down for reading or socketpair
1746 * went down for writing.
1747 */
1748 size_t in_buffer_size;
1749
1750 /**
1751 * Size of the @e out_buffer.
1752 * Set to 0 if the TLS connection went down for writing or socketpair
1753 * went down for reading.
1754 */
1755 size_t out_buffer_size;
1756
1757 /**
1758 * Number of bytes actually in use in the @e in_buffer. Can be larger
1759 * than @e in_buffer_size if and only if @a in_buffer_size is zero and
1760 * we still have bytes that can be forwarded.
1761 * Reset to zero if all data was forwarded to socketpair or
1762 * if socketpair went down for writing.
1763 */
1764 size_t in_buffer_used;
1765
1766 /**
1767 * Number of bytes actually in use in the @e out_buffer. Can be larger
1768 * than @e out_buffer_size if and only if @a out_buffer_size is zero and
1769 * we still have bytes that can be forwarded.
1770 * Reset to zero if all data was forwarded to TLS connection or
1771 * if TLS connection went down for writing.
1772 */
1773 size_t out_buffer_used;
1774
1775 /**
1776 * The socket we gave to the application (r/w).
1777 */
1778 struct UpgradeEpollHandle app;
1779
1780 /**
1781 * If @a app_sock was a socketpair, our end of it, otherwise
1782 * #MHD_INVALID_SOCKET; (r/w).
1783 */
1784 struct UpgradeEpollHandle mhd;
1785
1786 /**
1787 * Emergency IO buffer we use in case the memory pool has literally
1788 * nothing left.
1789 */
1790 char e_buf[RESERVE_EBUF_SIZE];
1791
1792 #endif /* HTTPS_SUPPORT */
1793
1794 /**
1795 * Set to true after the application finished with the socket
1796 * by #MHD_UPGRADE_ACTION_CLOSE.
1797 *
1798 * When BOTH @e was_closed (changed by command from application)
1799 * AND @e clean_ready (changed internally by MHD) are set to
1800 * #MHD_YES, function #MHD_resume_connection() will move this
1801 * connection to cleanup list.
1802 * @remark This flag could be changed from any thread.
1803 */
1804 volatile bool was_closed;
1805
1806 /**
1807 * Set to true if connection is ready for cleanup.
1808 *
1809 * In TLS mode functions #MHD_connection_finish_forward_() must
1810 * be called before setting this flag to true.
1811 *
1812 * In thread-per-connection mode, true in this flag means
1813 * that connection's thread exited or about to exit and will
1814 * not use MHD_Connection::urh data anymore.
1815 *
1816 * In any mode true in this flag also means that
1817 * MHD_Connection::urh data will not be used for socketpair
1818 * forwarding and forwarding itself is finished.
1819 *
1820 * When BOTH @e was_closed (changed by command from application)
1821 * AND @e clean_ready (changed internally by MHD) are set to
1822 * true, function #MHD_resume_connection() will move this
1823 * connection to cleanup list.
1824 * @remark This flag could be changed from thread that process
1825 * connection's recv(), send() and response.
1826 */
1827 volatile bool clean_ready;
1828 };
1829 #endif /* UPGRADE_SUPPORT */
1830
1831
1832 /**
1833 * Signature of function called to log URI accesses.
1834 *
1835 * @param cls closure
1836 * @param uri uri being accessed
1837 * @param con connection handle
1838 * @return new closure
1839 */
1840 typedef void *
1841 (*LogCallback)(void *cls,
1842 const char *uri,
1843 struct MHD_Connection *con);
1844
1845 /**
1846 * Signature of function called to unescape URIs. See also
1847 * #MHD_http_unescape().
1848 *
1849 * @param cls closure
1850 * @param conn connection handle
1851 * @param uri 0-terminated string to unescape (should be updated)
1852 * @return length of the resulting string
1853 */
1854 typedef size_t
1855 (*UnescapeCallback)(void *cls,
1856 struct MHD_Connection *conn,
1857 char *uri);
1858
1859
1860 /**
1861 * State kept for each MHD daemon. All connections are kept in two
1862 * doubly-linked lists. The first one reflects the state of the
1863 * connection in terms of what operations we are waiting for (read,
1864 * write, locally blocked, cleanup) whereas the second is about its
1865 * timeout state (default or custom).
1866 */
1867 struct MHD_Daemon
1868 {
1869
1870 /**
1871 * Callback function for all requests.
1872 */
1873 MHD_AccessHandlerCallback default_handler;
1874
1875 /**
1876 * Closure argument to default_handler.
1877 */
1878 void *default_handler_cls;
1879
1880 /**
1881 * Daemon's flags (bitfield).
1882 *
1883 * @remark Keep this member after pointer value to keep it
1884 * properly aligned as it will be used as member of union MHD_DaemonInfo.
1885 */
1886 enum MHD_FLAG options;
1887
1888 /**
1889 * Head of doubly-linked list of new, externally added connections.
1890 */
1891 struct MHD_Connection *new_connections_head;
1892
1893 /**
1894 * Tail of doubly-linked list of new, externally added connections.
1895 */
1896 struct MHD_Connection *new_connections_tail;
1897
1898 /**
1899 * Head of doubly-linked list of our current, active connections.
1900 */
1901 struct MHD_Connection *connections_head;
1902
1903 /**
1904 * Tail of doubly-linked list of our current, active connections.
1905 */
1906 struct MHD_Connection *connections_tail;
1907
1908 /**
1909 * Head of doubly-linked list of our current but suspended connections.
1910 */
1911 struct MHD_Connection *suspended_connections_head;
1912
1913 /**
1914 * Tail of doubly-linked list of our current but suspended connections.
1915 */
1916 struct MHD_Connection *suspended_connections_tail;
1917
1918 /**
1919 * Head of doubly-linked list of connections to clean up.
1920 */
1921 struct MHD_Connection *cleanup_head;
1922
1923 /**
1924 * Tail of doubly-linked list of connections to clean up.
1925 */
1926 struct MHD_Connection *cleanup_tail;
1927
1928 /**
1929 * _MHD_YES if the @e listen_fd socket is a UNIX domain socket.
1930 */
1931 enum MHD_tristate listen_is_unix;
1932
1933 #ifdef EPOLL_SUPPORT
1934 /**
1935 * Head of EDLL of connections ready for processing (in epoll mode).
1936 */
1937 struct MHD_Connection *eready_head;
1938
1939 /**
1940 * Tail of EDLL of connections ready for processing (in epoll mode)
1941 */
1942 struct MHD_Connection *eready_tail;
1943
1944 /**
1945 * File descriptor associated with our epoll loop.
1946 *
1947 * @remark Keep this member after pointer value to keep it
1948 * properly aligned as it will be used as member of union MHD_DaemonInfo.
1949 */
1950 int epoll_fd;
1951
1952 /**
1953 * true if the @e listen_fd socket is in the 'epoll' set,
1954 * false if not.
1955 */
1956 bool listen_socket_in_epoll;
1957
1958 #ifdef UPGRADE_SUPPORT
1959 #ifdef HTTPS_SUPPORT
1960 /**
1961 * File descriptor associated with the #run_epoll_for_upgrade() loop.
1962 * Only available if #MHD_USE_HTTPS_EPOLL_UPGRADE is set.
1963 */
1964 int epoll_upgrade_fd;
1965
1966 /**
1967 * true if @e epoll_upgrade_fd is in the 'epoll' set,
1968 * false if not.
1969 */
1970 bool upgrade_fd_in_epoll;
1971 #endif /* HTTPS_SUPPORT */
1972
1973 /**
1974 * Head of EDLL of upgraded connections ready for processing (in epoll mode).
1975 */
1976 struct MHD_UpgradeResponseHandle *eready_urh_head;
1977
1978 /**
1979 * Tail of EDLL of upgraded connections ready for processing (in epoll mode)
1980 */
1981 struct MHD_UpgradeResponseHandle *eready_urh_tail;
1982 #endif /* UPGRADE_SUPPORT */
1983 #endif /* EPOLL_SUPPORT */
1984
1985 /**
1986 * Head of the XDLL of ALL connections with a default ('normal')
1987 * timeout, sorted by timeout (earliest at the tail, most recently
1988 * used connection at the head). MHD can just look at the tail of
1989 * this list to determine the timeout for all of its elements;
1990 * whenever there is an event of a connection, the connection is
1991 * moved back to the tail of the list.
1992 *
1993 * All connections by default start in this list; if a custom
1994 * timeout that does not match @e connection_timeout_ms is set, they
1995 * are moved to the @e manual_timeout_head-XDLL.
1996 * Not used in MHD_USE_THREAD_PER_CONNECTION mode as each thread
1997 * needs only one connection-specific timeout.
1998 */
1999 struct MHD_Connection *normal_timeout_head;
2000
2001 /**
2002 * Tail of the XDLL of ALL connections with a default timeout,
2003 * sorted by timeout (earliest timeout at the tail).
2004 * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
2005 */
2006 struct MHD_Connection *normal_timeout_tail;
2007
2008 /**
2009 * Head of the XDLL of ALL connections with a non-default/custom
2010 * timeout, unsorted. MHD will do a O(n) scan over this list to
2011 * determine the current timeout.
2012 * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
2013 */
2014 struct MHD_Connection *manual_timeout_head;
2015
2016 /**
2017 * Tail of the XDLL of ALL connections with a non-default/custom
2018 * timeout, unsorted.
2019 * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
2020 */
2021 struct MHD_Connection *manual_timeout_tail;
2022
2023 /**
2024 * Function to call to check if we should accept or reject an
2025 * incoming request. May be NULL.
2026 */
2027 MHD_AcceptPolicyCallback apc;
2028
2029 /**
2030 * Closure argument to apc.
2031 */
2032 void *apc_cls;
2033
2034 /**
2035 * Function to call when we are done processing
2036 * a particular request. May be NULL.
2037 */
2038 MHD_RequestCompletedCallback notify_completed;
2039
2040 /**
2041 * Closure argument to @e notify_completed.
2042 */
2043 void *notify_completed_cls;
2044
2045 /**
2046 * Function to call when we are starting/stopping
2047 * a connection. May be NULL.
2048 */
2049 MHD_NotifyConnectionCallback notify_connection;
2050
2051 /**
2052 * Closure argument to @e notify_connection.
2053 */
2054 void *notify_connection_cls;
2055
2056 /**
2057 * Function to call with the full URI at the
2058 * beginning of request processing. May be NULL.
2059 * <p>
2060 * Returns the initial pointer to internal state
2061 * kept by the client for the request.
2062 */
2063 LogCallback uri_log_callback;
2064
2065 /**
2066 * Closure argument to @e uri_log_callback.
2067 */
2068 void *uri_log_callback_cls;
2069
2070 /**
2071 * Function to call when we unescape escape sequences.
2072 */
2073 UnescapeCallback unescape_callback;
2074
2075 /**
2076 * Closure for @e unescape_callback.
2077 */
2078 void *unescape_callback_cls;
2079
2080 /**
2081 * Listen port.
2082 *
2083 * @remark Keep this member after pointer value to keep it
2084 * properly aligned as it will be used as member of union MHD_DaemonInfo.
2085 */
2086 uint16_t port;
2087
2088 #ifdef HAVE_MESSAGES
2089 /**
2090 * Function for logging error messages (if we
2091 * support error reporting).
2092 */
2093 MHD_LogCallback custom_error_log;
2094
2095 /**
2096 * Closure argument to @e custom_error_log.
2097 */
2098 void *custom_error_log_cls;
2099 #endif
2100
2101 /**
2102 * Pointer to master daemon (NULL if this is the master)
2103 */
2104 struct MHD_Daemon *master;
2105
2106 /**
2107 * Listen socket.
2108 *
2109 * @remark Keep this member after pointer value to keep it
2110 * properly aligned as it will be used as member of union MHD_DaemonInfo.
2111 */
2112 MHD_socket listen_fd;
2113
2114 /**
2115 * Listen socket is non-blocking.
2116 */
2117 bool listen_nonblk;
2118
2119 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
2120 /**
2121 * Worker daemons (one per thread)
2122 */
2123 struct MHD_Daemon *worker_pool;
2124 #endif
2125
2126 /**
2127 * Table storing number of connections per IP
2128 */
2129 void *per_ip_connection_count;
2130
2131 /**
2132 * Number of active parallel connections.
2133 *
2134 * @remark Keep this member after pointer value to keep it
2135 * properly aligned as it will be used as member of union MHD_DaemonInfo.
2136 */
2137 unsigned int connections;
2138
2139 /**
2140 * Size of the per-connection memory pools.
2141 */
2142 size_t pool_size;
2143
2144 /**
2145 * Increment for growth of the per-connection memory pools.
2146 */
2147 size_t pool_increment;
2148
2149 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
2150 /**
2151 * Size of threads created by MHD.
2152 */
2153 size_t thread_stack_size;
2154
2155 /**
2156 * Number of worker daemons
2157 */
2158 unsigned int worker_pool_size;
2159
2160 /**
2161 * The select thread handle (if we have internal select)
2162 */
2163 MHD_thread_handle_ID_ tid;
2164
2165 /**
2166 * Mutex for per-IP connection counts.
2167 */
2168 MHD_mutex_ per_ip_connection_mutex;
2169
2170 /**
2171 * Mutex for (modifying) access to the "cleanup", "normal_timeout" and
2172 * "manual_timeout" DLLs.
2173 */
2174 MHD_mutex_ cleanup_connection_mutex;
2175
2176 /**
2177 * Mutex for any access to the "new connections" DL-list.
2178 */
2179 MHD_mutex_ new_connections_mutex;
2180 #endif
2181
2182 /**
2183 * Our #MHD_OPTION_SERVER_INSANITY level, bits indicating
2184 * which sanity checks are off.
2185 */
2186 enum MHD_DisableSanityCheck insanity_level;
2187
2188 /**
2189 * Whether to allow/disallow/ignore reuse of listening address.
2190 * The semantics is the following:
2191 * 0: ignore (user did not ask for neither allow/disallow, use SO_REUSEADDR
2192 * except W32)
2193 * >0: allow (use SO_REUSEPORT on most platforms, SO_REUSEADDR on Windows)
2194 * <0: disallow (mostly no action, SO_EXCLUSIVEADDRUSE on Windows or SO_EXCLBIND
2195 * on Solaris)
2196 */
2197 int listening_address_reuse;
2198
2199
2200 /**
2201 * Inter-thread communication channel (also used to unblock
2202 * select() in non-threaded code).
2203 */
2204 struct MHD_itc_ itc;
2205
2206 /**
2207 * Are we shutting down?
2208 */
2209 volatile bool shutdown;
2210
2211 /**
2212 * Has this daemon been quiesced via #MHD_quiesce_daemon()?
2213 * If so, we should no longer use the @e listen_fd (including
2214 * removing it from the @e epoll_fd when possible).
2215 */
2216 volatile bool was_quiesced;
2217
2218 /**
2219 * Did we hit some system or process-wide resource limit while
2220 * trying to accept() the last time? If so, we don't accept new
2221 * connections until we close an existing one. This effectively
2222 * temporarily lowers the "connection_limit" to the current
2223 * number of connections.
2224 */
2225 bool at_limit;
2226
2227 /*
2228 * Do we need to process resuming connections?
2229 */
2230 volatile bool resuming;
2231
2232 /**
2233 * Indicate that new connections in @e new_connections_head list
2234 * need to be processed.
2235 */
2236 volatile bool have_new;
2237
2238 /**
2239 * 'True' if some data is already waiting to be processed.
2240 * If set to 'true' - zero timeout for select()/poll*()
2241 * is used.
2242 * Should be reset each time before processing connections
2243 * and raised by any connection which require additional
2244 * immediately processing (application does not provide
2245 * data for response, data waiting in TLS buffers etc.)
2246 */
2247 bool data_already_pending;
2248
2249 /**
2250 * Limit on the number of parallel connections.
2251 */
2252 unsigned int connection_limit;
2253
2254 /**
2255 * After how many milliseconds of inactivity should
2256 * this connection time out?
2257 * Zero for no timeout.
2258 */
2259 uint64_t connection_timeout_ms;
2260
2261 /**
2262 * Maximum number of connections per IP, or 0 for
2263 * unlimited.
2264 */
2265 unsigned int per_ip_connection_limit;
2266
2267 /**
2268 * The strictness level for parsing of incoming data.
2269 * @see #MHD_OPTION_CLIENT_DISCIPLINE_LVL
2270 */
2271 int client_discipline;
2272
2273 /**
2274 * Allow binary zero in the URI (excluding query part).
2275 * When set to '1' then @a url parameter must be NULL, when binary zero
2276 * is used in URI.
2277 */
2278 int allow_bzero_in_url;
2279
2280 #ifdef HAS_FD_SETSIZE_OVERRIDABLE
2281 /**
2282 * The value of FD_SETSIZE used by the daemon.
2283 * For external sockets polling this is the value provided by the application
2284 * via MHD_OPTION_APP_FD_SETSIZE or current FD_SETSIZE value.
2285 * For internal threads modes this is always current FD_SETSIZE value.
2286 */
2287 int fdset_size;
2288
2289 /**
2290 * Indicates whether @a fdset_size value was set by application.
2291 * 'false' if default value is used.
2292 */
2293 bool fdset_size_set_by_app;
2294 #endif /* HAS_FD_SETSIZE_OVERRIDABLE */
2295
2296 /**
2297 * True if SIGPIPE is blocked
2298 */
2299 bool sigpipe_blocked;
2300
2301 #ifdef HTTPS_SUPPORT
2302 #ifdef UPGRADE_SUPPORT
2303 /**
2304 * Head of DLL of upgrade response handles we are processing.
2305 * Used for upgraded TLS connections when thread-per-connection
2306 * is not used.
2307 */
2308 struct MHD_UpgradeResponseHandle *urh_head;
2309
2310 /**
2311 * Tail of DLL of upgrade response handles we are processing.
2312 * Used for upgraded TLS connections when thread-per-connection
2313 * is not used.
2314 */
2315 struct MHD_UpgradeResponseHandle *urh_tail;
2316 #endif /* UPGRADE_SUPPORT */
2317
2318 /**
2319 * Desired cipher algorithms.
2320 */
2321 gnutls_priority_t priority_cache;
2322
2323 /**
2324 * What kind of credentials are we offering
2325 * for SSL/TLS?
2326 */
2327 gnutls_credentials_type_t cred_type;
2328
2329 /**
2330 * Server x509 credentials
2331 */
2332 gnutls_certificate_credentials_t x509_cred;
2333
2334 /**
2335 * Diffie-Hellman parameters
2336 */
2337 gnutls_dh_params_t dh_params;
2338
2339 /**
2340 * Server PSK credentials
2341 */
2342 gnutls_psk_server_credentials_t psk_cred;
2343
2344 #if GNUTLS_VERSION_MAJOR >= 3
2345 /**
2346 * Function that can be used to obtain the certificate. Needed
2347 * for SNI support. See #MHD_OPTION_HTTPS_CERT_CALLBACK.
2348 */
2349 gnutls_certificate_retrieve_function2 *cert_callback;
2350
2351 /**
2352 * Function that can be used to obtain the shared key.
2353 */
2354 MHD_PskServerCredentialsCallback cred_callback;
2355
2356 /**
2357 * Closure for @e cred_callback.
2358 */
2359 void *cred_callback_cls;
2360 #endif
2361
2362 #if GNUTLS_VERSION_NUMBER >= 0x030603
2363 /**
2364 * Function that can be used to obtain the certificate. Needed
2365 * for OCSP stapling support. See #MHD_OPTION_HTTPS_CERT_CALLBACK2.
2366 */
2367 gnutls_certificate_retrieve_function3 *cert_callback2;
2368 #endif
2369
2370 /**
2371 * Pointer to our SSL/TLS key (in ASCII) in memory.
2372 */
2373 const char *https_mem_key;
2374
2375 /**
2376 * Pointer to our SSL/TLS certificate (in ASCII) in memory.
2377 */
2378 const char *https_mem_cert;
2379
2380 /**
2381 * Pointer to 0-terminated HTTPS passphrase in memory.
2382 */
2383 const char *https_key_password;
2384
2385 /**
2386 * Pointer to our SSL/TLS certificate authority (in ASCII) in memory.
2387 */
2388 const char *https_mem_trust;
2389
2390 /**
2391 * Our Diffie-Hellman parameters in memory.
2392 */
2393 gnutls_dh_params_t https_mem_dhparams;
2394
2395 /**
2396 * true if we have initialized @e https_mem_dhparams.
2397 */
2398 bool have_dhparams;
2399
2400 /**
2401 * true if ALPN is disabled.
2402 */
2403 bool disable_alpn;
2404
2405 #endif /* HTTPS_SUPPORT */
2406
2407 #ifdef DAUTH_SUPPORT
2408
2409 /**
2410 * Character array of random values.
2411 */
2412 const char *digest_auth_random;
2413
2414 /**
2415 * Size of @a digest_auth_random.
2416 */
2417 size_t digest_auth_rand_size;
2418
2419 /**
2420 * The malloc'ed copy of the @a digest_auth_random.
2421 */
2422 void *digest_auth_random_copy;
2423
2424 /**
2425 * An array that contains the map nonce-nc.
2426 */
2427 struct MHD_NonceNc *nnc;
2428
2429 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
2430 /**
2431 * A rw-lock for synchronizing access to @e nnc.
2432 */
2433 MHD_mutex_ nnc_lock;
2434 #endif
2435
2436 /**
2437 * Size of the nonce-nc array.
2438 */
2439 unsigned int nonce_nc_size;
2440
2441 /**
2442 * Nonce bind type.
2443 */
2444 unsigned int dauth_bind_type;
2445
2446 /**
2447 * Default nonce validity length.
2448 */
2449 unsigned int dauth_def_nonce_timeout;
2450
2451 /**
2452 * Default maximum nc (nonce count) value.
2453 */
2454 uint32_t dauth_def_max_nc;
2455 #endif
2456
2457 #ifdef TCP_FASTOPEN
2458 /**
2459 * The queue size for incoming SYN + DATA packets.
2460 */
2461 unsigned int fastopen_queue_size;
2462 #endif
2463
2464 /**
2465 * The size of queue for listen socket.
2466 */
2467 unsigned int listen_backlog_size;
2468
2469 /* TODO: replace with a single member */
2470 /**
2471 * The value to be returned by #MHD_get_daemon_info()
2472 */
2473 union MHD_DaemonInfo daemon_info_dummy_listen_fd;
2474
2475 #ifdef EPOLL_SUPPORT
2476 /**
2477 * The value to be returned by #MHD_get_daemon_info()
2478 */
2479 union MHD_DaemonInfo daemon_info_dummy_epoll_fd;
2480 #endif /* EPOLL_SUPPORT */
2481
2482 /**
2483 * The value to be returned by #MHD_get_daemon_info()
2484 */
2485 union MHD_DaemonInfo daemon_info_dummy_num_connections;
2486
2487 /**
2488 * The value to be returned by #MHD_get_daemon_info()
2489 */
2490 union MHD_DaemonInfo daemon_info_dummy_flags;
2491
2492 /**
2493 * The value to be returned by #MHD_get_daemon_info()
2494 */
2495 union MHD_DaemonInfo daemon_info_dummy_port;
2496
2497 #if defined(_DEBUG) && defined(HAVE_ACCEPT4)
2498 /**
2499 * If set to 'true', accept() function will be used instead of accept4() even
2500 * if accept4() is available.
2501 * This is a workaround for zzuf, which does not support sockets created
2502 * by accept4() function.
2503 * There is no API to change the value of this member, it can be flipped
2504 * only by direct access to the struct member.
2505 */
2506 bool avoid_accept4;
2507 #endif /* _DEBUG */
2508 };
2509
2510
2511 #if defined(HAVE_POLL) && defined(EPOLL_SUPPORT)
2512 /**
2513 * Checks whether the @a d daemon is using select()
2514 */
2515 #define MHD_D_IS_USING_SELECT_(d) \
2516 (0 == (d->options & (MHD_USE_POLL | MHD_USE_EPOLL)))
2517 /**
2518 * Checks whether the @a d daemon is using poll()
2519 */
2520 #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL))
2521 /**
2522 * Checks whether the @a d daemon is using epoll
2523 */
2524 #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL))
2525 #elif defined(HAVE_POLL)
2526 /**
2527 * Checks whether the @a d daemon is using select()
2528 */
2529 #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_POLL))
2530 /**
2531 * Checks whether the @a d daemon is using poll()
2532 */
2533 #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL))
2534 /**
2535 * Checks whether the @a d daemon is using epoll
2536 */
2537 #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0)
2538 #elif defined(EPOLL_SUPPORT)
2539 /**
2540 * Checks whether the @a d daemon is using select()
2541 */
2542 #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_EPOLL))
2543 /**
2544 * Checks whether the @a d daemon is using poll()
2545 */
2546 #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0)
2547 /**
2548 * Checks whether the @a d daemon is using epoll
2549 */
2550 #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL))
2551 #else /* select() only */
2552 /**
2553 * Checks whether the @a d daemon is using select()
2554 */
2555 #define MHD_D_IS_USING_SELECT_(d) ((void) (d), ! 0)
2556 /**
2557 * Checks whether the @a d daemon is using poll()
2558 */
2559 #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0)
2560 /**
2561 * Checks whether the @a d daemon is using epoll
2562 */
2563 #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0)
2564 #endif /* select() only */
2565
2566 #if defined(MHD_USE_THREADS)
2567 /**
2568 * Checks whether the @a d daemon is using internal polling thread
2569 */
2570 #define MHD_D_IS_USING_THREADS_(d) \
2571 (0 != (d->options & (MHD_USE_INTERNAL_POLLING_THREAD)))
2572 /**
2573 * Checks whether the @a d daemon is using thread-per-connection mode
2574 */
2575 #define MHD_D_IS_USING_THREAD_PER_CONN_(d) \
2576 (0 != ((d)->options & MHD_USE_THREAD_PER_CONNECTION))
2577
2578 /**
2579 * Check whether the @a d daemon has thread-safety enabled.
2580 */
2581 #define MHD_D_IS_THREAD_SAFE_(d) \
2582 (0 == ((d)->options & MHD_USE_NO_THREAD_SAFETY))
2583 #else /* ! MHD_USE_THREADS */
2584 /**
2585 * Checks whether the @a d daemon is using internal polling thread
2586 */
2587 #define MHD_D_IS_USING_THREADS_(d) ((void) d, 0)
2588 /**
2589 * Checks whether the @a d daemon is using thread-per-connection mode
2590 */
2591 #define MHD_D_IS_USING_THREAD_PER_CONN_(d) ((void) d, 0)
2592
2593 /**
2594 * Check whether the @a d daemon has thread-safety enabled.
2595 */
2596 #define MHD_D_IS_THREAD_SAFE_(d) ((void) d, 0)
2597 #endif /* ! MHD_USE_THREADS */
2598
2599 #ifdef HAS_FD_SETSIZE_OVERRIDABLE
2600 /**
2601 * Get FD_SETSIZE used by the daemon @a d
2602 */
2603 #define MHD_D_GET_FD_SETSIZE_(d) ((d)->fdset_size)
2604 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */
2605 /**
2606 * Get FD_SETSIZE used by the daemon @a d
2607 */
2608 #define MHD_D_GET_FD_SETSIZE_(d) (FD_SETSIZE)
2609 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */
2610
2611 /**
2612 * Check whether socket @a sckt fits fd_sets used by the daemon @a d
2613 */
2614 #define MHD_D_DOES_SCKT_FIT_FDSET_(sckt,d) \
2615 MHD_SCKT_FD_FITS_FDSET_SETSIZE_(sckt,NULL,MHD_D_GET_FD_SETSIZE_(d))
2616
2617
2618 #ifdef DAUTH_SUPPORT
2619
2620 /**
2621 * Parameter of request's Digest Authorization header
2622 */
2623 struct MHD_RqDAuthParam
2624 {
2625 /**
2626 * The string with length, NOT zero-terminated
2627 */
2628 struct _MHD_str_w_len value;
2629 /**
2630 * True if string must be "unquoted" before processing.
2631 * This member is false if the string is used in DQUOTE marks, but no
2632 * backslash-escape is used in the string.
2633 */
2634 bool quoted;
2635 };
2636
2637 /**
2638 * Request client's Digest Authorization header parameters
2639 */
2640 struct MHD_RqDAuth
2641 {
2642 struct MHD_RqDAuthParam nonce;
2643 struct MHD_RqDAuthParam opaque;
2644 struct MHD_RqDAuthParam response;
2645 struct MHD_RqDAuthParam username;
2646 struct MHD_RqDAuthParam username_ext;
2647 struct MHD_RqDAuthParam realm;
2648 struct MHD_RqDAuthParam uri;
2649 /* The raw QOP value, used in the 'response' calculation */
2650 struct MHD_RqDAuthParam qop_raw;
2651 struct MHD_RqDAuthParam cnonce;
2652 struct MHD_RqDAuthParam nc;
2653
2654 /* Decoded values are below */
2655 bool userhash; /* True if 'userhash' parameter has value 'true'. */
2656 enum MHD_DigestAuthAlgo3 algo3;
2657 enum MHD_DigestAuthQOP qop;
2658 };
2659
2660
2661 #endif /* DAUTH_SUPPORT */
2662
2663 /**
2664 * Insert an element at the head of a DLL. Assumes that head, tail and
2665 * element are structs with prev and next fields.
2666 *
2667 * @param head pointer to the head of the DLL
2668 * @param tail pointer to the tail of the DLL
2669 * @param element element to insert
2670 */
2671 #define DLL_insert(head,tail,element) do { \
2672 mhd_assert (NULL == (element)->next); \
2673 mhd_assert (NULL == (element)->prev); \
2674 (element)->next = (head); \
2675 (element)->prev = NULL; \
2676 if ((tail) == NULL) { \
2677 (tail) = element; \
2678 } else { \
2679 (head)->prev = element; \
2680 } \
2681 (head) = (element); } while (0)
2682
2683
2684 /**
2685 * Remove an element from a DLL. Assumes
2686 * that head, tail and element are structs
2687 * with prev and next fields.
2688 *
2689 * @param head pointer to the head of the DLL
2690 * @param tail pointer to the tail of the DLL
2691 * @param element element to remove
2692 */
2693 #define DLL_remove(head,tail,element) do { \
2694 mhd_assert ( (NULL != (element)->next) || ((element) == (tail))); \
2695 mhd_assert ( (NULL != (element)->prev) || ((element) == (head))); \
2696 if ((element)->prev == NULL) { \
2697 (head) = (element)->next; \
2698 } else { \
2699 (element)->prev->next = (element)->next; \
2700 } \
2701 if ((element)->next == NULL) { \
2702 (tail) = (element)->prev; \
2703 } else { \
2704 (element)->next->prev = (element)->prev; \
2705 } \
2706 (element)->next = NULL; \
2707 (element)->prev = NULL; } while (0)
2708
2709
2710 /**
2711 * Insert an element at the head of a XDLL. Assumes that head, tail and
2712 * element are structs with prevX and nextX fields.
2713 *
2714 * @param head pointer to the head of the XDLL
2715 * @param tail pointer to the tail of the XDLL
2716 * @param element element to insert
2717 */
2718 #define XDLL_insert(head,tail,element) do { \
2719 mhd_assert (NULL == (element)->nextX); \
2720 mhd_assert (NULL == (element)->prevX); \
2721 (element)->nextX = (head); \
2722 (element)->prevX = NULL; \
2723 if (NULL == (tail)) { \
2724 (tail) = element; \
2725 } else { \
2726 (head)->prevX = element; \
2727 } \
2728 (head) = (element); } while (0)
2729
2730
2731 /**
2732 * Remove an element from a XDLL. Assumes
2733 * that head, tail and element are structs
2734 * with prevX and nextX fields.
2735 *
2736 * @param head pointer to the head of the XDLL
2737 * @param tail pointer to the tail of the XDLL
2738 * @param element element to remove
2739 */
2740 #define XDLL_remove(head,tail,element) do { \
2741 mhd_assert ( (NULL != (element)->nextX) || ((element) == (tail))); \
2742 mhd_assert ( (NULL != (element)->prevX) || ((element) == (head))); \
2743 if (NULL == (element)->prevX) { \
2744 (head) = (element)->nextX; \
2745 } else { \
2746 (element)->prevX->nextX = (element)->nextX; \
2747 } \
2748 if (NULL == (element)->nextX) { \
2749 (tail) = (element)->prevX; \
2750 } else { \
2751 (element)->nextX->prevX = (element)->prevX; \
2752 } \
2753 (element)->nextX = NULL; \
2754 (element)->prevX = NULL; } while (0)
2755
2756
2757 /**
2758 * Insert an element at the head of a EDLL. Assumes that head, tail and
2759 * element are structs with prevE and nextE fields.
2760 *
2761 * @param head pointer to the head of the EDLL
2762 * @param tail pointer to the tail of the EDLL
2763 * @param element element to insert
2764 */
2765 #define EDLL_insert(head,tail,element) do { \
2766 (element)->nextE = (head); \
2767 (element)->prevE = NULL; \
2768 if ((tail) == NULL) { \
2769 (tail) = element; \
2770 } else { \
2771 (head)->prevE = element; \
2772 } \
2773 (head) = (element); } while (0)
2774
2775
2776 /**
2777 * Remove an element from a EDLL. Assumes
2778 * that head, tail and element are structs
2779 * with prevE and nextE fields.
2780 *
2781 * @param head pointer to the head of the EDLL
2782 * @param tail pointer to the tail of the EDLL
2783 * @param element element to remove
2784 */
2785 #define EDLL_remove(head,tail,element) do { \
2786 if ((element)->prevE == NULL) { \
2787 (head) = (element)->nextE; \
2788 } else { \
2789 (element)->prevE->nextE = (element)->nextE; \
2790 } \
2791 if ((element)->nextE == NULL) { \
2792 (tail) = (element)->prevE; \
2793 } else { \
2794 (element)->nextE->prevE = (element)->prevE; \
2795 } \
2796 (element)->nextE = NULL; \
2797 (element)->prevE = NULL; } while (0)
2798
2799
2800 /**
2801 * Convert all occurrences of '+' to ' '.
2802 *
2803 * @param arg string that is modified (in place), must be 0-terminated
2804 */
2805 void
2806 MHD_unescape_plus (char *arg);
2807
2808
2809 /**
2810 * Callback invoked when iterating over @a key / @a value
2811 * argument pairs during parsing.
2812 *
2813 * @param cls context of the iteration
2814 * @param key 0-terminated key string, never NULL
2815 * @param key_size number of bytes in key
2816 * @param value 0-terminated binary data, may include binary zeros, may be NULL
2817 * @param value_size number of bytes in value
2818 * @param kind origin of the key-value pair
2819 * @return #MHD_YES on success (continue to iterate)
2820 * #MHD_NO to signal failure (and abort iteration)
2821 */
2822 typedef enum MHD_Result
2823 (*MHD_ArgumentIterator_)(void *cls,
2824 const char *key,
2825 size_t key_size,
2826 const char *value,
2827 size_t value_size,
2828 enum MHD_ValueKind kind);
2829
2830
2831 /**
2832 * Parse and unescape the arguments given by the client
2833 * as part of the HTTP request URI.
2834 *
2835 * @param kind header kind to pass to @a cb
2836 * @param connection connection to add headers to
2837 * @param[in,out] args argument URI string (after "?" in URI),
2838 * clobbered in the process!
2839 * @param cb function to call on each key-value pair found
2840 * @param cls the iterator context
2841 * @return #MHD_NO on failure (@a cb returned #MHD_NO),
2842 * #MHD_YES for success (parsing succeeded, @a cb always
2843 * returned #MHD_YES)
2844 */
2845 enum MHD_Result
2846 MHD_parse_arguments_ (struct MHD_Connection *connection,
2847 enum MHD_ValueKind kind,
2848 char *args,
2849 MHD_ArgumentIterator_ cb,
2850 void *cls);
2851
2852
2853 /**
2854 * Check whether response header contains particular token.
2855 *
2856 * Token could be surrounded by spaces and tabs and delimited by comma.
2857 * Case-insensitive match used for header names and tokens.
2858 *
2859 * @param response the response to query
2860 * @param key header name
2861 * @param key_len the length of @a key, not including optional
2862 * terminating null-character.
2863 * @param token the token to find
2864 * @param token_len the length of @a token, not including optional
2865 * terminating null-character.
2866 * @return true if token is found in specified header,
2867 * false otherwise
2868 */
2869 bool
2870 MHD_check_response_header_token_ci (const struct MHD_Response *response,
2871 const char *key,
2872 size_t key_len,
2873 const char *token,
2874 size_t token_len);
2875
2876 /**
2877 * Check whether response header contains particular static @a tkn.
2878 *
2879 * Token could be surrounded by spaces and tabs and delimited by comma.
2880 * Case-insensitive match used for header names and tokens.
2881 * @param r the response to query
2882 * @param k header name
2883 * @param tkn the static string of token to find
2884 * @return true if token is found in specified header,
2885 * false otherwise
2886 */
2887 #define MHD_check_response_header_s_token_ci(r,k,tkn) \
2888 MHD_check_response_header_token_ci ((r),(k),MHD_STATICSTR_LEN_ (k), \
2889 (tkn),MHD_STATICSTR_LEN_ (tkn))
2890
2891
2892 /**
2893 * Internal version of #MHD_suspend_connection().
2894 *
2895 * @remark In thread-per-connection mode: can be called from any thread,
2896 * in any other mode: to be called only from thread that process
2897 * daemon's select()/poll()/etc.
2898 *
2899 * @param connection the connection to suspend
2900 */
2901 void
2902 internal_suspend_connection_ (struct MHD_Connection *connection);
2903
2904
2905 /**
2906 * Trace up to and return master daemon. If the supplied daemon
2907 * is a master, then return the daemon itself.
2908 *
2909 * @param daemon handle to a daemon
2910 * @return master daemon handle
2911 */
2912 _MHD_static_inline struct MHD_Daemon *
2913 MHD_get_master (struct MHD_Daemon *const daemon)
2914 {
2915 struct MHD_Daemon *ret;
2916
2917 if (NULL != daemon->master)
2918 ret = daemon->master;
2919 else
2920 ret = daemon;
2921 mhd_assert (NULL == ret->master);
2922
2923 return ret;
2924 }
2925
2926
2927 #ifdef UPGRADE_SUPPORT
2928 /**
2929 * Mark upgraded connection as closed by application.
2930 *
2931 * The @a connection pointer must not be used after call of this function
2932 * as it may be freed in other thread immediately.
2933 * @param connection the upgraded connection to mark as closed by application
2934 */
2935 void
2936 MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection);
2937
2938 #endif /* UPGRADE_SUPPORT */
2939
2940
2941 #endif