aboutsummaryrefslogtreecommitdiff
path: root/zenhttp/httpsys.cpp
blob: 19dba126aaa7ad3ada71f06be5debc706a290816 (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
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
// Copyright Epic Games, Inc. All Rights Reserved.

#include "httpsys.h"

#include <zencore/compactbinary.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinarypackage.h>
#include <zencore/except.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <zencore/string.h>
#include <zencore/timer.h>
#include <zenhttp/httpshared.h>

#if ZEN_WITH_HTTPSYS

#	include <conio.h>
#	include <mstcpip.h>
#	pragma comment(lib, "httpapi.lib")

std::wstring
UTF8_to_UTF16(const char* InPtr)
{
	std::wstring OutString;
	unsigned int Codepoint;

	while (*InPtr != 0)
	{
		unsigned char InChar = static_cast<unsigned char>(*InPtr);

		if (InChar <= 0x7f)
			Codepoint = InChar;
		else if (InChar <= 0xbf)
			Codepoint = (Codepoint << 6) | (InChar & 0x3f);
		else if (InChar <= 0xdf)
			Codepoint = InChar & 0x1f;
		else if (InChar <= 0xef)
			Codepoint = InChar & 0x0f;
		else
			Codepoint = InChar & 0x07;

		++InPtr;

		if (((*InPtr & 0xc0) != 0x80) && (Codepoint <= 0x10ffff))
		{
			if (Codepoint > 0xffff)
			{
				OutString.append(1, static_cast<wchar_t>(0xd800 + (Codepoint >> 10)));
				OutString.append(1, static_cast<wchar_t>(0xdc00 + (Codepoint & 0x03ff)));
			}
			else if (Codepoint < 0xd800 || Codepoint >= 0xe000)
			{
				OutString.append(1, static_cast<wchar_t>(Codepoint));
			}
		}
	}

	return OutString;
}

namespace zen {

using namespace std::literals;

class HttpSysServer;
class HttpSysTransaction;
class HttpMessageResponseRequest;

//////////////////////////////////////////////////////////////////////////

HttpVerb
TranslateHttpVerb(HTTP_VERB ReqVerb)
{
	switch (ReqVerb)
	{
		case HttpVerbOPTIONS:
			return HttpVerb::kOptions;

		case HttpVerbGET:
			return HttpVerb::kGet;

		case HttpVerbHEAD:
			return HttpVerb::kHead;

		case HttpVerbPOST:
			return HttpVerb::kPost;

		case HttpVerbPUT:
			return HttpVerb::kPut;

		case HttpVerbDELETE:
			return HttpVerb::kDelete;

		case HttpVerbCOPY:
			return HttpVerb::kCopy;

		default:
			// TODO: invalid request?
			return (HttpVerb)0;
	}
}

uint64_t
GetContentLength(const HTTP_REQUEST* HttpRequest)
{
	const HTTP_KNOWN_HEADER& clh = HttpRequest->Headers.KnownHeaders[HttpHeaderContentLength];
	std::string_view		 cl(clh.pRawValue, clh.RawValueLength);
	uint64_t				 ContentLength = 0;
	std::from_chars(cl.data(), cl.data() + cl.size(), ContentLength);
	return ContentLength;
};

HttpContentType
GetContentType(const HTTP_REQUEST* HttpRequest)
{
	const HTTP_KNOWN_HEADER& CtHdr = HttpRequest->Headers.KnownHeaders[HttpHeaderContentType];
	return ParseContentType({CtHdr.pRawValue, CtHdr.RawValueLength});
};

HttpContentType
GetAcceptType(const HTTP_REQUEST* HttpRequest)
{
	const HTTP_KNOWN_HEADER& CtHdr = HttpRequest->Headers.KnownHeaders[HttpHeaderAccept];
	return ParseContentType({CtHdr.pRawValue, CtHdr.RawValueLength});
};

/**
 * @brief Base class for any pending or active HTTP transactions
 */
class HttpSysRequestHandler
{
public:
	explicit HttpSysRequestHandler(HttpSysTransaction& Transaction) : m_Transaction(Transaction) {}
	virtual ~HttpSysRequestHandler() = default;

	virtual void				   IssueRequest(std::error_code& ErrorCode)								= 0;
	virtual HttpSysRequestHandler* HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred) = 0;
	HttpSysTransaction&			   Transaction() { return m_Transaction; }

	HttpSysRequestHandler(const HttpSysRequestHandler&) = delete;
	HttpSysRequestHandler& operator=(const HttpSysRequestHandler&) = delete;

private:
	HttpSysTransaction& m_Transaction;
};

/**
 * This is the handler for the initial HTTP I/O request which will receive the headers
 * and however much of the remaining payload might fit in the embedded request buffer.
 *
 * It is also used to receive any entity body data relating to the request
 *
 */
struct InitialRequestHandler : public HttpSysRequestHandler
{
	inline HTTP_REQUEST* HttpRequest() { return (HTTP_REQUEST*)m_RequestBuffer; }
	inline uint32_t		 RequestBufferSize() const { return sizeof m_RequestBuffer; }
	inline bool			 IsInitialRequest() const { return m_IsInitialRequest; }

	InitialRequestHandler(HttpSysTransaction& InRequest);
	~InitialRequestHandler();

	virtual void				   IssueRequest(std::error_code& ErrorCode) override final;
	virtual HttpSysRequestHandler* HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred) override;

	bool	 m_IsInitialRequest		= true;
	uint64_t m_CurrentPayloadOffset = 0;
	uint64_t m_ContentLength		= ~uint64_t(0);
	IoBuffer m_PayloadBuffer;
	UCHAR	 m_RequestBuffer[4096 + sizeof(HTTP_REQUEST)];
};

/**
 * This is the class which request handlers use to interact with the server instance
 */

class HttpSysServerRequest : public HttpServerRequest
{
public:
	HttpSysServerRequest(HttpSysTransaction& Tx, HttpService& Service, IoBuffer PayloadBuffer);
	~HttpSysServerRequest() = default;

	virtual Oid		 ParseSessionId() const override;
	virtual uint32_t ParseRequestId() const override;

	virtual IoBuffer ReadPayload() override;
	virtual void	 WriteResponse(HttpResponseCode ResponseCode) override;
	virtual void	 WriteResponse(HttpResponseCode ResponseCode, HttpContentType ContentType, std::span<IoBuffer> Blobs) override;
	virtual void	 WriteResponse(HttpResponseCode ResponseCode, HttpContentType ContentType, std::u8string_view ResponseString) override;
	virtual void	 WriteResponseAsync(std::function<void(HttpServerRequest&)>&& ContinuationHandler) override;

	using HttpServerRequest::WriteResponse;

	HttpSysServerRequest(const HttpSysServerRequest&) = delete;
	HttpSysServerRequest& operator=(const HttpSysServerRequest&) = delete;

	HttpSysTransaction&			 m_HttpTx;
	HttpSysRequestHandler*		 m_NextCompletionHandler = nullptr;
	IoBuffer					 m_PayloadBuffer;
	ExtendableStringBuilder<128> m_UriUtf8;
	ExtendableStringBuilder<128> m_QueryStringUtf8;
};

/** HTTP transaction

	There will be an instance of this per pending and in-flight HTTP transaction

  */
class HttpSysTransaction final
{
public:
	HttpSysTransaction(HttpSysServer& Server);
	virtual ~HttpSysTransaction();

	enum class Status
	{
		kDone,
		kRequestPending
	};

	Status HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred);

	static void __stdcall IoCompletionCallback(PTP_CALLBACK_INSTANCE Instance,
											   PVOID				 pContext /* HttpSysServer */,
											   PVOID				 pOverlapped,
											   ULONG				 IoResult,
											   ULONG_PTR			 NumberOfBytesTransferred,
											   PTP_IO				 Io);

	void IssueInitialRequest(std::error_code& ErrorCode);
	bool IssueNextRequest(HttpSysRequestHandler* NewCompletionHandler);

	PTP_IO				  Iocp();
	HANDLE				  RequestQueueHandle();
	inline OVERLAPPED*	  Overlapped() { return &m_HttpOverlapped; }
	inline HttpSysServer& Server() { return m_HttpServer; }
	inline HTTP_REQUEST*  HttpRequest() { return m_InitialHttpHandler.HttpRequest(); }

	HttpSysServerRequest& InvokeRequestHandler(HttpService& Service, IoBuffer Payload);

	HttpSysServerRequest& ServerRequest() { return m_HandlerRequest.value(); }

private:
	OVERLAPPED	   m_HttpOverlapped{};
	HttpSysServer& m_HttpServer;

	// Tracks which handler is due to handle the next I/O completion event
	HttpSysRequestHandler*				m_CompletionHandler = nullptr;
	RwLock								m_CompletionMutex;
	InitialRequestHandler				m_InitialHttpHandler{*this};
	std::optional<HttpSysServerRequest> m_HandlerRequest;
	Ref<IHttpPackageHandler>			m_PackageHandler;
};

/**
 * @brief HTTP request response I/O request handler
 *
 * Asynchronously streams out a response to an HTTP request via compound
 * responses from memory or directly from file
 */

class HttpMessageResponseRequest : public HttpSysRequestHandler
{
public:
	HttpMessageResponseRequest(HttpSysTransaction& InRequest, uint16_t ResponseCode);
	HttpMessageResponseRequest(HttpSysTransaction& InRequest, uint16_t ResponseCode, std::string_view Message);
	HttpMessageResponseRequest(HttpSysTransaction& InRequest,
							   uint16_t			   ResponseCode,
							   HttpContentType	   ContentType,
							   const void*		   Payload,
							   size_t			   PayloadSize);
	HttpMessageResponseRequest(HttpSysTransaction& InRequest,
							   uint16_t			   ResponseCode,
							   HttpContentType	   ContentType,
							   std::span<IoBuffer> Blobs);
	~HttpMessageResponseRequest();

	virtual void				   IssueRequest(std::error_code& ErrorCode) override final;
	virtual HttpSysRequestHandler* HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred) override;
	void						   SuppressResponseBody();	// typically used for HEAD requests

private:
	std::vector<HTTP_DATA_CHUNK> m_HttpDataChunks;
	uint64_t					 m_TotalDataSize	   = 0;	 // Sum of all chunk sizes
	uint16_t					 m_ResponseCode		   = 0;
	uint32_t					 m_NextDataChunkOffset = 0;	 // Cursor used for very large chunk lists
	uint32_t					 m_RemainingChunkCount = 0;	 // Backlog for multi-call sends
	bool						 m_IsInitialResponse   = true;
	HttpContentType				 m_ContentType		   = HttpContentType::kBinary;
	std::vector<IoBuffer>		 m_DataBuffers;

	void InitializeForPayload(uint16_t ResponseCode, std::span<IoBuffer> Blobs);
};

HttpMessageResponseRequest::HttpMessageResponseRequest(HttpSysTransaction& InRequest, uint16_t ResponseCode)
: HttpSysRequestHandler(InRequest)
{
	std::array<IoBuffer, 0> EmptyBufferList;

	InitializeForPayload(ResponseCode, EmptyBufferList);
}

HttpMessageResponseRequest::HttpMessageResponseRequest(HttpSysTransaction& InRequest, uint16_t ResponseCode, std::string_view Message)
: HttpSysRequestHandler(InRequest)
, m_ContentType(HttpContentType::kText)
{
	IoBuffer				MessageBuffer(IoBuffer::Wrap, Message.data(), Message.size());
	std::array<IoBuffer, 1> SingleBufferList({MessageBuffer});

	InitializeForPayload(ResponseCode, SingleBufferList);
}

HttpMessageResponseRequest::HttpMessageResponseRequest(HttpSysTransaction& InRequest,
													   uint16_t			   ResponseCode,
													   HttpContentType	   ContentType,
													   const void*		   Payload,
													   size_t			   PayloadSize)
: HttpSysRequestHandler(InRequest)
, m_ContentType(ContentType)
{
	IoBuffer				MessageBuffer(IoBuffer::Wrap, Payload, PayloadSize);
	std::array<IoBuffer, 1> SingleBufferList({MessageBuffer});

	InitializeForPayload(ResponseCode, SingleBufferList);
}

HttpMessageResponseRequest::HttpMessageResponseRequest(HttpSysTransaction& InRequest,
													   uint16_t			   ResponseCode,
													   HttpContentType	   ContentType,
													   std::span<IoBuffer> BlobList)
: HttpSysRequestHandler(InRequest)
, m_ContentType(ContentType)
{
	InitializeForPayload(ResponseCode, BlobList);
}

HttpMessageResponseRequest::~HttpMessageResponseRequest()
{
}

void
HttpMessageResponseRequest::InitializeForPayload(uint16_t ResponseCode, std::span<IoBuffer> BlobList)
{
	const uint32_t ChunkCount = gsl::narrow<uint32_t>(BlobList.size());

	m_HttpDataChunks.reserve(ChunkCount);
	m_DataBuffers.reserve(ChunkCount);

	for (IoBuffer& Buffer : BlobList)
	{
		m_DataBuffers.emplace_back(std::move(Buffer)).MakeOwned();
	}

	// Initialize the full array up front

	uint64_t LocalDataSize = 0;

	for (IoBuffer& Buffer : m_DataBuffers)
	{
		uint64_t BufferDataSize = Buffer.Size();

		ZEN_ASSERT(BufferDataSize);

		LocalDataSize += BufferDataSize;

		IoBufferFileReference FileRef;
		if (Buffer.GetFileReference(/* out */ FileRef))
		{
			// Use direct file transfer

			m_HttpDataChunks.push_back({});
			auto& Chunk = m_HttpDataChunks.back();

			Chunk.DataChunkType									   = HttpDataChunkFromFileHandle;
			Chunk.FromFileHandle.FileHandle						   = FileRef.FileHandle;
			Chunk.FromFileHandle.ByteRange.StartingOffset.QuadPart = FileRef.FileChunkOffset;
			Chunk.FromFileHandle.ByteRange.Length.QuadPart		   = BufferDataSize;
		}
		else
		{
			// Send from memory, need to make sure we chunk the buffer up since
			// the underlying data structure only accepts 32-bit chunk sizes for
			// memory chunks. When this happens the vector will be reallocated,
			// which is fine since this will be a pretty rare case and sending
			// the data is going to take a lot longer than a memory allocation :)

			const uint8_t* WriteCursor = reinterpret_cast<const uint8_t*>(Buffer.Data());

			while (BufferDataSize)
			{
				const ULONG ThisChunkSize = gsl::narrow<ULONG>(zen::Min(1 * 1024 * 1024 * 1024, BufferDataSize));

				m_HttpDataChunks.push_back({});
				auto& Chunk = m_HttpDataChunks.back();

				Chunk.DataChunkType			  = HttpDataChunkFromMemory;
				Chunk.FromMemory.pBuffer	  = (void*)WriteCursor;
				Chunk.FromMemory.BufferLength = ThisChunkSize;

				BufferDataSize -= ThisChunkSize;
				WriteCursor += ThisChunkSize;
			}
		}
	}

	m_RemainingChunkCount = gsl::narrow<uint32_t>(m_HttpDataChunks.size());
	m_TotalDataSize		  = LocalDataSize;

	if (m_TotalDataSize == 0 && ResponseCode == 200)
	{
		// Some HTTP clients really don't like empty responses unless a 204 response is sent
		m_ResponseCode = uint16_t(HttpResponseCode::NoContent);
	}
	else
	{
		m_ResponseCode = ResponseCode;
	}
}

void
HttpMessageResponseRequest::SuppressResponseBody()
{
	m_RemainingChunkCount = 0;
	m_HttpDataChunks.clear();
	m_DataBuffers.clear();
}

HttpSysRequestHandler*
HttpMessageResponseRequest::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred)
{
	ZEN_UNUSED(NumberOfBytesTransferred);

	if (IoResult != NO_ERROR)
	{
		ZEN_WARN("response aborted due to error: '{}'", GetSystemErrorAsString(IoResult));

		// if one transmit failed there's really no need to go on
		return nullptr;
	}

	if (m_RemainingChunkCount == 0)
	{
		return nullptr;	 // All done
	}

	return this;
}

void
HttpMessageResponseRequest::IssueRequest(std::error_code& ErrorCode)
{
	HttpSysTransaction& Tx		= Transaction();
	HTTP_REQUEST* const HttpReq = Tx.HttpRequest();
	PTP_IO const		Iocp	= Tx.Iocp();

	StartThreadpoolIo(Iocp);

	// Split payload into batches to play well with the underlying API

	const int MaxChunksPerCall = 9999;

	const int ThisRequestChunkCount	 = std::min<int>(m_RemainingChunkCount, MaxChunksPerCall);
	const int ThisRequestChunkOffset = m_NextDataChunkOffset;

	m_RemainingChunkCount -= ThisRequestChunkCount;
	m_NextDataChunkOffset += ThisRequestChunkCount;

	/* Should this code also use HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA?

		From the docs:

		This flag enables buffering of data in the kernel on a per-response basis. It should
		be used by an application doing synchronous I/O, or by a an application doing
		asynchronous I/O with no more than one send outstanding at a time.

		Applications using asynchronous I/O which may have more than one send outstanding at
		a time should not use this flag.

		When this flag is set, it should be used consistently in calls to the
		HttpSendHttpResponse function as well.
	 */

	ULONG SendFlags = HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA;

	if (m_RemainingChunkCount)
	{
		// We need to make more calls to send the full amount of data
		SendFlags |= HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
	}

	ULONG SendResult = 0;

	if (m_IsInitialResponse)
	{
		// Populate response structure

		HTTP_RESPONSE HttpResponse = {};

		HttpResponse.EntityChunkCount = USHORT(ThisRequestChunkCount);
		HttpResponse.pEntityChunks	  = m_HttpDataChunks.data() + ThisRequestChunkOffset;

		// Server header
		//
		// By default this will also add a suffix " Microsoft-HTTPAPI/2.0" to this header
		//
		// This is controlled via a registry key 'DisableServerHeader', at:
		//
		// Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters
		//
		// Set DisableServerHeader to 1 to disable suffix, or 2 to disable the header altogether
		// (only the latter appears to do anything in my testing, on Windows 10).
		//
		// (reference https://docs.microsoft.com/en-us/archive/blogs/dsnotes/wswcf-remove-server-header)
		//

		PHTTP_KNOWN_HEADER ServerHeader = &HttpResponse.Headers.KnownHeaders[HttpHeaderServer];
		ServerHeader->pRawValue			= "Zen";
		ServerHeader->RawValueLength	= (USHORT)3;

		// Content-length header

		char ContentLengthString[32];
		_ui64toa_s(m_TotalDataSize, ContentLengthString, sizeof ContentLengthString, 10);

		PHTTP_KNOWN_HEADER ContentLengthHeader = &HttpResponse.Headers.KnownHeaders[HttpHeaderContentLength];
		ContentLengthHeader->pRawValue		   = ContentLengthString;
		ContentLengthHeader->RawValueLength	   = (USHORT)strlen(ContentLengthString);

		// Content-type header

		PHTTP_KNOWN_HEADER ContentTypeHeader = &HttpResponse.Headers.KnownHeaders[HttpHeaderContentType];

		std::string_view ContentTypeString = MapContentTypeToString(m_ContentType);

		ContentTypeHeader->pRawValue	  = ContentTypeString.data();
		ContentTypeHeader->RawValueLength = (USHORT)ContentTypeString.size();

		std::string_view ReasonString = ReasonStringForHttpResultCode(m_ResponseCode);

		HttpResponse.StatusCode	  = m_ResponseCode;
		HttpResponse.pReason	  = ReasonString.data();
		HttpResponse.ReasonLength = (USHORT)ReasonString.size();

		// Cache policy

		HTTP_CACHE_POLICY CachePolicy;

		CachePolicy.Policy		  = HttpCachePolicyNocache;	 //  HttpCachePolicyUserInvalidates;
		CachePolicy.SecondsToLive = 0;

		// Initial response API call

		SendResult = HttpSendHttpResponse(Tx.RequestQueueHandle(),
										  HttpReq->RequestId,
										  SendFlags,
										  &HttpResponse,
										  &CachePolicy,
										  NULL,
										  NULL,
										  0,
										  Tx.Overlapped(),
										  NULL);

		m_IsInitialResponse = false;
	}
	else
	{
		// Subsequent response API calls

		SendResult = HttpSendResponseEntityBody(Tx.RequestQueueHandle(),
												HttpReq->RequestId,
												SendFlags,
												(USHORT)ThisRequestChunkCount,				// EntityChunkCount
												&m_HttpDataChunks[ThisRequestChunkOffset],	// EntityChunks
												NULL,										// BytesSent
												NULL,										// Reserved1
												0,											// Reserved2
												Tx.Overlapped(),							// Overlapped
												NULL										// LogData
		);
	}

	if (SendResult == NO_ERROR)
	{
		// Synchronous completion, but the completion event will still be posted to IOCP

		ErrorCode.clear();
	}
	else if (SendResult == ERROR_IO_PENDING)
	{
		// Asynchronous completion, a completion notification will be posted to IOCP

		ErrorCode.clear();
	}
	else
	{
		// An error occurred, no completion will be posted to IOCP

		CancelThreadpoolIo(Iocp);

		ZEN_ERROR("failed to send HTTP response (error: '{}'), request URL: '{}', request id: {}",
				  GetSystemErrorAsString(SendResult),
				  HttpReq->pRawUrl,
				  HttpReq->RequestId);

		ErrorCode = MakeErrorCode(SendResult);
	}
}

/** HTTP completion handler for async work

	This is used to allow work to be taken off the request handler threads
	and to support posting responses asynchronously.
 */

class HttpAsyncWorkRequest : public HttpSysRequestHandler
{
public:
	HttpAsyncWorkRequest(HttpSysTransaction& Tx, std::function<void(HttpServerRequest&)>&& Response);
	~HttpAsyncWorkRequest();

	virtual void				   IssueRequest(std::error_code& ErrorCode) override final;
	virtual HttpSysRequestHandler* HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred) override;

private:
	struct AsyncWorkItem : public IWork
	{
		virtual void Execute() override;

		AsyncWorkItem(HttpSysTransaction& InTx, std::function<void(HttpServerRequest&)>&& InHandler)
		: Tx(InTx)
		, Handler(std::move(InHandler))
		{
		}

		HttpSysTransaction&						Tx;
		std::function<void(HttpServerRequest&)> Handler;
	};

	Ref<AsyncWorkItem> m_WorkItem;
};

HttpAsyncWorkRequest::HttpAsyncWorkRequest(HttpSysTransaction& Tx, std::function<void(HttpServerRequest&)>&& Response)
: HttpSysRequestHandler(Tx)
{
	m_WorkItem = new AsyncWorkItem(Tx, std::move(Response));
}

HttpAsyncWorkRequest::~HttpAsyncWorkRequest()
{
}

void
HttpAsyncWorkRequest::IssueRequest(std::error_code& ErrorCode)
{
	ErrorCode.clear();

	Transaction().Server().WorkPool().ScheduleWork(m_WorkItem);
}

HttpSysRequestHandler*
HttpAsyncWorkRequest::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred)
{
	// This ought to not be called since there should be no outstanding I/O request
	// when this completion handler is active

	ZEN_UNUSED(IoResult, NumberOfBytesTransferred);

	ZEN_WARN("Unexpected I/O completion during async work! IoResult: {}, NumberOfBytesTransferred: {}", IoResult, NumberOfBytesTransferred);

	return this;
}

void
HttpAsyncWorkRequest::AsyncWorkItem::Execute()
{
	try
	{
		HttpSysServerRequest& ThisRequest = Tx.ServerRequest();

		ThisRequest.m_NextCompletionHandler = nullptr;

		Handler(ThisRequest);

		// TODO: should Handler be destroyed at this point to ensure there
		//		 are no outstanding references into state which could be
		//		 deleted asynchronously as a result of issuing the response?

		if (HttpSysRequestHandler* NextHandler = ThisRequest.m_NextCompletionHandler)
		{
			return (void)Tx.IssueNextRequest(NextHandler);
		}
		else if (!ThisRequest.IsHandled())
		{
			return (void)Tx.IssueNextRequest(new HttpMessageResponseRequest(Tx, 404, "Not found"sv));
		}
		else
		{
			// "Handled" but no request handler? Shouldn't ever happen
			return (void)Tx.IssueNextRequest(
				new HttpMessageResponseRequest(Tx, 500, "Response generated but no request handler scheduled"sv));
		}
	}
	catch (std::exception& Ex)
	{
		return (void)Tx.IssueNextRequest(
			new HttpMessageResponseRequest(Tx, 500, fmt::format("Exception thrown in async work: '{}'", Ex.what())));
	}
}

/**
			  _________
			 /   _____/ ______________  __ ___________
			 \_____  \_/ __ \_  __ \  \/ // __ \_  __ \
			 /        \  ___/|  | \/\   /\  ___/|  | \/
			/_______  /\___  >__|    \_/  \___  >__|
					\/     \/                 \/
*/

HttpSysServer::HttpSysServer(unsigned int ThreadCount, unsigned int AsyncWorkThreadCount)
: m_Log(logging::Get("http"))
, m_RequestLog(logging::Get("http_requests"))
, m_ThreadPool(ThreadCount)
, m_AsyncWorkPool(AsyncWorkThreadCount)
{
	ULONG Result = HttpInitialize(HTTPAPI_VERSION_2, HTTP_INITIALIZE_SERVER, nullptr);

	if (Result != NO_ERROR)
	{
		return;
	}

	m_IsHttpInitialized = true;
	m_IsOk				= true;

	ZEN_INFO("http.sys server started, using {} I/O threads and {} async worker threads", ThreadCount, AsyncWorkThreadCount);
}

HttpSysServer::~HttpSysServer()
{
	if (m_IsHttpInitialized)
	{
		Cleanup();

		HttpTerminate(HTTP_INITIALIZE_SERVER, nullptr);
	}
}

int
HttpSysServer::InitializeServer(int BasePort)
{
	using namespace std::literals;

	WideStringBuilder<64> WildcardUrlPath;
	WildcardUrlPath << u8"http://*:"sv << int64_t(BasePort) << u8"/"sv;

	m_IsOk = false;

	ULONG Result = HttpCreateServerSession(HTTPAPI_VERSION_2, &m_HttpSessionId, 0);

	if (Result != NO_ERROR)
	{
		ZEN_ERROR("Failed to create server session for '{}': {:#x}", WideToUtf8(WildcardUrlPath), Result);

		return BasePort;
	}

	Result = HttpCreateUrlGroup(m_HttpSessionId, &m_HttpUrlGroupId, 0);

	if (Result != NO_ERROR)
	{
		ZEN_ERROR("Failed to create URL group for '{}': {:#x}", WideToUtf8(WildcardUrlPath), Result);

		return BasePort;
	}

	int EffectivePort = BasePort;

	Result = HttpAddUrlToUrlGroup(m_HttpUrlGroupId, WildcardUrlPath.c_str(), HTTP_URL_CONTEXT(0), 0);

	// Sharing violation implies the port is being used by another process
	for (int PortOffset = 1; (Result == ERROR_SHARING_VIOLATION) && (PortOffset < 10); ++PortOffset)
	{
		EffectivePort = BasePort + (PortOffset * 100);
		WildcardUrlPath.Reset();
		WildcardUrlPath << u8"http://*:"sv << int64_t(EffectivePort) << u8"/"sv;

		Result = HttpAddUrlToUrlGroup(m_HttpUrlGroupId, WildcardUrlPath.c_str(), HTTP_URL_CONTEXT(0), 0);
	}

	m_BaseUris.clear();
	if (Result == NO_ERROR)
	{
		m_BaseUris.push_back(WildcardUrlPath.c_str());
	}
	else if (Result == ERROR_ACCESS_DENIED)
	{
		// If we can't register the wildcard path, we fall back to local paths
		// This local paths allow requests originating locally to function, but will not allow
		// remote origin requests to function.  This can be remedied by using netsh
		// during an install process to grant permissions to route public access to the appropriate
		// port for the current user.  eg:
		// netsh http add urlacl url=http://*:1337/ user=<some_user>

		ZEN_WARN("Unable to register handler using '{}' - falling back to local-only", WideToUtf8(WildcardUrlPath));

		const std::u8string_view Hosts[] = {u8"[::1]"sv, u8"localhost"sv, u8"127.0.0.1"sv};

		ULONG InternalResult = ERROR_SHARING_VIOLATION;
		for (int PortOffset = 0; (InternalResult == ERROR_SHARING_VIOLATION) && (PortOffset < 10); ++PortOffset)
		{
			EffectivePort = BasePort + (PortOffset * 100);

			for (const std::u8string_view Host : Hosts)
			{
				WideStringBuilder<64> LocalUrlPath;
				LocalUrlPath << u8"http://"sv << Host << u8":"sv << int64_t(EffectivePort) << u8"/"sv;

				InternalResult = HttpAddUrlToUrlGroup(m_HttpUrlGroupId, LocalUrlPath.c_str(), HTTP_URL_CONTEXT(0), 0);

				if (InternalResult == NO_ERROR)
				{
					ZEN_INFO("Registered local handler '{}'", WideToUtf8(LocalUrlPath));

					m_BaseUris.push_back(LocalUrlPath.c_str());
				}
				else
				{
					break;
				}
			}
		}
	}

	if (m_BaseUris.empty())
	{
		ZEN_ERROR("Failed to add base URL to URL group for '{}': {:#x}", WideToUtf8(WildcardUrlPath), Result);

		return BasePort;
	}

	HTTP_BINDING_INFO HttpBindingInfo = {{0}, 0};

	Result = HttpCreateRequestQueue(HTTPAPI_VERSION_2,
									/* Name */ nullptr,
									/* SecurityAttributes */ nullptr,
									/* Flags */ 0,
									&m_RequestQueueHandle);

	if (Result != NO_ERROR)
	{
		ZEN_ERROR("Failed to create request queue for '{}': {:#x}", WideToUtf8(m_BaseUris.front()), Result);

		return EffectivePort;
	}

	HttpBindingInfo.Flags.Present	   = 1;
	HttpBindingInfo.RequestQueueHandle = m_RequestQueueHandle;

	Result = HttpSetUrlGroupProperty(m_HttpUrlGroupId, HttpServerBindingProperty, &HttpBindingInfo, sizeof(HttpBindingInfo));

	if (Result != NO_ERROR)
	{
		ZEN_ERROR("Failed to set server binding property for '{}': {:#x}", WideToUtf8(m_BaseUris.front()), Result);

		return EffectivePort;
	}

	// Create I/O completion port

	std::error_code ErrorCode;
	m_ThreadPool.CreateIocp(m_RequestQueueHandle, HttpSysTransaction::IoCompletionCallback, /* Context */ this, /* out */ ErrorCode);

	if (ErrorCode)
	{
		ZEN_ERROR("Failed to create IOCP for '{}': {}", WideToUtf8(m_BaseUris.front()), ErrorCode.message());
	}
	else
	{
		m_IsOk = true;

		ZEN_INFO("Started http.sys server at '{}'", WideToUtf8(m_BaseUris.front()));
	}

	return EffectivePort;
}

void
HttpSysServer::Cleanup()
{
	++m_IsShuttingDown;

	if (m_RequestQueueHandle)
	{
		HttpCloseRequestQueue(m_RequestQueueHandle);
		m_RequestQueueHandle = nullptr;
	}

	if (m_HttpUrlGroupId)
	{
		HttpCloseUrlGroup(m_HttpUrlGroupId);
		m_HttpUrlGroupId = 0;
	}

	if (m_HttpSessionId)
	{
		HttpCloseServerSession(m_HttpSessionId);
		m_HttpSessionId = 0;
	}
}

void
HttpSysServer::StartServer()
{
	const int InitialRequestCount = 32;

	for (int i = 0; i < InitialRequestCount; ++i)
	{
		IssueNewRequestMaybe();
	}
}

void
HttpSysServer::Run(bool IsInteractive)
{
	if (IsInteractive)
	{
		zen::logging::ConsoleLog().info("Zen Server running. Press ESC or Q to quit");
	}

	do
	{
		// int WaitTimeout = -1;
		int WaitTimeout = 100;

		if (IsInteractive)
		{
			WaitTimeout = 1000;

			if (_kbhit() != 0)
			{
				char c = (char)_getch();

				if (c == 27 || c == 'Q' || c == 'q')
				{
					RequestApplicationExit(0);
				}
			}
		}

		m_ShutdownEvent.Wait(WaitTimeout);
		UpdateLofreqTimerValue();
	} while (!IsApplicationExitRequested());
}

void
HttpSysServer::OnHandlingRequest()
{
	if (--m_PendingRequests > m_MinPendingRequests)
	{
		// We have more than the minimum number of requests pending, just let someone else
		// enqueue new requests
		return;
	}

	IssueNewRequestMaybe();
}

void
HttpSysServer::IssueNewRequestMaybe()
{
	if (m_IsShuttingDown.load(std::memory_order::acquire))
	{
		return;
	}

	if (m_PendingRequests.load(std::memory_order::relaxed) >= m_MaxPendingRequests)
	{
		return;
	}

	std::unique_ptr<HttpSysTransaction> Request = std::make_unique<HttpSysTransaction>(*this);

	std::error_code ErrorCode;
	Request->IssueInitialRequest(ErrorCode);

	if (ErrorCode)
	{
		// No request was actually issued. What is the appropriate response?

		return;
	}

	// This may end up exceeding the MaxPendingRequests limit, but it's not
	// really a problem. I'm doing it this way mostly to avoid dealing with
	// exceptions here
	++m_PendingRequests;

	Request.release();
}

void
HttpSysServer::RegisterService(const char* UrlPath, HttpService& Service)
{
	if (UrlPath[0] == '/')
	{
		++UrlPath;
	}

	const std::wstring PathUtf16 = UTF8_to_UTF16(UrlPath);
	Service.SetUriPrefixLength(PathUtf16.size() + 1 /* leading slash */);

	// Convert to wide string

	for (const std::wstring& BaseUri : m_BaseUris)
	{
		std::wstring Url16 = BaseUri + PathUtf16;

		ULONG Result = HttpAddUrlToUrlGroup(m_HttpUrlGroupId, Url16.c_str(), HTTP_URL_CONTEXT(&Service), 0 /* Reserved */);

		if (Result != NO_ERROR)
		{
			ZEN_ERROR("HttpAddUrlToUrlGroup failed with result: '{}'", GetSystemErrorAsString(Result));

			return;
		}
	}
}

void
HttpSysServer::UnregisterService(const char* UrlPath, HttpService& Service)
{
	ZEN_UNUSED(Service);

	if (UrlPath[0] == '/')
	{
		++UrlPath;
	}

	const std::wstring PathUtf16 = UTF8_to_UTF16(UrlPath);

	// Convert to wide string

	for (const std::wstring& BaseUri : m_BaseUris)
	{
		std::wstring Url16 = BaseUri + PathUtf16;

		ULONG Result = HttpRemoveUrlFromUrlGroup(m_HttpUrlGroupId, Url16.c_str(), 0);

		if (Result != NO_ERROR)
		{
			ZEN_ERROR("HttpRemoveUrlFromUrlGroup failed with result: '{}'", GetSystemErrorAsString(Result));
		}
	}
}

//////////////////////////////////////////////////////////////////////////

HttpSysTransaction::HttpSysTransaction(HttpSysServer& Server) : m_HttpServer(Server), m_CompletionHandler(&m_InitialHttpHandler)
{
}

HttpSysTransaction::~HttpSysTransaction()
{
}

PTP_IO
HttpSysTransaction::Iocp()
{
	return m_HttpServer.m_ThreadPool.Iocp();
}

HANDLE
HttpSysTransaction::RequestQueueHandle()
{
	return m_HttpServer.m_RequestQueueHandle;
}

void
HttpSysTransaction::IssueInitialRequest(std::error_code& ErrorCode)
{
	m_InitialHttpHandler.IssueRequest(ErrorCode);
}

void
HttpSysTransaction::IoCompletionCallback(PTP_CALLBACK_INSTANCE Instance,
										 PVOID				   pContext /* HttpSysServer */,
										 PVOID				   pOverlapped,
										 ULONG				   IoResult,
										 ULONG_PTR			   NumberOfBytesTransferred,
										 PTP_IO				   Io)
{
	UNREFERENCED_PARAMETER(Io);
	UNREFERENCED_PARAMETER(Instance);
	UNREFERENCED_PARAMETER(pContext);

	// Note that for a given transaction we may be in this completion function on more
	// than one thread at any given moment. This means we need to be careful about what
	// happens in here

	HttpSysTransaction* Transaction = CONTAINING_RECORD(pOverlapped, HttpSysTransaction, m_HttpOverlapped);

	if (Transaction->HandleCompletion(IoResult, NumberOfBytesTransferred) == HttpSysTransaction::Status::kDone)
	{
		delete Transaction;
	}
}

bool
HttpSysTransaction::IssueNextRequest(HttpSysRequestHandler* NewCompletionHandler)
{
	HttpSysRequestHandler* CurrentHandler = m_CompletionHandler;
	m_CompletionHandler					  = NewCompletionHandler;

	auto _ = MakeGuard([this, CurrentHandler] {
		if ((CurrentHandler != &m_InitialHttpHandler) && (CurrentHandler != m_CompletionHandler))
		{
			delete CurrentHandler;
		}
	});

	if (NewCompletionHandler == nullptr)
	{
		return false;
	}

	try
	{
		std::error_code ErrorCode;
		m_CompletionHandler->IssueRequest(ErrorCode);

		if (!ErrorCode)
		{
			return true;
		}

		ZEN_ERROR("IssueRequest() failed: '{}'", ErrorCode.message());
	}
	catch (std::exception& Ex)
	{
		ZEN_ERROR("exception caught in IssueNextRequest(): '{}'", Ex.what());
	}

	// something went wrong, no request is pending
	m_CompletionHandler = nullptr;

	return false;
}

HttpSysTransaction::Status
HttpSysTransaction::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred)
{
	// We use this to ensure sequential execution of completion handlers
	// for any given transaction. It also ensures all member variables are
	// in a consistent state for the current thread

	RwLock::ExclusiveLockScope _(m_CompletionMutex);

	bool IsRequestPending = false;

	if (HttpSysRequestHandler* CurrentHandler = m_CompletionHandler)
	{
		if ((CurrentHandler == &m_InitialHttpHandler) && m_InitialHttpHandler.IsInitialRequest())
		{
			// Ensure we have a sufficient number of pending requests outstanding
			m_HttpServer.OnHandlingRequest();
		}

		auto NewCompletionHandler = CurrentHandler->HandleCompletion(IoResult, NumberOfBytesTransferred);

		IsRequestPending = IssueNextRequest(NewCompletionHandler);
	}

	// Ensure new requests are enqueued as necessary
	m_HttpServer.IssueNewRequestMaybe();

	if (IsRequestPending)
	{
		// There is another request pending on this transaction, so it needs to remain valid
		return Status::kRequestPending;
	}

	if (m_HttpServer.m_IsRequestLoggingEnabled)
	{
		if (m_HandlerRequest.has_value())
		{
			m_HttpServer.m_RequestLog.info("{} {}", ToString(m_HandlerRequest->RequestVerb()), m_HandlerRequest->RelativeUri());
		}
	}

	// Transaction done, caller should clean up (delete) this instance
	return Status::kDone;
}

HttpSysServerRequest&
HttpSysTransaction::InvokeRequestHandler(HttpService& Service, IoBuffer Payload)
{
	HttpSysServerRequest& ThisRequest = m_HandlerRequest.emplace(*this, Service, Payload);

	// Default request handling

	if (!HandlePackageOffers(Service, ThisRequest, m_PackageHandler))
	{
		Service.HandleRequest(ThisRequest);
	}

	return ThisRequest;
}

//////////////////////////////////////////////////////////////////////////

HttpSysServerRequest::HttpSysServerRequest(HttpSysTransaction& Tx, HttpService& Service, IoBuffer PayloadBuffer)
: m_HttpTx(Tx)
, m_PayloadBuffer(std::move(PayloadBuffer))
{
	const HTTP_REQUEST* HttpRequestPtr = Tx.HttpRequest();

	const int PrefixLength	= Service.UriPrefixLength();
	const int AbsPathLength = HttpRequestPtr->CookedUrl.AbsPathLength / sizeof(wchar_t);

	HttpContentType AcceptContentType = HttpContentType::kUnknownContentType;

	if (AbsPathLength >= PrefixLength)
	{
		// We convert the URI immediately because most of the code involved prefers to deal
		// with utf8. This is overhead which I'd prefer to avoid but for now we just have
		// to live with it

		WideToUtf8({(wchar_t*)HttpRequestPtr->CookedUrl.pAbsPath + PrefixLength, gsl::narrow<size_t>(AbsPathLength - PrefixLength)},
				   m_UriUtf8);

		std::string_view UriSuffix8{m_UriUtf8};

		const size_t LastComponentIndex = UriSuffix8.find_last_of('/');

		if (LastComponentIndex != std::string_view::npos)
		{
			UriSuffix8.remove_prefix(LastComponentIndex);
		}

		const size_t LastDotIndex = UriSuffix8.find_last_of('.');

		if (LastDotIndex != std::string_view::npos)
		{
			UriSuffix8.remove_prefix(LastDotIndex + 1);

			AcceptContentType = ParseContentType(UriSuffix8);

			if (AcceptContentType != HttpContentType::kUnknownContentType)
			{
				m_UriUtf8.RemoveSuffix((uint32_t)(UriSuffix8.size() + 1));
			}
		}
	}
	else
	{
		m_UriUtf8.Reset();
	}

	m_Uri = std::string_view(m_UriUtf8);

	if (uint16_t QueryStringLength = HttpRequestPtr->CookedUrl.QueryStringLength)
	{
		--QueryStringLength;  // We skip the leading question mark

		WideToUtf8({(wchar_t*)(HttpRequestPtr->CookedUrl.pQueryString) + 1, QueryStringLength / sizeof(wchar_t)}, m_QueryStringUtf8);
	}
	else
	{
		m_QueryStringUtf8.Reset();
	}

	m_QueryString	= std::string_view(m_QueryStringUtf8);
	m_Verb			= TranslateHttpVerb(HttpRequestPtr->Verb);
	m_ContentLength = GetContentLength(HttpRequestPtr);
	m_ContentType	= GetContentType(HttpRequestPtr);

	// It an explicit content type extension was specified then we'll use that over any
	// Accept: header value that may be present

	if (AcceptContentType != HttpContentType::kUnknownContentType)
	{
		m_AcceptType = AcceptContentType;
	}
	else
	{
		m_AcceptType = GetAcceptType(HttpRequestPtr);
	}

	if (m_Verb == HttpVerb::kHead)
	{
		SetSuppressResponseBody();
	}
}

Oid
HttpSysServerRequest::ParseSessionId() const
{
	const HTTP_REQUEST* HttpRequestPtr = m_HttpTx.HttpRequest();

	for (int i = 0; i < HttpRequestPtr->Headers.UnknownHeaderCount; ++i)
	{
		HTTP_UNKNOWN_HEADER& Header = HttpRequestPtr->Headers.pUnknownHeaders[i];
		std::string_view	 HeaderName{Header.pName, Header.NameLength};

		if (HeaderName == "UE-Session"sv)
		{
			if (Header.RawValueLength == Oid::StringLength)
			{
				return Oid::FromHexString({Header.pRawValue, Header.RawValueLength});
			}
		}
	}

	return {};
}

uint32_t
HttpSysServerRequest::ParseRequestId() const
{
	const HTTP_REQUEST* HttpRequestPtr = m_HttpTx.HttpRequest();

	for (int i = 0; i < HttpRequestPtr->Headers.UnknownHeaderCount; ++i)
	{
		HTTP_UNKNOWN_HEADER& Header = HttpRequestPtr->Headers.pUnknownHeaders[i];
		std::string_view	 HeaderName{Header.pName, Header.NameLength};

		if (HeaderName == "UE-Request"sv)
		{
			std::string_view RequestValue{Header.pRawValue, Header.RawValueLength};
			uint32_t		 RequestId = 0;
			std::from_chars(RequestValue.data(), RequestValue.data() + RequestValue.size(), RequestId);
			return RequestId;
		}
	}

	return 0;
}

IoBuffer
HttpSysServerRequest::ReadPayload()
{
	return m_PayloadBuffer;
}

void
HttpSysServerRequest::WriteResponse(HttpResponseCode ResponseCode)
{
	ZEN_ASSERT(IsHandled() == false);

	auto Response = new HttpMessageResponseRequest(m_HttpTx, (uint16_t)ResponseCode);

	if (SuppressBody())
	{
		Response->SuppressResponseBody();
	}

	m_NextCompletionHandler = Response;

	SetIsHandled();
}

void
HttpSysServerRequest::WriteResponse(HttpResponseCode ResponseCode, HttpContentType ContentType, std::span<IoBuffer> Blobs)
{
	ZEN_ASSERT(IsHandled() == false);

	auto Response = new HttpMessageResponseRequest(m_HttpTx, (uint16_t)ResponseCode, ContentType, Blobs);

	if (SuppressBody())
	{
		Response->SuppressResponseBody();
	}

	m_NextCompletionHandler = Response;

	SetIsHandled();
}

void
HttpSysServerRequest::WriteResponse(HttpResponseCode ResponseCode, HttpContentType ContentType, std::u8string_view ResponseString)
{
	ZEN_ASSERT(IsHandled() == false);

	auto Response =
		new HttpMessageResponseRequest(m_HttpTx, (uint16_t)ResponseCode, ContentType, ResponseString.data(), ResponseString.size());

	if (SuppressBody())
	{
		Response->SuppressResponseBody();
	}

	m_NextCompletionHandler = Response;

	SetIsHandled();
}

void
HttpSysServerRequest::WriteResponseAsync(std::function<void(HttpServerRequest&)>&& ContinuationHandler)
{
	if (m_HttpTx.Server().IsAsyncResponseEnabled())
	{
		ContinuationHandler(m_HttpTx.ServerRequest());
	}
	else
	{
		m_NextCompletionHandler = new HttpAsyncWorkRequest(m_HttpTx, std::move(ContinuationHandler));
	}
}

//////////////////////////////////////////////////////////////////////////

InitialRequestHandler::InitialRequestHandler(HttpSysTransaction& InRequest) : HttpSysRequestHandler(InRequest)
{
}

InitialRequestHandler::~InitialRequestHandler()
{
}

void
InitialRequestHandler::IssueRequest(std::error_code& ErrorCode)
{
	HttpSysTransaction& Tx		= Transaction();
	PTP_IO				Iocp	= Tx.Iocp();
	HTTP_REQUEST*		HttpReq = Tx.HttpRequest();

	StartThreadpoolIo(Iocp);

	ULONG HttpApiResult;

	if (IsInitialRequest())
	{
		HttpApiResult = HttpReceiveHttpRequest(Tx.RequestQueueHandle(),
											   HTTP_NULL_ID,
											   HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY,
											   HttpReq,
											   RequestBufferSize(),
											   NULL,
											   Tx.Overlapped());
	}
	else
	{
		// The http.sys team recommends limiting the size to 128KB
		static const uint64_t kMaxBytesPerApiCall = 128 * 1024;

		uint64_t	   BytesToRead		   = m_ContentLength - m_CurrentPayloadOffset;
		const uint64_t BytesToReadThisCall = zen::Min(BytesToRead, kMaxBytesPerApiCall);
		void*		   BufferWriteCursor   = reinterpret_cast<uint8_t*>(m_PayloadBuffer.MutableData()) + m_CurrentPayloadOffset;

		HttpApiResult = HttpReceiveRequestEntityBody(Tx.RequestQueueHandle(),
													 HttpReq->RequestId,
													 0, /* Flags */
													 BufferWriteCursor,
													 gsl::narrow<ULONG>(BytesToReadThisCall),
													 nullptr,  // BytesReturned
													 Tx.Overlapped());
	}

	if (HttpApiResult != ERROR_IO_PENDING && HttpApiResult != NO_ERROR)
	{
		CancelThreadpoolIo(Iocp);

		ErrorCode = MakeErrorCode(HttpApiResult);

		ZEN_ERROR("HttpReceiveHttpRequest failed, error: '{}'", ErrorCode.message());

		return;
	}

	ErrorCode.clear();
}

HttpSysRequestHandler*
InitialRequestHandler::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTransferred)
{
	auto _ = MakeGuard([&] { m_IsInitialRequest = false; });

	switch (IoResult)
	{
		default:
		case ERROR_OPERATION_ABORTED:
			return nullptr;

		case ERROR_MORE_DATA:  // Insufficient buffer space
		case NO_ERROR:
			break;
	}

	// Route request

	try
	{
		HTTP_REQUEST* HttpReq = HttpRequest();

#	if 0
		for (int i = 0; i < HttpReq->RequestInfoCount; ++i)
		{
			auto& ReqInfo = HttpReq->pRequestInfo[i];

			switch (ReqInfo.InfoType)
			{
				case HttpRequestInfoTypeRequestTiming:
					{
						const HTTP_REQUEST_TIMING_INFO* TimingInfo = reinterpret_cast<HTTP_REQUEST_TIMING_INFO*>(ReqInfo.pInfo);

						ZEN_INFO("");
					}
					break;
				case HttpRequestInfoTypeAuth:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeChannelBind:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeSslProtocol:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeSslTokenBindingDraft:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeSslTokenBinding:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeTcpInfoV0:
					{
						const TCP_INFO_v0* TcpInfo = reinterpret_cast<const TCP_INFO_v0*>(ReqInfo.pInfo);

						ZEN_INFO("");
					}
					break;
				case HttpRequestInfoTypeRequestSizing:
					{
						const HTTP_REQUEST_SIZING_INFO* SizingInfo = reinterpret_cast<const HTTP_REQUEST_SIZING_INFO*>(ReqInfo.pInfo);
						ZEN_INFO("");
					}
					break;
				case HttpRequestInfoTypeQuicStats:
					ZEN_INFO("");
					break;
				case HttpRequestInfoTypeTcpInfoV1:
					{
						const TCP_INFO_v1* TcpInfo = reinterpret_cast<const TCP_INFO_v1*>(ReqInfo.pInfo);

						ZEN_INFO("");
					}
					break;
			}
		}
#	endif

		if (HttpService* Service = reinterpret_cast<HttpService*>(HttpReq->UrlContext))
		{
			if (m_IsInitialRequest)
			{
				m_ContentLength					  = GetContentLength(HttpReq);
				const HttpContentType ContentType = GetContentType(HttpReq);

				if (m_ContentLength)
				{
					// Handle initial chunk read by copying any payload which has already been copied
					// into our embedded request buffer

					m_PayloadBuffer = IoBuffer(m_ContentLength);
					m_PayloadBuffer.SetContentType(ContentType);

					uint64_t	   BytesToRead		 = m_ContentLength;
					uint8_t* const BufferBase		 = reinterpret_cast<uint8_t*>(m_PayloadBuffer.MutableData());
					uint8_t*	   BufferWriteCursor = BufferBase;

					const int EntityChunkCount = HttpReq->EntityChunkCount;

					for (int i = 0; i < EntityChunkCount; ++i)
					{
						HTTP_DATA_CHUNK& EntityChunk = HttpReq->pEntityChunks[i];

						ZEN_ASSERT(EntityChunk.DataChunkType == HttpDataChunkFromMemory);

						const uint64_t BufferLength = EntityChunk.FromMemory.BufferLength;

						ZEN_ASSERT(BufferLength <= BytesToRead);

						memcpy(BufferWriteCursor, EntityChunk.FromMemory.pBuffer, BufferLength);

						BufferWriteCursor += BufferLength;
						BytesToRead -= BufferLength;
					}

					m_CurrentPayloadOffset = BufferWriteCursor - BufferBase;
				}
			}
			else
			{
				m_CurrentPayloadOffset += NumberOfBytesTransferred;
			}

			if (m_CurrentPayloadOffset != m_ContentLength)
			{
				// Body not complete, issue another read request to receive more body data
				return this;
			}

			// Request body received completely

			m_PayloadBuffer.MakeImmutable();

			HttpSysServerRequest& ThisRequest = Transaction().InvokeRequestHandler(*Service, m_PayloadBuffer);

			if (HttpSysRequestHandler* Response = ThisRequest.m_NextCompletionHandler)
			{
				return Response;
			}

			if (!ThisRequest.IsHandled())
			{
				return new HttpMessageResponseRequest(Transaction(), 404, "Not found"sv);
			}
		}

		// Unable to route
		return new HttpMessageResponseRequest(Transaction(), 404, "No suitable route found"sv);
	}
	catch (std::exception& ex)
	{
		ZEN_ERROR("Caught exception while handling request: '{}'", ex.what());

		return new HttpMessageResponseRequest(Transaction(), 500, ex.what());
	}
}

//////////////////////////////////////////////////////////////////////////
//
// HttpServer interface implementation
//

int
HttpSysServer::Initialize(int BasePort)
{
	int EffectivePort = InitializeServer(BasePort);
	StartServer();
	return EffectivePort;
}

void
HttpSysServer::RequestExit()
{
	m_ShutdownEvent.Set();
}
void
HttpSysServer::RegisterService(HttpService& Service)
{
	RegisterService(Service.BaseUri(), Service);
}

}  // namespace zen
#endif