forked from tjanczuk/httpsys
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpsys.cc
More file actions
1130 lines (909 loc) · 35.9 KB
/
Copy pathhttpsys.cc
File metadata and controls
1130 lines (909 loc) · 35.9 KB
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
#include "httpsys.h"
/*
Design notes:
- Only one async operation per HTTP request should be outstanding at a time. JavaScript
must ensure not to initiate another async operation (e.g. httpsys_write_body) before
the ongoing one completes. This implies JavaScript must manage a state machine around a request
and buffer certain calls from user code (e.g. writing multiple chunks of response body before
previous write completes)
- Native resources are released by native code if async operation completes with error.
- If JavaScript encounters an error it must explicitly request native resources to be released.
In particular there is no exception contract between JavaScript callback and native code.
- JavaScript cannot make any additional calls into native in the context of a particular request
after it has been called with an error event type; at that time all native resources had already
been cleaned up.
*/
using namespace v8;
int initialized;
int initialBufferSize;
Persistent<Function> callback;
Persistent<Function> bufferConstructor;
// Global V8 strings reused across requests
Handle<String> v8uv_httpsys_server;
Handle<String> v8method;
Handle<String> v8req;
Handle<String> v8httpHeaders;
Handle<String> v8httpVersionMajor;
Handle<String> v8httpVersionMinor;
Handle<String> v8eventType;
Handle<String> v8code;
Handle<String> v8url;
Handle<String> v8uv_httpsys;
Handle<String> v8data;
Handle<String> v8statusCode;
Handle<String> v8reason;
Handle<String> v8knownHeaders;
Handle<String> v8unknownHeaders;
Handle<String> v8isLastChunk;
Handle<String> v8chunks;
// Maps HTTP_HEADER_ID enum to v8 string
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364526(v=vs.85).aspx
Handle<String> v8httpRequestHeaderNames[HttpHeaderRequestMaximum];
char* requestHeaders[] = {
"cache-control",
"connection",
"date",
"keep-alive",
"pragma",
"trailer",
"transfer-encoding",
"upgrade",
"via",
"warning",
"alive",
"content-length",
"content-type",
"content-encoding",
"content-language",
"content-location",
"content-md5",
"content-range",
"expires",
"last-modified",
"accept",
"accept-charset",
"accept-encoding",
"accept-language",
"authorization",
"cookie",
"expect",
"from",
"host",
"if-match",
"if-modified-since",
"if-none-match",
"if-range",
"if-unmodified-since",
"max-forwards",
"proxy-authorization",
"referer",
"range",
"te",
"translate",
"user-agent"
};
// Maps HTTP_VERB enum to V8 string
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364664(v=vs.85).aspx
Handle<String> v8verbs[HttpVerbMaximum];
char* verbs[] = {
NULL,
NULL,
NULL,
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DETELE",
"TRACE",
"CONNECT",
"TRACK",
"MOVE",
"COPY",
"PROPFIND",
"PROPPATCH",
"MKCOL",
"LOCK",
"UNLOCK",
"SEARCH"
};
// Processing common to all callbacks from HTTP.SYS:
// - map the uv_async_t handle to uv_httpsys_t
// - decrement event loop reference count to indicate completion of async operation
#define HTTPSYS_CALLBACK_PREAMBLE \
HandleScope handleScope; \
uv_httpsys_t* uv_httpsys = CONTAINING_RECORD(handle, uv_httpsys_t, uv_async); \
uv_unref((uv_handle_t*)&uv_httpsys->uv_async); \
uv_httpsys->uv_async.loop = NULL; \
PHTTP_REQUEST request = (PHTTP_REQUEST)uv_httpsys->buffer;
// Processing common to most exported methods:
// - declare handle scope and hr
// - extract uv_httpsys_t from the 'uv_httpsys' member of the object passed as the first parameter
#define HTTPSYS_EXPORT_PREAMBLE \
HandleScope handleScope; \
HRESULT hr; \
uv_httpsys_t* uv_httpsys = (uv_httpsys_t*)args[0]->ToObject()->Get(v8uv_httpsys)->Uint32Value();
void uv_insert_pending_req(uv_loop_t* loop, uv_req_t* req)
{
req->next_req = NULL;
if (loop->pending_reqs_tail) {
req->next_req = loop->pending_reqs_tail->next_req;
loop->pending_reqs_tail->next_req = req;
loop->pending_reqs_tail = req;
} else {
req->next_req = req;
loop->pending_reqs_tail = req;
}
}
Handle<Value> httpsys_make_callback(Handle<Value> options)
{
HandleScope handleScope;
Handle<Value> argv[] = { options };
TryCatch try_catch;
Handle<Value> result = callback->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
return handleScope.Close(result);
}
Handle<Object> httpsys_create_event(uv_httpsys_server_t* uv_httpsys_server, int eventType)
{
HandleScope handleScope;
Handle<Object> event = Object::New();
event->Set(v8eventType, Integer::NewFromUnsigned(eventType));
event->Set(v8uv_httpsys_server, Integer::NewFromUnsigned((uint32_t)uv_httpsys_server));
return handleScope.Close(event);
}
Handle<Object> httpsys_create_event(uv_httpsys_t* uv_httpsys, int eventType)
{
HandleScope handleScope;
Handle<Object> event = Object::New();
event->Set(v8eventType, Integer::NewFromUnsigned(eventType));
event->Set(v8uv_httpsys, Integer::NewFromUnsigned((uint32_t)uv_httpsys));
event->Set(v8uv_httpsys_server, Integer::NewFromUnsigned((uint32_t)uv_httpsys->uv_httpsys_server));
return handleScope.Close(event);
}
Handle<Value> httpsys_notify_error(uv_httpsys_server_t* uv_httpsys_server, uv_httpsys_event_type errorType, int code)
{
HandleScope handleScope;
Handle<Object> error = httpsys_create_event(uv_httpsys_server, errorType);
error->Set(v8code, Integer::NewFromUnsigned(code));
return handleScope.Close(httpsys_make_callback(error));
}
Handle<Value> httpsys_notify_error(uv_httpsys_t* uv_httpsys, uv_httpsys_event_type errorType, int code)
{
HandleScope handleScope;
Handle<Object> error = httpsys_create_event(uv_httpsys, errorType);
error->Set(v8code, Integer::NewFromUnsigned(code));
return handleScope.Close(httpsys_make_callback(error));
}
void httpsys_new_request_callback(uv_async_t* handle, int status)
{
HTTPSYS_CALLBACK_PREAMBLE
HRESULT hr;
// Copy the request ID assigned to the request by HTTP.SYS to uv_httpsys
// to start subsequent async operations related to this request
uv_httpsys->requestId = request->RequestId;
// Increase the count of new read requests to initialize to replace the one that just completed.
// Actual initialization will be done in the uv_prepare callback httpsys_prepare_new_requests
// associated with this server.
uv_httpsys->uv_httpsys_server->readsToInitialize++;
// Process async completion
if (S_OK != uv_httpsys->uv_async.async_req.overlapped.Internal)
{
// Async completion failed - notify JavaScript
httpsys_notify_error(
uv_httpsys,
HTTPSYS_ERROR_NEW_REQUEST,
uv_httpsys->uv_async.async_req.overlapped.Internal);
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
else
{
// New request received - notify JavaScript
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_NEW_REQUEST);
// Create the 'req' object representing the request
Handle<Object> req = Object::New();
event->Set(v8req, req);
// Add HTTP verb information
if (HttpVerbUnknown == request->Verb)
{
req->Set(v8method, String::New(request->pUnknownVerb));
}
else
{
req->Set(v8method, v8verbs[request->Verb]);
}
// Add known HTTP header information
Handle<Object> headers = Object::New();
req->Set(v8httpHeaders, headers);
for (int i = 0; i < HttpHeaderRequestMaximum; i++)
{
if (request->Headers.KnownHeaders[i].RawValueLength > 0)
{
headers->Set(v8httpRequestHeaderNames[i], String::New(
request->Headers.KnownHeaders[i].pRawValue,
request->Headers.KnownHeaders[i].RawValueLength));
}
}
// Add custom HTTP header information
for (int i = 0; i < request->Headers.UnknownHeaderCount; i++)
{
// TODO: lowercase unknown header names
headers->Set(
String::New(
request->Headers.pUnknownHeaders[i].pName,
request->Headers.pUnknownHeaders[i].NameLength),
String::New(
request->Headers.pUnknownHeaders[i].pRawValue,
request->Headers.pUnknownHeaders[i].RawValueLength));
}
// TODO: process trailers
// Add HTTP version information
req->Set(v8httpVersionMajor, Integer::NewFromUnsigned(request->Version.MajorVersion));
req->Set(v8httpVersionMinor, Integer::NewFromUnsigned(request->Version.MinorVersion));
// Add URL information
req->Set(v8url, String::New(request->pRawUrl, request->RawUrlLength));
// Invoke the JavaScript callback passing event as the only paramater
Handle<Value> result = httpsys_make_callback(event);
if (result->IsBoolean() && result->BooleanValue())
{
// If the callback response is 'true', proceed to process the request body.
// Otherwise request had been paused and will be resumed asynchronously from JavaScript
// with a call to httpsys_resume.
if (0 == (request->Flags & HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS))
{
// This is a body-less request. Notify JavaScript the request is finished.
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_END_REQUEST);
httpsys_make_callback(event);
}
else if (S_OK != (hr = httpsys_initiate_read_request_body(uv_httpsys)))
{
// Initiation failed - notify JavaScript
httpsys_notify_error(uv_httpsys, HTTPSYS_ERROR_INITIALIZING_READ_REQUEST_BODY, hr);
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
}
}
}
HRESULT httpsys_initiate_new_request(uv_httpsys_t* uv_httpsys)
{
HRESULT hr;
// Create libuv async handle and initialize it
CheckError(uv_async_init(uv_default_loop(), &uv_httpsys->uv_async, httpsys_new_request_callback));
// Allocate initial buffer to receice the HTTP request
uv_httpsys->bufferSize = initialBufferSize;
ErrorIf(NULL == (uv_httpsys->buffer = malloc(uv_httpsys->bufferSize)), ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(uv_httpsys->buffer, uv_httpsys->bufferSize);
// Initiate async receive of a new request with HTTP.SYS, using the OVERLAPPED
// associated with the default libuv event loop.
hr = HttpReceiveHttpRequest(
uv_httpsys->uv_httpsys_server->requestQueue,
HTTP_NULL_ID,
0,
(PHTTP_REQUEST)uv_httpsys->buffer,
uv_httpsys->bufferSize,
NULL,
&uv_httpsys->uv_async.async_req.overlapped);
if (NO_ERROR == hr)
{
// Synchronous completion.
httpsys_new_request_callback(&uv_httpsys->uv_async, 0);
}
else
{
ErrorIf(ERROR_IO_PENDING != hr, hr);
}
return S_OK;
Error:
return hr;
}
void httpsys_free_chunks(uv_httpsys_t* uv_httpsys)
{
if (uv_httpsys->chunk.FromMemory.pBuffer)
{
free(uv_httpsys->chunk.FromMemory.pBuffer);
RtlZeroMemory(&uv_httpsys->chunk, sizeof(uv_httpsys->chunk));
}
}
void httpsys_free(uv_httpsys_t* uv_httpsys)
{
if (NULL != uv_httpsys)
{
httpsys_free_chunks(uv_httpsys);
if (uv_httpsys->response.pReason)
{
free((void*)uv_httpsys->response.pReason);
}
for (int i = 0; i < HttpHeaderResponseMaximum; i++)
{
if (uv_httpsys->response.Headers.KnownHeaders[i].pRawValue)
{
free((void*)uv_httpsys->response.Headers.KnownHeaders[i].pRawValue);
}
}
if (uv_httpsys->response.Headers.pUnknownHeaders)
{
for (int i = 0; i < uv_httpsys->response.Headers.UnknownHeaderCount; i++)
{
if (uv_httpsys->response.Headers.pUnknownHeaders[i].pName)
{
free((void*)uv_httpsys->response.Headers.pUnknownHeaders[i].pName);
}
if (uv_httpsys->response.Headers.pUnknownHeaders[i].pRawValue)
{
free((void*)uv_httpsys->response.Headers.pUnknownHeaders[i].pRawValue);
}
}
free(uv_httpsys->response.Headers.pUnknownHeaders);
}
RtlZeroMemory(&uv_httpsys->response, sizeof (uv_httpsys->response));
if (NULL != uv_httpsys->uv_async.loop)
{
uv_unref((uv_handle_t*)&uv_httpsys->uv_async);
}
if (NULL != uv_httpsys->buffer)
{
free(uv_httpsys->buffer);
uv_httpsys->buffer = NULL;
}
free(uv_httpsys);
uv_httpsys = NULL;
}
}
void httpsys_read_request_body_callback(uv_async_t* handle, int status)
{
HTTPSYS_CALLBACK_PREAMBLE
HRESULT hr;
// Process async completion
if (ERROR_HANDLE_EOF == uv_httpsys->uv_async.async_req.overlapped.Internal)
{
// End of request body - notify JavaScript
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_END_REQUEST);
httpsys_make_callback(event);
}
else if (S_OK != uv_httpsys->uv_async.async_req.overlapped.Internal)
{
// Async completion failed - notify JavaScript
httpsys_notify_error(
uv_httpsys,
HTTPSYS_ERROR_READ_REQUEST_BODY,
uv_httpsys->uv_async.async_req.overlapped.Internal);
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
else
{
// Successful completion - send body chunk to JavaScript as a Buffer
// Good explanation of native Buffers at
// http://sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_REQUEST_BODY);
ULONG length = uv_httpsys->uv_async.async_req.overlapped.InternalHigh;
node::Buffer* slowBuffer = node::Buffer::New(length);
memcpy(node::Buffer::Data(slowBuffer), uv_httpsys->buffer, length);
Handle<Value> args[] = { slowBuffer->handle_, Integer::New(length), Integer::New(0) };
Handle<Object> fastBuffer = bufferConstructor->NewInstance(3, args);
event->Set(v8data, fastBuffer);
Handle<Value> result = httpsys_make_callback(event);
if (result->IsBoolean() && result->BooleanValue())
{
// If the callback response is 'true', proceed to read more of the request body.
// Otherwise request had been paused and will be resumed asynchronously from JavaScript
// with a call to httpsys_resume.
if (S_OK != (hr = httpsys_initiate_read_request_body(uv_httpsys)))
{
// Initiation failed - notify JavaScript
httpsys_notify_error(uv_httpsys, HTTPSYS_ERROR_INITIALIZING_READ_REQUEST_BODY, hr);
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
}
}
}
HRESULT httpsys_initiate_read_request_body(uv_httpsys_t* uv_httpsys)
{
HandleScope handleScope;
HRESULT hr;
// Initialize libuv handle representing this async operation
RtlZeroMemory(&uv_httpsys->uv_async, sizeof(uv_async_t));
CheckError(uv_async_init(uv_default_loop(), &uv_httpsys->uv_async, httpsys_read_request_body_callback));
// Initiate async receive of the HTTP request body
hr = HttpReceiveRequestEntityBody(
uv_httpsys->uv_httpsys_server->requestQueue,
uv_httpsys->requestId,
0,
uv_httpsys->buffer,
uv_httpsys->bufferSize,
NULL,
&uv_httpsys->uv_async.async_req.overlapped);
if (ERROR_HANDLE_EOF == hr)
{
// End of request body, decrement libuv loop ref count since no async completion will follow
// and generate JavaScript event
uv_unref((uv_handle_t*)&uv_httpsys->uv_async);
uv_httpsys->uv_async.loop = NULL;
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_END_REQUEST);
httpsys_make_callback(event);
}
else if (NO_ERROR == hr)
{
// Synchronous completion. Insert a pending req into libuv loop to execute the callback after
// unwinding the stack without posting a completion to the IO completion port.
//uv_insert_pending_req(uv_httpsys->uv_async.loop, &uv_httpsys->uv_async.async_req);
httpsys_read_request_body_callback(&uv_httpsys->uv_async, 0);
}
else
{
ErrorIf(ERROR_IO_PENDING != hr, hr);
}
return S_OK;
Error:
return hr;
}
Handle<Value> httpsys_init(const Arguments& args)
{
HandleScope handleScope;
Handle<Object> options = args[0]->ToObject();
callback.Dispose();
callback.Clear();
callback = Persistent<Function>::New(
Handle<Function>::Cast(options->Get(String::New("callback"))));
initialBufferSize = options->Get(String::New("initialBufferSize"))->Int32Value();
return handleScope.Close(Undefined());
}
void httpsys_prepare_new_requests(uv_prepare_t* handle, int status)
{
uv_httpsys_server_t* uv_httpsys_server = CONTAINING_RECORD(handle, uv_httpsys_server_t, uv_prepare);
HRESULT hr;
uv_httpsys_t* uv_httpsys = NULL;
while (uv_httpsys_server->readsToInitialize)
{
// TODO: address a situation when some new requests fail while others not - cancel them?
ErrorIf(NULL == (uv_httpsys = (uv_httpsys_t*)malloc(sizeof(uv_httpsys_t))),
ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(uv_httpsys, sizeof(uv_httpsys_t));
uv_httpsys->uv_httpsys_server = uv_httpsys_server;
CheckError(httpsys_initiate_new_request(uv_httpsys));
uv_httpsys = NULL;
uv_httpsys_server->readsToInitialize--;
}
return;
Error:
if (NULL != uv_httpsys)
{
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
httpsys_notify_error(uv_httpsys_server, HTTPSYS_ERROR_INITIALIZING_REQUEST, hr);
return;
}
Handle<Value> httpsys_listen(const Arguments& args)
{
HandleScope handleScope;
HRESULT hr;
HTTPAPI_VERSION HttpApiVersion = HTTPAPI_VERSION_2;
WCHAR url[MAX_PATH + 1];
HTTP_BINDING_INFO bindingInfo;
uv_loop_t* loop;
Handle<Value> result;
uv_httpsys_t* uv_httpsys = NULL;
uv_httpsys_server_t* uv_httpsys_server = NULL;
// Process arguments
Handle<Object> options = args[0]->ToObject();
// Lazy, one-time initialization of HTTP.SYS
if (!initialized)
{
CheckError(HttpInitialize(
HttpApiVersion,
HTTP_INITIALIZE_SERVER,
NULL));
initialized = 1;
}
// Create uv_httpsys_server_t
ErrorIf(NULL == (uv_httpsys_server = (uv_httpsys_server_t*)malloc(sizeof(uv_httpsys_server_t))),
ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(uv_httpsys_server, sizeof(uv_httpsys_server_t));
// Create HTTP.SYS session and associate it with URL group containing the
// single listen URL.
CheckError(HttpCreateServerSession(
HttpApiVersion,
&uv_httpsys_server->sessionId,
NULL));
CheckError(HttpCreateUrlGroup(
uv_httpsys_server->sessionId,
&uv_httpsys_server->groupId,
NULL));
options->Get(String::New("url"))->ToString()->Write((uint16_t*)url, 0, MAX_PATH);
CheckError(HttpAddUrlToUrlGroup(
uv_httpsys_server->groupId,
url,
0,
NULL));
// Create the request queue name by replacing slahes in the URL with _
// to make it a valid file name.
for (WCHAR* current = url; *current; current++)
{
if (L'/' == *current)
{
*current = L'_';
}
}
// Create HTTP.SYS request queue (one per URL). Request queues are named
// to allow sharing between processes and support cluster.
// First try to obtain a handle to a pre-existing queue with the name
// based on the listen URL. If that fails, create a new named request queue.
hr = HttpCreateRequestQueue(
HttpApiVersion,
url,
NULL,
HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING,
&uv_httpsys_server->requestQueue);
if (ERROR_FILE_NOT_FOUND == hr)
{
// Request queue by that name does not exist yet, try to create it
CheckError(HttpCreateRequestQueue(
HttpApiVersion,
url,
NULL,
0,
&uv_httpsys_server->requestQueue));
}
else
{
CheckError(hr);
}
// Configure the request queue to prevent queuing a completion to the libuv
// IO completion port when an async operation completes synchronously.
ErrorIf(!SetFileCompletionNotificationModes(
uv_httpsys_server->requestQueue,
FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE),
GetLastError());
// Bind the request queue with the URL group to enable receiving
// HTTP traffic on the request queue.
RtlZeroMemory(&bindingInfo, sizeof(HTTP_BINDING_INFO));
bindingInfo.RequestQueueHandle = uv_httpsys_server->requestQueue;
bindingInfo.Flags.Present = 1;
CheckError(HttpSetUrlGroupProperty(
uv_httpsys_server->groupId,
HttpServerBindingProperty,
&bindingInfo,
sizeof(HTTP_BINDING_INFO)));
// Associate the HTTP.SYS request queue handle with the IO completion port
// of the default libuv event loop used by node. This will cause
// async completions related to the HTTP.SYS request queue to execute
// on the node.js thread. The event loop will process these events as
// UV_ASYNC handle types, beacuse a call to uv_async_init will be made
// every time an async operation is started with HTTP.SYS. On Windows,
// uv_async_init associates the OVERLAPPED structure representing the
// async operation with the uv_async_t handle that embeds it, which allows
// the event loop to map the OVERLAPPED instance back to the async
// callback to invoke when the IO completion port is signaled.
loop = uv_default_loop();
ErrorIf(NULL == CreateIoCompletionPort(
uv_httpsys_server->requestQueue,
loop->iocp,
(ULONG_PTR)uv_httpsys_server->requestQueue,
0),
GetLastError());
// Initiate uv_prepare associated with this server that will be responsible for
// initializing new pending receives of new HTTP reqests against HTTP.SYS
// to replace completed ones. This logic will run once per iteration of the libuv event loop.
// The first execution of the callback will initiate the first batch of reads.
uv_prepare_init(loop, &uv_httpsys_server->uv_prepare);
uv_prepare_start(&uv_httpsys_server->uv_prepare, httpsys_prepare_new_requests);
uv_httpsys_server->readsToInitialize = options->Get(String::New("pendingReadCount"))->Uint32Value();
// TODO: uv_httpsys_server representation will need to be fixed on 64-bit systems.
result = Integer::NewFromUnsigned((uint32_t)uv_httpsys_server);
return handleScope.Close(result);
Error:
if (NULL != uv_httpsys_server)
{
if (HTTP_NULL_ID != uv_httpsys_server->groupId)
{
HttpCloseUrlGroup(uv_httpsys_server->groupId);
}
if (NULL != uv_httpsys_server->requestQueue)
{
HttpCloseRequestQueue(uv_httpsys_server->requestQueue);
}
if (HTTP_NULL_ID != uv_httpsys_server->sessionId)
{
HttpCloseServerSession(uv_httpsys_server->sessionId);
}
free(uv_httpsys_server);
uv_httpsys_server = NULL;
}
if (NULL != uv_httpsys)
{
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
return handleScope.Close(ThrowException(Int32::New(hr)));
}
Handle<Value> httpsys_stop_listen(const Arguments& args)
{
HandleScope handleScope;
HRESULT hr;
uv_httpsys_server_t* uv_httpsys_server = (uv_httpsys_server_t*)args[0]->Uint32Value();
CheckError(HttpCloseUrlGroup(uv_httpsys_server->groupId));
CheckError(HttpCloseRequestQueue(uv_httpsys_server->requestQueue));
CheckError(HttpCloseServerSession(uv_httpsys_server->sessionId));
uv_prepare_stop(&uv_httpsys_server->uv_prepare);
return handleScope.Close(Undefined());
Error:
return handleScope.Close(ThrowException(Int32::New(hr)));
}
Handle<Value> httpsys_resume(const Arguments& args)
{
HTTPSYS_EXPORT_PREAMBLE;
CheckError(httpsys_initiate_read_request_body(uv_httpsys));
return handleScope.Close(Undefined());
Error:
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
return handleScope.Close(ThrowException(Int32::New(hr)));
}
Handle<Value> httpsys_write_headers(const Arguments& args)
{
HTTPSYS_EXPORT_PREAMBLE;
Handle<Object> options = args[0]->ToObject();
String::Utf8Value reason(options->Get(v8reason));
Handle<Object> unknownHeaders;
Handle<Array> headerNames;
Handle<String> headerName;
Handle<Array> knownHeaders;
ULONG flags;
// Initialize libuv handle representing this async operation
RtlZeroMemory(&uv_httpsys->uv_async, sizeof(uv_async_t));
CheckError(uv_async_init(uv_default_loop(), &uv_httpsys->uv_async, httpsys_write_callback));
// Set response status code and reason
uv_httpsys->response.StatusCode = options->Get(v8statusCode)->Uint32Value();
ErrorIf(NULL == (uv_httpsys->response.pReason = (PCSTR)malloc(reason.length())),
ERROR_NOT_ENOUGH_MEMORY);
uv_httpsys->response.ReasonLength = reason.length();
memcpy((void*)uv_httpsys->response.pReason, *reason, reason.length());
// Set known headers
knownHeaders = Handle<Array>::Cast(options->Get(v8knownHeaders));
for (int i = 0; i < HttpHeaderResponseMaximum; i++)
{
Handle<Value> knownHeader = knownHeaders->Get(i);
if (!knownHeader->IsUndefined())
{
String::Utf8Value header(knownHeader);
ErrorIf(NULL == (uv_httpsys->response.Headers.KnownHeaders[i].pRawValue =
(PCSTR)malloc(header.length())),
ERROR_NOT_ENOUGH_MEMORY);
uv_httpsys->response.Headers.KnownHeaders[i].RawValueLength = header.length();
memcpy((void*)uv_httpsys->response.Headers.KnownHeaders[i].pRawValue,
*header, header.length());
}
}
// Set unknown headers
unknownHeaders = options->Get(v8unknownHeaders)->ToObject();
headerNames = unknownHeaders->GetOwnPropertyNames();
if (headerNames->Length() > 0)
{
ErrorIf(NULL == (uv_httpsys->response.Headers.pUnknownHeaders =
(PHTTP_UNKNOWN_HEADER)malloc(headerNames->Length() * sizeof (HTTP_UNKNOWN_HEADER))),
ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(uv_httpsys->response.Headers.pUnknownHeaders,
headerNames->Length() * sizeof (HTTP_UNKNOWN_HEADER));
uv_httpsys->response.Headers.UnknownHeaderCount = headerNames->Length();
for (int i = 0; i < uv_httpsys->response.Headers.UnknownHeaderCount; i++)
{
headerName = headerNames->Get(i)->ToString();
String::Utf8Value headerNameUtf8(headerName);
String::Utf8Value headerValueUtf8(unknownHeaders->Get(headerName));
uv_httpsys->response.Headers.pUnknownHeaders[i].NameLength = headerNameUtf8.length();
ErrorIf(NULL == (uv_httpsys->response.Headers.pUnknownHeaders[i].pName =
(PCSTR)malloc(headerNameUtf8.length())),
ERROR_NOT_ENOUGH_MEMORY);
memcpy((void*)uv_httpsys->response.Headers.pUnknownHeaders[i].pName,
*headerNameUtf8, headerNameUtf8.length());
uv_httpsys->response.Headers.pUnknownHeaders[i].RawValueLength = headerValueUtf8.length();
ErrorIf(NULL == (uv_httpsys->response.Headers.pUnknownHeaders[i].pRawValue =
(PCSTR)malloc(headerValueUtf8.length())),
ERROR_NOT_ENOUGH_MEMORY);
memcpy((void*)uv_httpsys->response.Headers.pUnknownHeaders[i].pRawValue,
*headerValueUtf8, headerValueUtf8.length());
}
}
// Prepare response body and determine flags
CheckError(httpsys_initialize_body_chunks(options, uv_httpsys, &flags));
if (uv_httpsys->chunk.FromMemory.pBuffer)
{
uv_httpsys->response.EntityChunkCount = 1;
uv_httpsys->response.pEntityChunks = &uv_httpsys->chunk;
}
// TOOD: support response trailers
// Initiate async send of the HTTP response headers and optional body
hr = HttpSendHttpResponse(
uv_httpsys->uv_httpsys_server->requestQueue,
uv_httpsys->requestId,
flags,
&uv_httpsys->response,
NULL,
NULL,
NULL,
0,
&uv_httpsys->uv_async.async_req.overlapped,
NULL);
if (NO_ERROR == hr)
{
// Synchronous completion. Insert a pending req into libuv loop to execute the callback after
// unwinding the stack without posting a completion to the IO completion port.
// uv_insert_pending_req(uv_httpsys->uv_async.loop, &uv_httpsys->uv_async.async_req);
httpsys_write_callback(&uv_httpsys->uv_async, 0);
}
else
{
ErrorIf(ERROR_IO_PENDING != hr, hr);
}
return handleScope.Close(Undefined());
Error:
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
return handleScope.Close(ThrowException(Int32::New(hr)));
}
void httpsys_write_callback(uv_async_t* handle, int status)
{
HTTPSYS_CALLBACK_PREAMBLE;
// Process async completion
if (S_OK != uv_httpsys->uv_async.async_req.overlapped.Internal)
{
// Async completion failed - notify JavaScript
httpsys_notify_error(
uv_httpsys,
HTTPSYS_ERROR_WRITING,
uv_httpsys->uv_async.async_req.overlapped.Internal);
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
else
{
// Successful completion
Handle<Object> event = httpsys_create_event(uv_httpsys, HTTPSYS_WRITTEN);
if (uv_httpsys->lastChunkSent)
{
// Response is completed - clean up resources
httpsys_free(uv_httpsys);
uv_httpsys = NULL;
}
httpsys_make_callback(event);
}
}
HRESULT httpsys_initialize_body_chunks(Handle<Object> options, uv_httpsys_t* uv_httpsys, ULONG* flags)
{
HRESULT hr;
HandleScope handleScope;
Handle<Array> chunks;
httpsys_free_chunks(uv_httpsys);
// Copy JavaScript buffers representing response body chunks into a single
// continuous memory block in an HTTP_DATA_CHUNK.
chunks = Handle<Array>::Cast(options->Get(v8chunks));
if (chunks->Length() > 0)
{
for (unsigned int i = 0; i < chunks->Length(); i++) {
Handle<Object> buffer = chunks->Get(i)->ToObject();
uv_httpsys->chunk.FromMemory.BufferLength += node::Buffer::Length(buffer);
}
ErrorIf(NULL == (uv_httpsys->chunk.FromMemory.pBuffer =
malloc(uv_httpsys->chunk.FromMemory.BufferLength)),
ERROR_NOT_ENOUGH_MEMORY);
char* position = (char*)uv_httpsys->chunk.FromMemory.pBuffer;
for (unsigned int i = 0; i < chunks->Length(); i++)
{
Handle<Object> buffer = chunks->Get(i)->ToObject();
memcpy(position, node::Buffer::Data(buffer), node::Buffer::Length(buffer));
position += node::Buffer::Length(buffer);
}
}
// Remove the 'chunks' propert from the options object to indicate they have been
// consumed.
ErrorIf(!options->Delete(v8chunks), E_FAIL);
// Determine whether the last of the response body is to be written out.
if (options->Get(v8isLastChunk)->IsBoolean() && options->Get(v8isLastChunk)->BooleanValue())
{
*flags = 0;