aboutsummaryrefslogtreecommitdiff
path: root/src/microhttpd/response.c
blob: 27b3ee3fb0ba0e1db6990d1f70a83565a087600a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
/*
     This file is part of libmicrohttpd
     Copyright (C) 2007, 2009, 2010, 2016, 2017 Daniel Pittman and Christian Grothoff

     This library is free software; you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public
     License as published by the Free Software Foundation; either
     version 2.1 of the License, or (at your option) any later version.

     This library is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     Lesser General Public License for more details.

     You should have received a copy of the GNU Lesser General Public
     License along with this library; if not, write to the Free Software
     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
/**
 * @file response.c
 * @brief  Methods for managing response objects
 * @author Daniel Pittman
 * @author Christian Grothoff
 * @author Karlson2k (Evgeny Grin)
 */

#define MHD_NO_DEPRECATION 1

#include "mhd_options.h"
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif /* HAVE_SYS_IOCTL_H */
#if defined(_WIN32) && ! defined(__CYGWIN__)
#include <windows.h>
#endif /* _WIN32 && !__CYGWIN__ */

#include "internal.h"
#include "response.h"
#include "mhd_limits.h"
#include "mhd_sockets.h"
#include "mhd_itc.h"
#include "mhd_str.h"
#include "connection.h"
#include "memorypool.h"
#include "mhd_compat.h"


#if defined(MHD_W32_MUTEX_)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif /* !WIN32_LEAN_AND_MEAN */
#include <windows.h>
#endif /* MHD_W32_MUTEX_ */
#if defined(_WIN32)
#include <io.h> /* for lseek(), read() */
#endif /* _WIN32 */


/**
 * Size of single file read operation for
 * file-backed responses.
 */
#ifndef MHD_FILE_READ_BLOCK_SIZE
#ifdef _WIN32
#define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */
#else /* _WIN32 */
#define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */
#endif /* _WIN32 */
#endif /* !MHD_FD_BLOCK_SIZE */


/**
 * Add a header or footer line to the response.
 *
 * @param response response to add a header to
 * @param kind header or footer
 * @param header the header to add
 * @param content value to add
 * @return #MHD_NO on error (i.e. invalid header or content format).
 */
static enum MHD_Result
add_response_entry (struct MHD_Response *response,
                    enum MHD_ValueKind kind,
                    const char *header,
                    const char *content)
{
  struct MHD_HTTP_Header *hdr;

  if ( (NULL == response) ||
       (NULL == header) ||
       (NULL == content) ||
       (0 == header[0]) ||
       (0 == content[0]) ||
       (NULL != strchr (header, '\t')) ||
       (NULL != strchr (header, '\r')) ||
       (NULL != strchr (header, '\n')) ||
       (NULL != strchr (content, '\t')) ||
       (NULL != strchr (content, '\r')) ||
       (NULL != strchr (content, '\n')) )
    return MHD_NO;
  if (NULL == (hdr = malloc (sizeof (struct MHD_HTTP_Header))))
    return MHD_NO;
  if (NULL == (hdr->header = strdup (header)))
  {
    free (hdr);
    return MHD_NO;
  }
  hdr->header_size = strlen (header);
  if (NULL == (hdr->value = strdup (content)))
  {
    free (hdr->header);
    free (hdr);
    return MHD_NO;
  }
  hdr->value_size = strlen (content);
  hdr->kind = kind;
  hdr->next = response->first_header;
  response->first_header = hdr;
  return MHD_YES;
}


/**
 * Add a header line to the response.
 *
 * @param response response to add a header to
 * @param header the header to add
 * @param content value to add
 * @return #MHD_NO on error (i.e. invalid header or content format).
 * @ingroup response
 */
enum MHD_Result
MHD_add_response_header (struct MHD_Response *response,
                         const char *header,
                         const char *content)
{
  if ( (MHD_str_equal_caseless_ (header,
                                 MHD_HTTP_HEADER_TRANSFER_ENCODING)) &&
       (! MHD_str_equal_caseless_ (content,
                                   "identity")) &&
       (! MHD_str_equal_caseless_ (content,
                                   "chunked")) )
  {
    /* Setting transfer encodings other than "identity" or
       "chunked" is not allowed.  Note that MHD will set the
       correct transfer encoding if required automatically. */
    /* NOTE: for compressed bodies, use the "Content-encoding" header */
    return MHD_NO;
  }
  if ( (0 == (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
              & response->flags)) &&
       (MHD_str_equal_caseless_ (header,
                                 MHD_HTTP_HEADER_CONTENT_LENGTH)) )
  {
    /* MHD will set Content-length if allowed and possible,
       reject attempt by application */
    return MHD_NO;
  }

  return add_response_entry (response,
                             MHD_HEADER_KIND,
                             header,
                             content);
}


/**
 * Add a footer line to the response.
 *
 * @param response response to remove a header from
 * @param footer the footer to delete
 * @param content value to delete
 * @return #MHD_NO on error (i.e. invalid footer or content format).
 * @ingroup response
 */
enum MHD_Result
MHD_add_response_footer (struct MHD_Response *response,
                         const char *footer,
                         const char *content)
{
  return add_response_entry (response,
                             MHD_FOOTER_KIND,
                             footer,
                             content);
}


/**
 * Delete a header (or footer) line from the response.
 *
 * @param response response to remove a header from
 * @param header the header to delete
 * @param content value to delete
 * @return #MHD_NO on error (no such header known)
 * @ingroup response
 */
enum MHD_Result
MHD_del_response_header (struct MHD_Response *response,
                         const char *header,
                         const char *content)
{
  struct MHD_HTTP_Header *pos;
  struct MHD_HTTP_Header *prev;
  size_t header_len;
  size_t content_len;

  if ( (NULL == header) ||
       (NULL == content) )
    return MHD_NO;
  header_len = strlen (header);
  content_len = strlen (content);
  prev = NULL;
  pos = response->first_header;
  while (NULL != pos)
  {
    if ((header_len == pos->header_size) &&
        (content_len == pos->value_size) &&
        (0 == memcmp (header,
                      pos->header,
                      header_len)) &&
        (0 == memcmp (content,
                      pos->value,
                      content_len)))
    {
      free (pos->header);
      free (pos->value);
      if (NULL == prev)
        response->first_header = pos->next;
      else
        prev->next = pos->next;
      free (pos);
      return MHD_YES;
    }
    prev = pos;
    pos = pos->next;
  }
  return MHD_NO;
}


/**
 * Get all of the headers (and footers) added to a response.
 *
 * @param response response to query
 * @param iterator callback to call on each header;
 *        maybe NULL (then just count headers)
 * @param iterator_cls extra argument to @a iterator
 * @return number of entries iterated over
 * @ingroup response
 */
int
MHD_get_response_headers (struct MHD_Response *response,
                          MHD_KeyValueIterator iterator,
                          void *iterator_cls)
{
  int numHeaders = 0;
  struct MHD_HTTP_Header *pos;

  for (pos = response->first_header;
       NULL != pos;
       pos = pos->next)
  {
    numHeaders++;
    if ((NULL != iterator) &&
        (MHD_YES != iterator (iterator_cls,
                              pos->kind,
                              pos->header,
                              pos->value)))
      break;
  }
  return numHeaders;
}


/**
 * Get a particular header (or footer) from the response.
 *
 * @param response response to query
 * @param key which header to get
 * @return NULL if header does not exist
 * @ingroup response
 */
const char *
MHD_get_response_header (struct MHD_Response *response,
                         const char *key)
{
  struct MHD_HTTP_Header *pos;
  size_t key_size;

  if (NULL == key)
    return NULL;

  key_size = strlen (key);
  for (pos = response->first_header;
       NULL != pos;
       pos = pos->next)
  {
    if ((pos->header_size == key_size) &&
        (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size)))
      return pos->value;
  }
  return NULL;
}


/**
 * Check whether response header contains particular token.
 *
 * Token could be surrounded by spaces and tabs and delimited by comma.
 * Case-insensitive match used for header names and tokens.
 *
 * @param response  the response to query
 * @param key       header name
 * @param key_len   the length of @a key, not including optional
 *                  terminating null-character.
 * @param token     the token to find
 * @param token_len the length of @a token, not including optional
 *                  terminating null-character.
 * @return true if token is found in specified header,
 *         false otherwise
 */
bool
MHD_check_response_header_token_ci (const struct MHD_Response *response,
                                    const char *key,
                                    size_t key_len,
                                    const char *token,
                                    size_t token_len)
{
  struct MHD_HTTP_Header *pos;

  if ( (NULL == key) ||
       ('\0' == key[0]) ||
       (NULL == token) ||
       ('\0' == token[0]) )
    return false;

  /* Token must not contain binary zero! */
  mhd_assert (strlen (token) == token_len);

  for (pos = response->first_header;
       NULL != pos;
       pos = pos->next)
  {
    if ( (pos->kind == MHD_HEADER_KIND) &&
         (key_len == pos->header_size) &&
         MHD_str_equal_caseless_bin_n_ (pos->header,
                                        key,
                                        key_len) &&
         MHD_str_has_token_caseless_ (pos->value,
                                      token,
                                      token_len) )
      return true;
  }
  return false;
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
 * @param block_size preferred block size for querying crc (advisory only,
 *                   MHD may still call @a crc using smaller chunks); this
 *                   is essentially the buffer size used for IO, clients
 *                   should pick a value that is appropriate for IO and
 *                   memory performance requirements
 * @param crc callback to use to obtain response data
 * @param crc_cls extra argument to @a crc
 * @param crfc callback to call to free @a crc_cls resources
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
struct MHD_Response *
MHD_create_response_from_callback (uint64_t size,
                                   size_t block_size,
                                   MHD_ContentReaderCallback crc,
                                   void *crc_cls,
                                   MHD_ContentReaderFreeCallback crfc)
{
  struct MHD_Response *response;

  if ((NULL == crc) || (0 == block_size))
    return NULL;
  if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response)
                                       + block_size)))
    return NULL;
  response->fd = -1;
  response->data = (void *) &response[1];
  response->data_buffer_size = block_size;
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  if (! MHD_mutex_init_ (&response->mutex))
  {
    free (response);
    return NULL;
  }
#endif
  response->crc = crc;
  response->crfc = crfc;
  response->crc_cls = crc_cls;
  response->reference_count = 1;
  response->total_size = size;
  return response;
}


/**
 * Set special flags and options for a response.
 *
 * @param response the response to modify
 * @param flags to set for the response
 * @param ... #MHD_RO_END terminated list of options
 * @return #MHD_YES on success, #MHD_NO on error
 */
enum MHD_Result
MHD_set_response_options (struct MHD_Response *response,
                          enum MHD_ResponseFlags flags,
                          ...)
{
  va_list ap;
  enum MHD_Result ret;
  enum MHD_ResponseOptions ro;

  ret = MHD_YES;
  response->flags = flags;
  va_start (ap, flags);
  while (MHD_RO_END != (ro = va_arg (ap, enum MHD_ResponseOptions)))
  {
    switch (ro)
    {
    default:
      ret = MHD_NO;
      break;
    }
  }
  va_end (ap);
  return ret;
}


/**
 * Given a file descriptor, read data from the file
 * to generate the response.
 *
 * @param cls pointer to the response
 * @param pos offset in the file to access
 * @param buf where to write the data
 * @param max number of bytes to write at most
 * @return number of bytes written
 */
static ssize_t
file_reader (void *cls,
             uint64_t pos,
             char *buf,
             size_t max)
{
  struct MHD_Response *response = cls;
#if ! defined(_WIN32) || defined(__CYGWIN__)
  ssize_t n;
#else  /* _WIN32 && !__CYGWIN__ */
  const HANDLE fh = (HANDLE) _get_osfhandle (response->fd);
#endif /* _WIN32 && !__CYGWIN__ */
  const int64_t offset64 = (int64_t) (pos + response->fd_off);

  if (offset64 < 0)
    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */

#if ! defined(_WIN32) || defined(__CYGWIN__)
  if (max > SSIZE_MAX)
    max = SSIZE_MAX; /* Clamp to maximum return value. */

#if defined(HAVE_PREAD64)
  n = pread64 (response->fd, buf, max, offset64);
#elif defined(HAVE_PREAD)
  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
       (offset64 > (uint64_t) INT32_MAX) )
    return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */

  n = pread (response->fd, buf, max, (off_t) offset64);
#else  /* ! HAVE_PREAD */
#if defined(HAVE_LSEEK64)
  if (lseek64 (response->fd,
               offset64,
               SEEK_SET) != offset64)
    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
#else  /* ! HAVE_LSEEK64 */
  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
       (offset64 > (uint64_t) INT32_MAX) )
    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */

  if (lseek (response->fd,
             (off_t) offset64,
             SEEK_SET) != (off_t) offset64)
    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
#endif /* ! HAVE_LSEEK64 */
  n = read (response->fd,
            buf,
            max);

#endif /* ! HAVE_PREAD */
  if (0 == n)
    return MHD_CONTENT_READER_END_OF_STREAM;
  if (n < 0)
    return MHD_CONTENT_READER_END_WITH_ERROR;
  return n;
#else /* _WIN32 && !__CYGWIN__ */
  if (INVALID_HANDLE_VALUE == fh)
    return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */
  else
  {
    OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0};   /* Initialize to zero. */
    ULARGE_INTEGER pos_uli;
    DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max;
    DWORD resRead;

    pos_uli.QuadPart = (uint64_t) offset64;   /* Simple transformation 64bit -> 2x32bit. */
    f_ol.Offset = pos_uli.LowPart;
    f_ol.OffsetHigh = pos_uli.HighPart;
    if (! ReadFile (fh, (void*) buf, toRead, &resRead, &f_ol))
      return MHD_CONTENT_READER_END_WITH_ERROR;   /* Read error. */
    if (0 == resRead)
      return MHD_CONTENT_READER_END_OF_STREAM;
    return (ssize_t) resRead;
  }
#endif /* _WIN32 && !__CYGWIN__ */
}


/**
 * Given a pipe descriptor, read data from the pipe
 * to generate the response.
 *
 * @param cls pointer to the response
 * @param pos offset in the pipe to access (ignored)
 * @param buf where to write the data
 * @param max number of bytes to write at most
 * @return number of bytes written
 */
static ssize_t
pipe_reader (void *cls,
             uint64_t pos,
             char *buf,
             size_t max)
{
  struct MHD_Response *response = cls;
  ssize_t n;

  (void) pos;
  n = read (response->fd,
            buf,
            max);
  if (0 == n)
    return MHD_CONTENT_READER_END_OF_STREAM;
  if (n < 0)
    return MHD_CONTENT_READER_END_WITH_ERROR;
  return n;
}


/**
 * Destroy file reader context.  Closes the file
 * descriptor.
 *
 * @param cls pointer to file descriptor
 */
static void
free_callback (void *cls)
{
  struct MHD_Response *response = cls;

  (void) close (response->fd);
  response->fd = -1;
}


#undef MHD_create_response_from_fd_at_offset

/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response
 * @param fd file descriptor referring to a file on disk with the
 *        data; will be closed when response is destroyed;
 *        fd should be in 'blocking' mode
 * @param offset offset to start reading from in the file;
 *        Be careful! `off_t` may have been compiled to be a
 *        64-bit variable for MHD, in which case your application
 *        also has to be compiled using the same options! Read
 *        the MHD manual for more details.
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
struct MHD_Response *
MHD_create_response_from_fd_at_offset (size_t size,
                                       int fd,
                                       off_t offset)
{
  return MHD_create_response_from_fd_at_offset64 (size,
                                                  fd,
                                                  offset);
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response;
 *        sizes larger than 2 GiB may be not supported by OS or
 *        MHD build; see ::MHD_FEATURE_LARGE_FILE
 * @param fd file descriptor referring to a file on disk with the
 *        data; will be closed when response is destroyed;
 *        fd should be in 'blocking' mode
 * @param offset offset to start reading from in the file;
 *        reading file beyond 2 GiB may be not supported by OS or
 *        MHD build; see ::MHD_FEATURE_LARGE_FILE
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd_at_offset64 (uint64_t size,
                                         int fd,
                                         uint64_t offset)
{
  struct MHD_Response *response;

#if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64)
  if ( (sizeof(uint64_t) > sizeof(off_t)) &&
       ( (size > (uint64_t) INT32_MAX) ||
         (offset > (uint64_t) INT32_MAX) ||
         ((size + offset) >= (uint64_t) INT32_MAX) ) )
    return NULL;
#endif
  if ( ((int64_t) size < 0) ||
       ((int64_t) offset < 0) ||
       ((int64_t) (size + offset) < 0) )
    return NULL;

  response = MHD_create_response_from_callback (size,
                                                MHD_FILE_READ_BLOCK_SIZE,
                                                &file_reader,
                                                NULL,
                                                &free_callback);
  if (NULL == response)
    return NULL;
  response->fd = fd;
  response->is_pipe = false;
  response->fd_off = offset;
  response->crc_cls = response;
  return response;
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used ONLY ONCE.
 *
 * @param fd file descriptor referring to a read-end of a pipe with the
 *        data; will be closed when response is destroyed;
 *        fd should be in 'blocking' mode
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_pipe (int fd)
{
  struct MHD_Response *response;

  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
                                                MHD_FILE_READ_BLOCK_SIZE,
                                                &pipe_reader,
                                                NULL,
                                                &free_callback);
  if (NULL == response)
    return NULL;
  response->fd = fd;
  response->is_pipe = true;
  response->crc_cls = response;
  return response;
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response
 * @param fd file descriptor referring to a file on disk with the data
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
struct MHD_Response *
MHD_create_response_from_fd (size_t size,
                             int fd)
{
  return MHD_create_response_from_fd_at_offset64 (size,
                                                  fd,
                                                  0);
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response;
 *        sizes larger than 2 GiB may be not supported by OS or
 *        MHD build; see ::MHD_FEATURE_LARGE_FILE
 * @param fd file descriptor referring to a file on disk with the
 *        data; will be closed when response is destroyed;
 *        fd should be in 'blocking' mode
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd64 (uint64_t size,
                               int fd)
{
  return MHD_create_response_from_fd_at_offset64 (size,
                                                  fd,
                                                  0);
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the @a data portion of the response
 * @param data the data itself
 * @param must_free libmicrohttpd should free data when done
 * @param must_copy libmicrohttpd must make a copy of @a data
 *        right away, the data maybe released anytime after
 *        this call returns
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @deprecated use #MHD_create_response_from_buffer instead
 * @ingroup response
 */
struct MHD_Response *
MHD_create_response_from_data (size_t size,
                               void *data,
                               int must_free,
                               int must_copy)
{
  struct MHD_Response *response;
  void *tmp;

  if ((NULL == data) && (size > 0))
    return NULL;
  if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response))))
    return NULL;
  response->fd = -1;
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  if (! MHD_mutex_init_ (&response->mutex))
  {
    free (response);
    return NULL;
  }
#endif
  if ((must_copy) && (size > 0))
  {
    if (NULL == (tmp = malloc (size)))
    {
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
      MHD_mutex_destroy_chk_ (&response->mutex);
#endif
      free (response);
      return NULL;
    }
    memcpy (tmp, data, size);
    must_free = MHD_YES;
    data = tmp;
  }
  if (must_free)
  {
    response->crfc = &free;
    response->crc_cls = data;
  }
  response->reference_count = 1;
  response->total_size = size;
  response->data = data;
  response->data_size = size;
  return response;
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response
 * @param buffer size bytes containing the response's data portion
 * @param mode flags for buffer management
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
struct MHD_Response *
MHD_create_response_from_buffer (size_t size,
                                 void *buffer,
                                 enum MHD_ResponseMemoryMode mode)
{
  return MHD_create_response_from_data (size,
                                        buffer,
                                        mode == MHD_RESPMEM_MUST_FREE,
                                        mode == MHD_RESPMEM_MUST_COPY);
}


/**
 * Create a response object.  The response object can be extended with
 * header information and then be used any number of times.
 *
 * @param size size of the data portion of the response
 * @param buffer size bytes containing the response's data portion
 * @param crfc function to call to free the @a buffer
 * @return NULL on error (i.e. invalid arguments, out of memory)
 * @ingroup response
 */
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_buffer_with_free_callback (size_t size,
                                                    void *buffer,
                                                    MHD_ContentReaderFreeCallback
                                                    crfc)
{
  struct MHD_Response *r;

  r = MHD_create_response_from_data (size,
                                     buffer,
                                     MHD_YES,
                                     MHD_NO);
  if (NULL == r)
    return r;
  r->crfc = crfc;
  return r;
}


#ifdef UPGRADE_SUPPORT
/**
 * This connection-specific callback is provided by MHD to
 * applications (unusual) during the #MHD_UpgradeHandler.
 * It allows applications to perform 'special' actions on
 * the underlying socket from the upgrade.
 *
 * @param urh the handle identifying the connection to perform
 *            the upgrade @a action on.
 * @param action which action should be performed
 * @param ... arguments to the action (depends on the action)
 * @return #MHD_NO on error, #MHD_YES on success
 */
_MHD_EXTERN enum MHD_Result
MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh,
                    enum MHD_UpgradeAction action,
                    ...)
{
  struct MHD_Connection *connection;
  struct MHD_Daemon *daemon;

  if (NULL == urh)
    return MHD_NO;
  connection = urh->connection;

  /* Precaution checks on external data. */
  if (NULL == connection)
    return MHD_NO;
  daemon = connection->daemon;
  if (NULL == daemon)
    return MHD_NO;

  switch (action)
  {
  case MHD_UPGRADE_ACTION_CLOSE:
    if (urh->was_closed)
      return MHD_NO; /* Already closed. */

    /* transition to special 'closed' state for start of cleanup */
#ifdef HTTPS_SUPPORT
    if (0 != (daemon->options & MHD_USE_TLS) )
    {
      /* signal that app is done by shutdown() of 'app' socket */
      /* Application will not use anyway this socket after this command. */
      shutdown (urh->app.socket,
                SHUT_RDWR);
    }
#endif /* HTTPS_SUPPORT */
    mhd_assert (MHD_CONNECTION_UPGRADE == connection->state);
    urh->was_closed = true;
    /* As soon as connection will be marked with BOTH
     * 'urh->was_closed' AND 'urh->clean_ready', it will
     * be moved to cleanup list by MHD_resume_connection(). */
    MHD_resume_connection (connection);
    return MHD_YES;
  case MHD_UPGRADE_ACTION_CORK_ON:
    if (connection->sk_cork_on)
      return MHD_YES;
#ifdef HTTPS_SUPPORT
    if (0 != (daemon->options & MHD_USE_TLS) )
    {
      gnutls_record_cork (connection->tls_session);
      connection->sk_cork_on = true;
      return MHD_YES;
    }
    else
#endif
    {
      if (0 ==
          MHD_socket_cork_ (connection->socket_fd,
                            true))
      {
        connection->sk_cork_on = true;
        return MHD_YES;
      }
      return MHD_NO;
    }
  case MHD_UPGRADE_ACTION_CORK_OFF:
    if (! connection->sk_cork_on)
      return MHD_YES;
#ifdef HTTPS_SUPPORT
    if (0 != (daemon->options & MHD_USE_TLS) )
    {
      gnutls_record_uncork (connection->tls_session, 0);
      connection->sk_cork_on = false;
      return MHD_YES;
    }
    else
#endif
    {
      if (0 ==
          MHD_socket_cork_ (connection->socket_fd,
                            false))
      {
        connection->sk_cork_on = false;
        return MHD_YES;
      }
      return MHD_NO;
    }
  default:
    /* we don't understand this one */
    return MHD_NO;
  }
}


/**
 * We are done sending the header of a given response to the client.
 * Now it is time to perform the upgrade and hand over the connection
 * to the application.
 * @remark To be called only from thread that process connection's
 * recv(), send() and response. Must be called right after sending
 * response headers.
 *
 * @param response the response that was created for an upgrade
 * @param connection the specific connection we are upgrading
 * @return #MHD_YES on success, #MHD_NO on failure (will cause
 *        connection to be closed)
 */
enum MHD_Result
MHD_response_execute_upgrade_ (struct MHD_Response *response,
                               struct MHD_Connection *connection)
{
  struct MHD_Daemon *daemon = connection->daemon;
  struct MHD_UpgradeResponseHandle *urh;
  size_t rbo;

  if (0 == (daemon->options & MHD_ALLOW_UPGRADE))
    return MHD_NO;

  if (NULL ==
      MHD_get_response_header (response,
                               MHD_HTTP_HEADER_UPGRADE))
  {
#ifdef HAVE_MESSAGES
    MHD_DLOG (daemon,
              _ (
                "Invalid response for upgrade: application failed to set the 'Upgrade' header!\n"));
#endif
    return MHD_NO;
  }

  urh = MHD_calloc_ (1, sizeof (struct MHD_UpgradeResponseHandle));
  if (NULL == urh)
    return MHD_NO;
  urh->connection = connection;
  rbo = connection->read_buffer_offset;
  connection->read_buffer_offset = 0;
#ifdef HTTPS_SUPPORT
  if (0 != (daemon->options & MHD_USE_TLS) )
  {
    struct MemoryPool *pool;
    size_t avail;
    char *buf;
    MHD_socket sv[2];
#if defined(MHD_socket_nosignal_) || ! defined(MHD_socket_pair_nblk_)
    int res1;
    int res2;
#endif /* MHD_socket_nosignal_ || !MHD_socket_pair_nblk_ */

#ifdef MHD_socket_pair_nblk_
    if (! MHD_socket_pair_nblk_ (sv))
    {
      free (urh);
      return MHD_NO;
    }
#else  /* !MHD_socket_pair_nblk_ */
    if (! MHD_socket_pair_ (sv))
    {
      free (urh);
      return MHD_NO;
    }
    res1 = MHD_socket_nonblocking_ (sv[0]);
    res2 = MHD_socket_nonblocking_ (sv[1]);
    if ( (! res1) || (! res2) )
    {
#ifdef HAVE_MESSAGES
      MHD_DLOG (daemon,
                _ ("Failed to make loopback sockets non-blocking.\n"));
#endif
      if (! res2)
      {
        /* Socketpair cannot be used. */
        MHD_socket_close_chk_ (sv[0]);
        MHD_socket_close_chk_ (sv[1]);
        free (urh);
        return MHD_NO;
      }
    }
#endif /* !MHD_socket_pair_nblk_ */
#ifdef MHD_socket_nosignal_
    res1 = MHD_socket_nosignal_ (sv[0]);
    res2 = MHD_socket_nosignal_ (sv[1]);
    if ( (! res1) || (! res2) )
    {
#ifdef HAVE_MESSAGES
      MHD_DLOG (daemon,
                _ ("Failed to set SO_NOSIGPIPE on loopback sockets.\n"));
#endif
#ifndef MSG_NOSIGNAL
      if (! res2)
      {
        /* Socketpair cannot be used. */
        MHD_socket_close_chk_ (sv[0]);
        MHD_socket_close_chk_ (sv[1]);
        free (urh);
        return MHD_NO;
      }
#endif /* ! MSG_NOSIGNAL */
    }
#endif /* MHD_socket_nosignal_ */
    if ( (! MHD_SCKT_FD_FITS_FDSET_ (sv[1],
                                     NULL)) &&
         (0 == (daemon->options & (MHD_USE_POLL | MHD_USE_EPOLL))) )
    {
#ifdef HAVE_MESSAGES
      MHD_DLOG (daemon,
                _ ("Socketpair descriptor larger than FD_SETSIZE: %d > %d\n"),
                (int) sv[1],
                (int) FD_SETSIZE);
#endif
      MHD_socket_close_chk_ (sv[0]);
      MHD_socket_close_chk_ (sv[1]);
      free (urh);
      return MHD_NO;
    }
    urh->app.socket = sv[0];
    urh->app.urh = urh;
    urh->app.celi = MHD_EPOLL_STATE_UNREADY;
    urh->mhd.socket = sv[1];
    urh->mhd.urh = urh;
    urh->mhd.celi = MHD_EPOLL_STATE_UNREADY;
    pool = connection->pool;
    avail = MHD_pool_get_free (pool);
    if (avail < RESERVE_EBUF_SIZE)
    {
      /* connection's pool is totally at the limit,
         use our 'emergency' buffer of #RESERVE_EBUF_SIZE bytes. */
      avail = RESERVE_EBUF_SIZE;
      buf = urh->e_buf;
    }
    else
    {
      /* Normal case: grab all remaining memory from the
         connection's pool for the IO buffers; the connection
         certainly won't need it anymore as we've upgraded
         to another protocol. */
      buf = MHD_pool_allocate (pool,
                               avail,
                               false);
    }
    /* use half the buffer for inbound, half for outbound */
    urh->in_buffer_size = avail / 2;
    urh->out_buffer_size = avail - urh->in_buffer_size;
    urh->in_buffer = buf;
    urh->out_buffer = &buf[urh->in_buffer_size];
#ifdef EPOLL_SUPPORT
    /* Launch IO processing by the event loop */
    if (0 != (daemon->options & MHD_USE_EPOLL))
    {
      /* We're running with epoll(), need to add the sockets
         to the event set of the daemon's `epoll_upgrade_fd` */
      struct epoll_event event;

      mhd_assert (-1 != daemon->epoll_upgrade_fd);
      /* First, add network socket */
      event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
      event.data.ptr = &urh->app;
      if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
                          EPOLL_CTL_ADD,
                          connection->socket_fd,
                          &event))
      {
#ifdef HAVE_MESSAGES
        MHD_DLOG (daemon,
                  _ ("Call to epoll_ctl failed: %s\n"),
                  MHD_socket_last_strerr_ ());
#endif
        MHD_socket_close_chk_ (sv[0]);
        MHD_socket_close_chk_ (sv[1]);
        free (urh);
        return MHD_NO;
      }

      /* Second, add our end of the UNIX socketpair() */
      event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
      event.data.ptr = &urh->mhd;
      if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
                          EPOLL_CTL_ADD,
                          urh->mhd.socket,
                          &event))
      {
        event.events = EPOLLIN | EPOLLOUT | EPOLLPRI;
        event.data.ptr = &urh->app;
        if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
                            EPOLL_CTL_DEL,
                            connection->socket_fd,
                            &event))
          MHD_PANIC (_ ("Error cleaning up while handling epoll error.\n"));
#ifdef HAVE_MESSAGES
        MHD_DLOG (daemon,
                  _ ("Call to epoll_ctl failed: %s\n"),
                  MHD_socket_last_strerr_ ());
#endif
        MHD_socket_close_chk_ (sv[0]);
        MHD_socket_close_chk_ (sv[1]);
        free (urh);
        return MHD_NO;
      }
      EDLL_insert (daemon->eready_urh_head,
                   daemon->eready_urh_tail,
                   urh);
      urh->in_eready_list = true;
    }
#endif /* EPOLL_SUPPORT */
    if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION) )
    {
      /* This takes care of further processing for most event loops:
         simply add to DLL for bi-direcitonal processing */
      DLL_insert (daemon->urh_head,
                  daemon->urh_tail,
                  urh);
    }
    /* In thread-per-connection mode, thread will switch to forwarding once
     * connection.urh is not NULL and connection.state == MHD_CONNECTION_UPGRADE.
     */
  }
  else
  {
    urh->app.socket = MHD_INVALID_SOCKET;
    urh->mhd.socket = MHD_INVALID_SOCKET;
    /* Non-TLS connection do not hold any additional resources. */
    urh->clean_ready = true;
  }
#else  /* ! HTTPS_SUPPORT */
  urh->clean_ready = true;
#endif /* ! HTTPS_SUPPORT */
  connection->urh = urh;
  /* As far as MHD's event loops are concerned, this connection is
     suspended; it will be resumed once application is done by the
     #MHD_upgrade_action() function */
  internal_suspend_connection_ (connection);

  /* hand over socket to application */
  response->upgrade_handler (response->upgrade_handler_cls,
                             connection,
                             connection->client_context,
                             connection->read_buffer,
                             rbo,
#ifdef HTTPS_SUPPORT
                             (0 == (daemon->options & MHD_USE_TLS) ) ?
                             connection->socket_fd : urh->app.socket,
#else  /* ! HTTPS_SUPPORT */
                             connection->socket_fd,
#endif /* ! HTTPS_SUPPORT */
                             urh);
  return MHD_YES;
}


/**
 * Create a response object that can be used for 101 UPGRADE
 * responses, for example to implement WebSockets.  After sending the
 * response, control over the data stream is given to the callback (which
 * can then, for example, start some bi-directional communication).
 * If the response is queued for multiple connections, the callback
 * will be called for each connection.  The callback
 * will ONLY be called after the response header was successfully passed
 * to the OS; if there are communication errors before, the usual MHD
 * connection error handling code will be performed.
 *
 * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS)
 * and setting correct HTTP headers for the upgrade must be done
 * manually (this way, it is possible to implement most existing
 * WebSocket versions using this API; in fact, this API might be useful
 * for any protocol switch, not just WebSockets).  Note that
 * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this
 * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake"
 * cannot be generated; instead, MHD will always produce "HTTP/1.1 101
 * Switching Protocols" (if the response code 101 is used).
 *
 * As usual, the response object can be extended with header
 * information and then be used any number of times (as long as the
 * header information is not connection-specific).
 *
 * @param upgrade_handler function to call with the 'upgraded' socket
 * @param upgrade_handler_cls closure for @a upgrade_handler
 * @return NULL on error (i.e. invalid arguments, out of memory)
 */
_MHD_EXTERN struct MHD_Response *
MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
                                 void *upgrade_handler_cls)
{
  struct MHD_Response *response;

  if (NULL == upgrade_handler)
    return NULL; /* invalid request */
  response = MHD_calloc_ (1, sizeof (struct MHD_Response));
  if (NULL == response)
    return NULL;
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  if (! MHD_mutex_init_ (&response->mutex))
  {
    free (response);
    return NULL;
  }
#endif
  response->upgrade_handler = upgrade_handler;
  response->upgrade_handler_cls = upgrade_handler_cls;
  response->total_size = MHD_SIZE_UNKNOWN;
  response->reference_count = 1;
  if (MHD_NO ==
      MHD_add_response_header (response,
                               MHD_HTTP_HEADER_CONNECTION,
                               "Upgrade"))
  {
    MHD_destroy_response (response);
    return NULL;
  }
  return response;
}


#endif /* UPGRADE_SUPPORT */


/**
 * Destroy a response object and associated resources.  Note that
 * libmicrohttpd may keep some of the resources around if the response
 * is still in the queue for some clients, so the memory may not
 * necessarily be freed immediately.
 *
 * @param response response to destroy
 * @ingroup response
 */
void
MHD_destroy_response (struct MHD_Response *response)
{
  struct MHD_HTTP_Header *pos;

  if (NULL == response)
    return;
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  MHD_mutex_lock_chk_ (&response->mutex);
#endif
  if (0 != --(response->reference_count))
  {
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
    MHD_mutex_unlock_chk_ (&response->mutex);
#endif
    return;
  }
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  MHD_mutex_unlock_chk_ (&response->mutex);
  MHD_mutex_destroy_chk_ (&response->mutex);
#endif
  if (NULL != response->crfc)
    response->crfc (response->crc_cls);
  while (NULL != response->first_header)
  {
    pos = response->first_header;
    response->first_header = pos->next;
    free (pos->header);
    free (pos->value);
    free (pos);
  }
  free (response);
}


/**
 * Increments the reference counter for the @a response.
 *
 * @param response object to modify
 */
void
MHD_increment_response_rc (struct MHD_Response *response)
{
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  MHD_mutex_lock_chk_ (&response->mutex);
#endif
  (response->reference_count)++;
#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
  MHD_mutex_unlock_chk_ (&response->mutex);
#endif
}


/* end of response.c */