-
Notifications
You must be signed in to change notification settings - Fork 581
/
Copy pathcprotocolbridge.cpp
1951 lines (1615 loc) · 74.4 KB
/
cprotocolbridge.cpp
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 "precomp.h"
HRESULT CProtocolBridge::PostponeProcessing(CNodeHttpStoredContext* context, DWORD dueTime)
{
CAsyncManager* async = context->GetNodeApplication()->GetApplicationManager()->GetAsyncManager();
LARGE_INTEGER delay;
delay.QuadPart = dueTime;
delay.QuadPart *= -10000; // convert from ms to 100ns units
return async->SetTimer(context->GetAsyncContext(), &delay);
}
#define LOCAL127 0x0100007F // 127.0.0.1
BOOL CProtocolBridge::IsLocalCall(IHttpContext* ctx)
{
PSOCKADDR src = ctx->GetRequest()->GetRemoteAddress();
PSOCKADDR dest = ctx->GetRequest()->GetLocalAddress();
if (AF_INET == src->sa_family && AF_INET == dest->sa_family)
{
DWORD srcAddress = ntohl(((PSOCKADDR_IN)src)->sin_addr.s_addr);
DWORD destAddress = ntohl(((PSOCKADDR_IN)dest)->sin_addr.s_addr);
return srcAddress == destAddress || LOCAL127 == srcAddress || LOCAL127 == destAddress;
}
else if (AF_INET6 == src->sa_family && AF_INET6 == dest->sa_family)
{
IN6_ADDR* srcAddress = &((PSOCKADDR_IN6)src)->sin6_addr;
IN6_ADDR* destAddress = &((PSOCKADDR_IN6)dest)->sin6_addr;
if (0 == memcmp(srcAddress, destAddress, sizeof IN6_ADDR))
{
return TRUE;
}
if (IN6_IS_ADDR_LOOPBACK(srcAddress) || IN6_IS_ADDR_LOOPBACK(destAddress))
{
return TRUE;
}
}
return FALSE;
}
BOOL CProtocolBridge::SendIisnodeError(IHttpContext* httpCtx, HRESULT hr)
{
if (IISNODE_ERROR_UNABLE_TO_READ_CONFIGURATION == hr || IISNODE_ERROR_UNABLE_TO_READ_CONFIGURATION_OVERRIDE == hr)
{
if (CProtocolBridge::IsLocalCall(httpCtx))
{
switch (hr) {
default:
return FALSE;
case IISNODE_ERROR_UNABLE_TO_READ_CONFIGURATION:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"iisnode was unable to read the configuration file. Make sure the web.config file syntax is correct. In particular, verify the "
" <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"iisnode configuration section</a> matches the expected schema. The schema of the iisnode section that your version of iisnode requires is stored in the "
"%systemroot%\\system32\\inetsrv\\config\\schema\\iisnode_schema.xml file.");
break;
case IISNODE_ERROR_UNABLE_TO_READ_CONFIGURATION_OVERRIDE:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"iisnode was unable to read the configuration file iisnode.yml. Make sure the iisnode.yml file syntax is correct. For reference, check "
" <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/iisnode.yml"">"
"the sample iisnode.yml file</a>. The property names recognized in the iisnode.yml file of your version of iisnode are stored in the "
"%systemroot%\\system32\\inetsrv\\config\\schema\\iisnode_schema.xml file.");
break;
};
return TRUE;
}
else
{
return FALSE;
}
}
if (!CModuleConfiguration::GetDevErrorsEnabled(httpCtx))
{
return FALSE;
}
switch (hr) {
default:
return FALSE;
case IISNODE_ERROR_UNRECOGNIZED_DEBUG_COMMAND:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"Unrecognized debugging command. Supported commands are ?debug (default), ?brk, and ?kill.");
break;
case IISNODE_ERROR_UNABLE_TO_FIND_DEBUGGING_PORT:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"The debugger was unable to acquire a TCP port to establish communication with the debugee. "
"This may be due to lack of free TCP ports in the range specified in the <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"system.webServer/iisnode/@debuggerPortRange</a> configuration "
"section, or due to lack of permissions to create TCP listeners by the identity of the IIS worker process.");
break;
case IISNODE_ERROR_UNABLE_TO_CONNECT_TO_DEBUGEE:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"The debugger was unable to connect to the the debugee. "
"This may be due to the debugee process terminating during startup (e.g. due to an unhandled exception) or "
"failing to establish a TCP listener on the debugging port. ");
break;
case IISNODE_ERROR_INSPECTOR_NOT_FOUND:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"The version of iisnode installed on the server does not support remote debugging. "
"To use remote debugging, please update your iisnode installation on the server to one available from "
"<a href=""http://github.com/tjanczuk/iisnode/downloads"">http://github.com/tjanczuk/iisnode/downloads</a>. "
"We apologize for inconvenience.");
break;
case IISNODE_ERROR_UNABLE_TO_CREATE_DEBUGGER_FILES:
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
"The iisnode module is unable to deploy supporting files necessary to initialize the debugger. "
"Please check that the identity of the IIS application pool running the node.js application has read and write access "
"permissions to the directory on the server where the node.js application is located.");
break;
case IISNODE_ERROR_UNABLE_TO_START_NODE_EXE:
char* errorMessage =
"The iisnode module is unable to start the node.exe process. Make sure the node.exe executable is available "
"at the location specified in the <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"system.webServer/iisnode/@nodeProcessCommandLine</a> element of web.config. "
"By default node.exe is expected in one of the directories listed in the PATH environment variable.";
CProtocolBridge::SendSyncResponse(
httpCtx,
200,
"OK",
hr,
TRUE,
errorMessage);
break;
};
return TRUE;
}
BOOL CProtocolBridge::SendIisnodeError(CNodeHttpStoredContext* ctx, HRESULT hr)
{
if (CProtocolBridge::SendIisnodeError(ctx->GetHttpContext(), hr))
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode request processing failed for reasons recognized by iisnode", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
if (INVALID_HANDLE_VALUE != ctx->GetPipe())
{
CloseHandle(ctx->GetPipe());
ctx->SetPipe(INVALID_HANDLE_VALUE);
}
CProtocolBridge::FinalizeResponseCore(
ctx,
RQ_NOTIFICATION_FINISH_REQUEST,
hr,
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider(),
L"iisnode posts completion from SendIisnodeError",
WINEVENT_LEVEL_VERBOSE);
return TRUE;
}
return FALSE;
}
BOOL CProtocolBridge::SendDevError(CNodeHttpStoredContext* context,
USHORT status,
USHORT subStatus,
PCTSTR reason,
HRESULT hresult,
BOOL disableCache)
{
HRESULT hr;
DWORD rawLogSize, htmlLogSize, htmlTotalSize;
IHttpContext* ctx;
char* rawLog;
char* templ1;
char* templ2;
char* templ3;
char* html;
char* current;
if (500 <= status && CModuleConfiguration::GetDevErrorsEnabled(context->GetHttpContext()) && NULL != context->GetNodeProcess())
{
// return a friendly HTTP 200 response with HTML entity body that contains error details
// and the content of node.exe stdout/err, if available
ctx = context->GetHttpContext();
rawLog = context->GetNodeProcess()->TryGetLog(ctx, &rawLogSize);
templ1 =
"<p>iisnode encountered an error when processing the request.</p><pre style=\"background-color: eeeeee\">"
"HRESULT: 0x%x\n"
"HTTP status: %d\n"
"HTTP subStatus: %d\n"
"HTTP reason: %s</pre>"
"<p>You are receiving this HTTP 200 response because <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"system.webServer/iisnode/@devErrorsEnabled</a> configuration setting is 'true'.</p>"
"<p>In addition to the log of stdout and stderr of the node.exe process, consider using "
"<a href=""http://tomasz.janczuk.org/2011/11/debug-nodejs-applications-on-windows.html"">debugging</a> "
"and <a href=""http://tomasz.janczuk.org/2011/09/using-event-tracing-for-windows-to.html"">ETW traces</a> to further diagnose the problem.</p>";
templ2 = "<p>The node.exe process has not written any information to stderr or iisnode was unable to capture this information. "
"Frequent reason is that the iisnode module is unable to create a log file to capture stdout and stderr output from node.exe. "
"Please check that the identity of the IIS application pool running the node.js application has read and write access "
"permissions to the directory on the server where the node.js application is located. Alternatively you can disable logging "
"by setting <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"system.webServer/iisnode/@loggingEnabled</a> element of web.config to 'false'.";
templ3="<p>You may get additional information about this error condition by logging stdout and stderr of the node.exe process."
"To enable logging, set the <a href=""https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config"">"
"system.webServer/iisnode/@loggingEnabled</a> configuration setting to 'true' (current value is 'false').</p>";
// calculate HTML encoded size of the log
htmlLogSize = 0;
for (int i = 0; i < rawLogSize; i++)
{
if (rawLog[i] >= 0 && rawLog[i] <= 0x8
|| rawLog[i] >= 0xb && rawLog[i] <= 0xc
|| rawLog[i] >= 0xe && rawLog[i] <= 0x1f
|| rawLog[i] >= 0x80 && rawLog[i] <= 0x9f)
{
// characters disallowed in HTML will be converted to [xAB] notation, thus taking 5 bytes
htmlLogSize += 5;
}
else
{
switch (rawLog[i])
{
default:
htmlLogSize++;
break;
case '&':
htmlLogSize += 5; // &
break;
case '<':
case '>':
htmlLogSize += 4; // < >
break;
case '"':
case '\'':
htmlLogSize += 6; // " '
break;
};
}
}
// calculate total size of HTML and allocate memory
htmlTotalSize = strlen(templ1) + 20 /* hresult */ + 20 /* status code */ + strlen(reason) + strlen(templ2) /* log content heading */ + htmlLogSize;
ErrorIf(NULL == (html = (char*)ctx->AllocateRequestMemory(htmlTotalSize)), ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(html, htmlTotalSize);
// construct the HTML
sprintf(html, templ1, hresult, status, subStatus, reason);
if (0 == rawLogSize)
{
if (CModuleConfiguration::GetLoggingEnabled(ctx))
{
strcat(html, templ2);
}
else
{
strcat(html, templ3);
}
}
else
{
strcat(html, "<p>The last 64k of the output generated by the node.exe process to stderr is shown below:</p><pre style=\"background-color: eeeeee\">");
current = html + strlen(html);
if (htmlLogSize == rawLogSize)
{
// no HTML encoding is necessary
memcpy(current, rawLog, rawLogSize);
}
else
{
// HTML encode the log
for (int i = 0; i < rawLogSize; i++)
{
if (rawLog[i] >= 0 && rawLog[i] <= 0x8
|| rawLog[i] >= 0xb && rawLog[i] <= 0xc
|| rawLog[i] >= 0xe && rawLog[i] <= 0x1f
|| rawLog[i] >= 0x80 && rawLog[i] <= 0x9f)
{
// characters disallowed in HTML are converted to [xAB] notation
*current++ = '[';
*current++ = 'x';
*current = rawLog[i] >> 4;
*current++ += *current > 9 ? 'A' - 10 : '0';
*current = rawLog[i] & 15;
*current++ += *current > 9 ? 'A' - 10 : '0';
*current++ = ']';
}
else
{
switch (rawLog[i])
{
default:
*current++ = rawLog[i];
break;
case '&':
*current++ = '&';
*current++ = 'a';
*current++ = 'm';
*current++ = 'p';
*current++ = ';';
break;
case '<':
*current++ = '&';
*current++ = 'l';
*current++ = 't';
*current++ = ';';
break;
case '>':
*current++ = '&';
*current++ = 'g';
*current++ = 't';
*current++ = ';';
break;
case '"':
*current++ = '&';
*current++ = 'q';
*current++ = 'u';
*current++ = 'o';
*current++ = 't';
*current++ = ';';
break;
case '\'':
*current++ = '&';
*current++ = 'a';
*current++ = 'p';
*current++ = 'o';
*current++ = 's';
*current++ = ';';
break;
};
}
}
}
}
// send the response
CheckError(CProtocolBridge::SendSyncResponse(
ctx,
200,
"OK",
hresult,
TRUE,
html));
return true;
}
Error:
return false;
}
HRESULT CProtocolBridge::SendEmptyResponse(CNodeHttpStoredContext* context, USHORT status, USHORT subStatus, PCTSTR reason, HRESULT hresult, BOOL disableCache)
{
context->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(context->GetHttpContext(),
L"iisnode request processing failed for reasons unrecognized by iisnode", WINEVENT_LEVEL_VERBOSE, context->GetActivityId());
if (INVALID_HANDLE_VALUE != context->GetPipe())
{
CloseHandle(context->GetPipe());
context->SetPipe(INVALID_HANDLE_VALUE);
}
if (!CProtocolBridge::SendDevError(context, status, subStatus, reason, hresult, disableCache))
{
// return default IIS response
CProtocolBridge::SendEmptyResponse(context->GetHttpContext(), status, subStatus, reason, hresult, disableCache);
}
CProtocolBridge::FinalizeResponseCore(
context,
RQ_NOTIFICATION_FINISH_REQUEST,
hresult,
context->GetNodeApplication()->GetApplicationManager()->GetEventProvider(),
L"iisnode posts completion from SendEmtpyResponse",
WINEVENT_LEVEL_VERBOSE);
return S_OK;
}
HRESULT CProtocolBridge::SendSyncResponse(IHttpContext* httpCtx, USHORT status, PCTSTR reason, HRESULT hresult, BOOL disableCache, PCSTR htmlBody)
{
HRESULT hr;
DWORD bytesSent;
HTTP_DATA_CHUNK body;
CProtocolBridge::SendEmptyResponse(httpCtx, status, 0, reason, hresult, disableCache);
IHttpResponse* response = httpCtx->GetResponse();
response->SetHeader(HttpHeaderContentType, "text/html", 9, TRUE);
body.DataChunkType = HttpDataChunkFromMemory;
body.FromMemory.pBuffer = (PVOID)htmlBody;
body.FromMemory.BufferLength = strlen(htmlBody);
CheckError(response->WriteEntityChunks(&body, 1, FALSE, FALSE, &bytesSent));
return S_OK;
Error:
return hr;
}
void CProtocolBridge::SendEmptyResponse(IHttpContext* httpCtx, USHORT status, USHORT subStatus, PCTSTR reason, HRESULT hresult, BOOL disableCache)
{
if (!httpCtx->GetResponseHeadersSent())
{
httpCtx->GetResponse()->Clear();
httpCtx->GetResponse()->SetStatus(status, reason, subStatus, hresult);
if (disableCache)
{
httpCtx->GetResponse()->SetHeader(HttpHeaderCacheControl, "no-cache", 8, TRUE);
}
}
}
HRESULT CProtocolBridge::InitiateRequest(CNodeHttpStoredContext* context)
{
HRESULT hr;
BOOL requireChildContext = FALSE;
BOOL mainDebuggerPage = FALSE;
IHttpContext* child = NULL;
BOOL completionExpected;
// determine what the target path of the request is
if (context->GetNodeApplication()->IsDebugger())
{
// All debugger URLs require rewriting. Requests for static content will be processed using a child http context and served
// by a static file handler. Debugging protocol requests will continue executing in the current context and be processed
// by the node-inspector application.
CheckError(CNodeDebugger::DispatchDebuggingRequest(context, &requireChildContext, &mainDebuggerPage));
}
else
{
// For application requests, if the URL rewrite module had been used to rewrite the URL,
// present the original URL to the node.js application instead of the re-written one.
PCSTR url;
USHORT urlLength;
IHttpRequest* request = context->GetHttpContext()->GetRequest();
if (NULL == (url = request->GetHeader("X-Original-URL", &urlLength)))
{
HTTP_REQUEST* raw = request->GetRawHttpRequest();
// Fix for https://github.com/tjanczuk/iisnode/issues/296
PSTR path = NULL;
int pathSizeA = 0;
int cchAbsPathLength = (raw->CookedUrl.AbsPathLength + raw->CookedUrl.QueryStringLength) >> 1;
ErrorIf(0 == (pathSizeA = WideCharToMultiByte(CP_ACP, 0, raw->CookedUrl.pAbsPath, cchAbsPathLength, NULL, 0, NULL, NULL)), E_FAIL);
ErrorIf(NULL == (path = (TCHAR*)context->GetHttpContext()->AllocateRequestMemory(pathSizeA + 1)), ERROR_NOT_ENOUGH_MEMORY);
ErrorIf(pathSizeA != WideCharToMultiByte(CP_ACP, 0, raw->CookedUrl.pAbsPath, cchAbsPathLength, path, pathSizeA, NULL, NULL), E_FAIL);
path[pathSizeA] = 0;
context->SetTargetUrl(path, pathSizeA);
}
else
{
context->SetTargetUrl(url, urlLength);
}
}
// determine how to process the request
if (requireChildContext)
{
CheckError(context->GetHttpContext()->CloneContext(CLONE_FLAG_BASICS | CLONE_FLAG_ENTITY | CLONE_FLAG_HEADERS, &child));
if (mainDebuggerPage)
{
// Prevent client caching of responses to requests for debugger entry points e.g. app.js/debug or app.js/debug?brk
// This is to allow us to run initialization logic on the server if necessary every time user refreshes the page
// Static content subordinate to the main debugger page is eligible for client side caching
child->GetResponse()->SetHeader(HttpHeaderCacheControl, "no-cache", 8, TRUE);
}
CheckError(child->GetRequest()->SetUrl(context->GetTargetUrl(), context->GetTargetUrlLength(), FALSE));
context->SetChildContext(child);
context->SetNextProcessor(CProtocolBridge::ChildContextCompleted);
CheckError(context->GetHttpContext()->ExecuteRequest(TRUE, child, 0, NULL, &completionExpected));
if (!completionExpected)
{
CProtocolBridge::ChildContextCompleted(S_OK, 0, context->GetOverlapped());
}
}
else
{
context->SetNextProcessor(CProtocolBridge::CreateNamedPipeConnection);
CProtocolBridge::CreateNamedPipeConnection(S_OK, 0, context->InitializeOverlapped());
}
return S_OK;
Error:
if (child)
{
child->ReleaseClonedContext();
child = NULL;
context->SetChildContext(NULL);
}
return hr;
}
void WINAPI CProtocolBridge::ChildContextCompleted(DWORD error, DWORD bytesTransfered, LPOVERLAPPED overlapped)
{
CNodeHttpStoredContext* ctx = CNodeHttpStoredContext::Get(overlapped);
ctx->GetChildContext()->ReleaseClonedContext();
ctx->SetChildContext(NULL);
if (S_OK == error)
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode finished processing child http request", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
}
else
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode failed to process child http request", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
}
ctx->SetHresult(error);
ctx->SetRequestNotificationStatus(RQ_NOTIFICATION_CONTINUE);
ctx->SetNextProcessor(NULL);
CProtocolBridge::FinalizeResponseCore(
ctx,
RQ_NOTIFICATION_CONTINUE,
error,
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider(),
L"iisnode posts completion from ChildContextCompleted",
WINEVENT_LEVEL_VERBOSE);
return;
}
void WINAPI CProtocolBridge::CreateNamedPipeConnection(DWORD error, DWORD bytesTransfered, LPOVERLAPPED overlapped)
{
HRESULT hr;
CNodeHttpStoredContext* ctx = CNodeHttpStoredContext::Get(overlapped);
HANDLE pipe = INVALID_HANDLE_VALUE;
DWORD retry = ctx->GetConnectionRetryCount();
if (0 == retry)
{
// only the first connection attempt uses connections from the pool
pipe = ctx->GetNodeProcess()->GetConnectionPool()->Take();
}
if (INVALID_HANDLE_VALUE == pipe)
{
ErrorIf(INVALID_HANDLE_VALUE == (pipe = CreateFile(
ctx->GetNodeProcess()->GetNamedPipeName(),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL)),
GetLastError());
ErrorIf(!SetFileCompletionNotificationModes(
pipe,
FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE),
GetLastError());
ctx->SetIsConnectionFromPool(FALSE);
ctx->GetNodeApplication()->GetApplicationManager()->GetAsyncManager()->AddAsyncCompletionHandle(pipe);
}
else
{
ctx->SetIsConnectionFromPool(TRUE);
}
ctx->SetPipe(pipe);
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode created named pipe connection to the node.exe process", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
CProtocolBridge::SendHttpRequestHeaders(ctx);
return;
Error:
if (INVALID_HANDLE_VALUE == pipe)
{
if (retry >= CModuleConfiguration::GetMaxNamedPipeConnectionRetry(ctx->GetHttpContext()))
{
if (hr == ERROR_PIPE_BUSY)
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode was unable to establish named pipe connection to the node.exe process because the named pipe server is too busy", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
CProtocolBridge::SendEmptyResponse(ctx, 503, CNodeConstants::IISNODE_ERROR_PIPE_CONNECTION_TOO_BUSY, _T("Service Unavailable"), hr);
}
else
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode was unable to establish named pipe connection to the node.exe process", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
CProtocolBridge::SendEmptyResponse( ctx,
500,
CNodeConstants::IISNODE_ERROR_PIPE_CONNECTION,
_T("Internal Server Error"),
hr );
}
}
else if (ctx->GetNodeProcess()->HasProcessExited())
{
// the process has exited, likely due to initialization error
// stop trying to establish the named pipe connection to minimize the failure latency
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode was unable to establish named pipe connection to the node.exe process before the process terminated", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
CProtocolBridge::SendEmptyResponse( ctx,
500,
CNodeConstants::IISNODE_ERROR_PIPE_CONNECTION_BEFORE_PROCESS_TERMINATED,
_T("Internal Server Error"),
hr );
}
else
{
ctx->SetConnectionRetryCount(retry + 1);
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode scheduled a retry of a named pipe connection to the node.exe process ", WINEVENT_LEVEL_INFO, ctx->GetActivityId());
CProtocolBridge::PostponeProcessing(ctx, CModuleConfiguration::GetNamedPipeConnectionRetryDelay(ctx->GetHttpContext()));
}
}
else
{
CloseHandle(pipe);
pipe = INVALID_HANDLE_VALUE;
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode was unable to configure the named pipe connection to the node.exe process", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
CProtocolBridge::SendEmptyResponse( ctx,
500,
CNodeConstants::IISNODE_ERROR_CONFIGURE_PIPE_CONNECTION,
_T("Internal Server Error"),
hr );
}
return;
}
void CProtocolBridge::SendHttpRequestHeaders(CNodeHttpStoredContext* context)
{
HRESULT hr;
DWORD length;
IHttpRequest *request;
PCSTR pszConnectionHeader = NULL;
// set the start time of the request
GetSystemTimeAsFileTime(context->GetStartTime());
// capture ETW provider since after a successful call to WriteFile the context may be asynchronously deleted
CNodeEventProvider* etw = context->GetNodeApplication()->GetApplicationManager()->GetEventProvider();
GUID activityId;
memcpy(&activityId, context->GetActivityId(), sizeof GUID);
// request the named pipe to be kept alive by the server after the response is sent
// to enable named pipe connection pooling
request = context->GetHttpContext()->GetRequest();
pszConnectionHeader = request->GetHeader(HttpHeaderConnection);
if( pszConnectionHeader == NULL ||
(pszConnectionHeader != NULL && stricmp(pszConnectionHeader, "upgrade") != 0))
{
CheckError(request->SetHeader(HttpHeaderConnection, "keep-alive", 10, TRUE));
}
// Expect: 100-continue has been processed by IIS - do not propagate it up to node.js since node will
// attempt to process it again
USHORT expectLength;
PCSTR expect = request->GetHeader(HttpHeaderExpect, &expectLength);
if (NULL != expect && 0 == strnicmp(expect, "100-continue", expectLength))
{
CheckError(request->DeleteHeader(HttpHeaderExpect));
}
// determine if the request body had been chunked; IIS decodes chunked encoding, so it
// must be re-applied when sending the request entity body
USHORT encodingLength;
PCSTR encoding = request->GetHeader(HttpHeaderTransferEncoding, &encodingLength);
if (NULL != encoding && 0 == strnicmp(encoding, "chunked;", encodingLength > 8 ? 8 : encodingLength))
{
context->SetIsChunked(TRUE);
context->SetIsLastChunk(FALSE);
}
// serialize and send request headers
CheckError(CHttpProtocol::SerializeRequestHeaders(context, context->GetBufferRef(), context->GetBufferSizeRef(), &length));
context->SetNextProcessor(CProtocolBridge::SendHttpRequestHeadersCompleted);
if (WriteFile(context->GetPipe(), context->GetBuffer(), length, NULL, context->InitializeOverlapped()))
{
// completed synchronously
etw->Log(context->GetHttpContext(), L"iisnode initiated sending http request headers to the node.exe process and completed synchronously",
WINEVENT_LEVEL_VERBOSE,
&activityId);
// despite IO completion ports are used, asynchronous callback will not be invoked because in
// CProtocolBridge:CreateNamedPipeConnection the SetFileCompletionNotificationModes function was called
// - see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365683(v=vs.85).aspx
// and http://msdn.microsoft.com/en-us/library/windows/desktop/aa365538(v=vs.85).aspx
CProtocolBridge::SendHttpRequestHeadersCompleted(S_OK, 0, context->GetOverlapped());
}
else
{
hr = GetLastError();
if (ERROR_IO_PENDING == hr)
{
}
else
{
// error
if (context->GetIsConnectionFromPool())
{
// communication over a connection from the connection pool failed
// try to create a brand new connection instead
context->SetConnectionRetryCount(1);
CProtocolBridge::CreateNamedPipeConnection(S_OK, 0, context->GetOverlapped());
}
else
{
etw->Log(context->GetHttpContext(), L"iisnode failed to initiate sending http request headers to the node.exe process",
WINEVENT_LEVEL_ERROR,
&activityId);
CProtocolBridge::SendEmptyResponse( context,
500,
CNodeConstants::IISNODE_ERROR_FAILED_INIT_SEND_HTTP_HEADERS,
_T("Internal Server Error"),
hr );
}
}
}
return;
Error:
etw->Log(context->GetHttpContext(), L"iisnode failed to serialize http request headers",
WINEVENT_LEVEL_ERROR,
&activityId);
CProtocolBridge::SendEmptyResponse( context,
500,
CNodeConstants::IISNODE_ERROR_FAILED_SERIALIZE_HTTP_HEADERS,
_T("Internal Server Error"),
hr );
return;
}
void WINAPI CProtocolBridge::SendHttpRequestHeadersCompleted(DWORD error, DWORD bytesTransfered, LPOVERLAPPED overlapped)
{
HRESULT hr;
CNodeHttpStoredContext* ctx = CNodeHttpStoredContext::Get(overlapped);
CheckError(error);
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode finished sending http request headers to the node.exe process", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
CProtocolBridge::ReadRequestBody(ctx);
return;
Error:
if (ctx->GetIsConnectionFromPool())
{
// communication over a connection from the connection pool failed
// try to create a brand new connection instead
ctx->SetConnectionRetryCount(1);
CProtocolBridge::CreateNamedPipeConnection(S_OK, 0, ctx->GetOverlapped());
}
else
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode failed to send http request headers to the node.exe process", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
CProtocolBridge::SendEmptyResponse( ctx,
500,
CNodeConstants::IISNODE_ERROR_FAILED_SEND_HTTP_HEADERS,
_T("Internal Server Error"),
hr );
}
return;
}
void CProtocolBridge::ReadRequestBody(CNodeHttpStoredContext* context)
{
HRESULT hr;
DWORD bytesReceived = 0;
BOOL completionPending = FALSE;
BOOL continueSynchronouslyNow = TRUE;
if (0 < context->GetHttpContext()->GetRequest()->GetRemainingEntityBytes() || context->GetIsUpgrade())
{
context->SetNextProcessor(CProtocolBridge::ReadRequestBodyCompleted);
if (context->GetIsChunked())
{
CheckError(context->GetHttpContext()->GetRequest()->ReadEntityBody(context->GetChunkBuffer(), context->GetChunkBufferSize(), TRUE, &bytesReceived, &completionPending));
}
else
{
CheckError(context->GetHttpContext()->GetRequest()->ReadEntityBody(context->GetBuffer(), context->GetBufferSize(), TRUE, &bytesReceived, &completionPending));
}
if (!completionPending)
{
context->SetContinueSynchronously(TRUE);
continueSynchronouslyNow = FALSE;
context->SetBytesCompleted(bytesReceived);
}
}
if (!completionPending)
{
context->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(context->GetHttpContext(),
L"iisnode initiated reading http request body chunk and completed synchronously", WINEVENT_LEVEL_VERBOSE, context->GetActivityId());
context->SetBytesCompleted(bytesReceived);
if (continueSynchronouslyNow)
{
CProtocolBridge::ReadRequestBodyCompleted(S_OK, 0, context->GetOverlapped());
}
}
else
{
//context->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(context->GetHttpContext(),
// L"iisnode initiated reading http request body chunk and will complete asynchronously", WINEVENT_LEVEL_VERBOSE, context->GetActivityId());
}
return;
Error:
if (HRESULT_FROM_WIN32(ERROR_HANDLE_EOF) == hr)
{
context->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(context->GetHttpContext(),
L"iisnode detected the end of the http request body", WINEVENT_LEVEL_VERBOSE, context->GetActivityId());
if (context->GetIsUpgrade())
{
CProtocolBridge::FinalizeUpgradeResponse(context, S_OK);
}
else if (context->GetIsChunked() && !context->GetIsLastChunk())
{
// send the terminating zero-length chunk
CProtocolBridge::ReadRequestBodyCompleted(S_OK, 0, context->GetOverlapped());
}
else
{
CProtocolBridge::StartReadResponse(context);
}
}
else
{
context->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(context->GetHttpContext(),
L"iisnode failed reading http request body", WINEVENT_LEVEL_ERROR, context->GetActivityId());
if (context->GetIsUpgrade())
{
CProtocolBridge::FinalizeUpgradeResponse(context, HRESULT_FROM_WIN32(hr));
}
else
{
CProtocolBridge::SendEmptyResponse( context,
500,
CNodeConstants::IISNODE_ERROR_FAILED_READ_REQ_BODY,
_T("Internal Server Error"),
HRESULT_FROM_WIN32(hr) );
}
}
return;
}
void WINAPI CProtocolBridge::ReadRequestBodyCompleted(DWORD error, DWORD bytesTransfered, LPOVERLAPPED overlapped)
{
CNodeHttpStoredContext* ctx = CNodeHttpStoredContext::Get(overlapped);
if (S_OK == error && bytesTransfered > 0)
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode read a chunk of http request body", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
CProtocolBridge::SendRequestBody(ctx, bytesTransfered);
}
else if (ERROR_HANDLE_EOF == error || 0 == bytesTransfered)
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode detected the end of the http request body", WINEVENT_LEVEL_VERBOSE, ctx->GetActivityId());
if (ctx->GetIsUpgrade())
{
CProtocolBridge::FinalizeUpgradeResponse(ctx, S_OK);
}
else if (ctx->GetIsChunked() && !ctx->GetIsLastChunk())
{
// send the zero-length last chunk to indicate the end of a chunked entity body
CProtocolBridge::SendRequestBody(ctx, 0);
}
else
{
CProtocolBridge::StartReadResponse(ctx);
}
}
else
{
ctx->GetNodeApplication()->GetApplicationManager()->GetEventProvider()->Log(ctx->GetHttpContext(),
L"iisnode failed reading http request body", WINEVENT_LEVEL_ERROR, ctx->GetActivityId());
if (ctx->GetIsUpgrade())
{
CProtocolBridge::FinalizeUpgradeResponse(ctx, error);
}
else
{
CProtocolBridge::SendEmptyResponse( ctx,
500,
CNodeConstants::IISNODE_ERROR_FAILED_READ_REQ_BODY_COMPLETED,
_T("Internal Server Error"),
error );
}
}
}
void CProtocolBridge::SendRequestBody(CNodeHttpStoredContext* context, DWORD chunkLength)
{
// capture ETW provider since after a successful call to WriteFile the context may be asynchronously deleted