-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpServer.jsmod
More file actions
889 lines (662 loc) · 24.9 KB
/
Copy pathhttpServer.jsmod
File metadata and controls
889 lines (662 loc) · 24.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
/* ***** BEGIN LICENSE BLOCK *****
* Version: GNU GPL 3.0
*
* The contents of this file are subject to the
* GNU General Public License Version 3.0; you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
* ***** END LICENSE BLOCK ***** */
(function webServerModule($D, $A, $S) {
LoadModule('jsz');
this.disabled = false;
var _name = this.name = this.constructor.name;
var $MD = $D[_name];
const mimeType = {
htm:'text/html',
html:'text/html',
xml:'text/xml',
png:'image/png',
gif:'image/gif',
jpeg:'image/jpeg',
jpg:'image/jpeg',
jpe:'image/jpeg',
svg:'image/svg+xml'
};
const httpReasonPhrase = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Time-out',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Large',
415: 'Unsupported Media Type',
416: 'Requested range not satisfiable',
417: 'Expectation Failed',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Time-out',
505: 'HTTP Version not supported'
};
// Tools
function MimeTypeByFileName(fileName) {
return mimeType[fileName.substr(fileName.lastIndexOf(DOT)+1)] || 'text/html; charset=iso-8859-1';
}
function NormalizeHeaderName(rawName) {
return [ h[0].toUpperCase()+h.substr(1) for each( h in rawName.split('-')) ].join('-');
}
function ParseHttpStatus(buffer) {
var status = NewDataObj();
status.method = buffer.ReadUntil(SPC);
status.url = buffer.ReadUntil(SPC);
status.protoName = buffer.ReadUntil(SLASH);
status.protoVersion = buffer.ReadUntil(CRLF);
var [path,query] = status.url.split('?');
status.path = path;
status.query = query;
return status;
}
function ParseHttpHeaders(buffer) {
var headers = new HttpHeaders();
for (;;) {
var key = buffer.ReadUntil(': ');
var value = buffer.ReadUntil(CRLF);
if ( !key )
break;
headers.Set(key, value);
}
return headers;
}
function HttpHeaders() {
var _headers = NewDataObj();
this.Parse = function(rawHeaders) {
var res, hre = /(.*?): ?(.*?)\r?\n/g;
for ( hre.lastIndex = 0; res = hre.exec(rawHeaders); _headers[res[1]] = res[2]);
}
this.Has = function(name) {
return name in _headers;
}
this.Set = function(name, value) {
_headers[name] = value;
}
this.MSet = function(obj) {
for ( var p in obj )
_headers[p] = obj[p];
}
this.Get = function(name) {
return name in _headers ? _headers[name] : undefined;
}
this.Is = function(name, value) {
return name in _headers && _headers[name].toLowerCase() == value.toLowerCase();
}
this.Contain = function(name, value) {
return name in _headers && _headers[name].toLowerCase().indexOf(value.toLowerCase()) != -1;
}
this.Remove = function(name) {
delete _headers[name];
}
this.Serialize = function() {
var tmp = '';
for ( var [h,v] in Iterator(_headers) )
tmp += h + ': ' + v + CRLF;
return tmp;
}
}
function CreateHttpHeaders( statusCode, protoVersion, headers ) {
var buf = 'HTTP/' + protoVersion + SPC + statusCode + SPC + httpReasonPhrase[statusCode] + CRLF;
return buf + headers.Serialize() + CRLF;
}
function NormalizePath( path ) { // (TBD) try with regexp
var epath = path.split('/');
var newPath = [];
for each ( var name in epath )
switch (name) {
case '..':
newPath.pop();
break;
case '.':
case '':
break;
default:
newPath.push(name);
}
return newPath.join('/');
}
function ProcessFileRequest(req) {
var root='./';
var data = '';
var fileName = root + NormalizePath(req.iStatus.path);
var file = new File( fileName );
if ( !file.exist || file.info.type != File.FILE_FILE ) {
var message = 'file '+fileName+' not found';
req.oHeaders.Set('Content-Length', message.length);
req.oHeaders.Set('Content-Type', 'text/plain');
req.Respond(404)(message);
return;
}
file.Open( File.RDONLY );
req.OnBodyData = function(req, buf) data += buf;
req.OnEndOfBody = function(req) {
req.oHeaders.Set('Content-Type', MimeTypeByFileName(fileName));
var TransferEncodingFilter = Identity;
if (req.iStatus.protoVersion >= 1.1) {
req.oHeaders.Set('Transfer-Encoding', 'chunked');
TransferEncodingFilter = function(data) [ data.length.toString(16) + CRLF, data, CRLF ];
}
var ContentEncodingFilter = Identity;
if ( req.iHeaders.Has('Accept-Encoding') && req.iHeaders.Contain('Accept-Encoding', 'deflate') ) {
req.oHeaders.Set('Content-Encoding', 'deflate');
ContentEncodingFilter = new Z(Z.DEFLATE,0);
}
req.Respond(200);
req.Send( function() {
var data = file.Read(4096); // Z.idealInputLength
data = ContentEncodingFilter(data);
if ( !data ) {
file.Close();
req.Send(TransferEncodingFilter(''));
req.End();
return undefined;
}
return TransferEncodingFilter(data);
}, true );
}
}
function IrcTextToWeb(text) {
var colors = { 0:'FFF', 1:'000', 2:'007', 3:'070', 4:'F00', 5:'700', 6:'909', 7:'F70',
8:'FF0', 9:'0F0', 10:'077', 11:'0FF', 12:'00F', 13:'F0F', 14:'777', 15:'DDD' };
var lines = text.split('\x03');
var end = '';
for ( var i=1; i<lines.length; i++ ) {
var [m,fg,bg] = /^(\d{1,2})(?:,(\d{1,2}))?/(lines[i]);
var html = '';
html += isNaN(fg)?'':('color:#'+colors[fg]+';');
html += isNaN(bg)?'':('background-color:#'+colors[bg]+';');
lines[i] = '<span style="'+html+'">'+lines[i].substr(m.length);;
end += '</span>';
}
return lines.join('')+end;
}
function TermIrc(term) {
var _currentChan;
term.Send(['cout','Welcome to the IRC term<br/> HELP:<br/> /j <channel> : join<br/> /q : quit<br/> /names : name list<br/>']);
term.OnRequest = function([name, data]) {
if ( name != 'cin' || !data )
return;
if ( data[0] == '/' ) {
var arg = ParseArguments(data.substr(1));
switch (arg[0].toLowerCase()) {
case 'q':
$A.RemoveModuleListener(listener);
TermLogin(term);
break;
case 'j':
_currentChan = $A.NormalizeChannelName((arg[1][0] == '#' ? '' : '#') + arg[1]);
$A.Join( _currentChan );
term.Send(['cout', '* Now talking in '+_currentChan+'<br/>']);
break;
case 'names':
var names = '';
for ( let name in $D.channel[_currentChan].names )
names += ($A.IsVoice(_currentChan, name)?'+':'') + ($A.IsOp(_currentChan, name)?'@':'') + name + ' ';
term.Send(['cout', names+'<br/>']);
break;
default:
term.Send(['cout', 'unknown command<br/>']);
}
} else {
_currentChan && $A.Privmsg( _currentChan, data );
term.Send(['cout', '<i>'+_currentChan+'</i> <'+getData($D.nick)+'> '+data+'<br/>']);
}
}
var listener = { ircMsg: {
PRIVMSG: function( tmp, command, from, to, msg ) {
to = $A.NormalizeChannelName(to);
if ( _currentChan && to == _currentChan )
term.Send(['cout', '<i>' + to + '</i> <' + StrBefore(from, '!') +'> ' + IrcTextToWeb(msg) + '<br/>']);
}
}};
$A.AddModuleListener(listener);
term.OnClose = function() $A.RemoveModuleListener(listener);
}
function TermLogin(term) {
term.Send(['cout', 'Login as: ']);
term.OnRequest = function([name, data]) {
if ( name != 'cin' )
return;
term.Send(['cout', data+'<br/>password: ']);
term.OnRequest = function([name, data]) {
if ( name != 'cin' )
return;
term.Send(['cout', StringRepeat('*', data.length)+'<br/><br/>']);
if ( data == getData($MD.consolePasword) ) {
TermIrc(term);
} else {
term.Send(['cout', '<span style="color:red">Invalid password, bye.</span><br/>']);
term.Close();
}
}
}
term.OnClose = Noop;
}
function TermSession() {
this.OnShow = function(persisted) {
var consoleWebModule = new File('./webConsole.js').content; // (TBD) filename from config
this.Send(['AddModule', consoleWebModule]);
this.Send(['config', 'termSessionTimeout', getData($MD.termSessionTimeout)]);
TermLogin(this);
}
}
////
/*
function TermSession() {
var _term = this;
var _history = [];
var i = 0, j = 0;
function Send(message) {
_history.push(message);
if ( _history.length > 100 )
_history.shift();
_term.Send && _term.Send(message);
}
_term.OnShow = function(persisted) {
var consoleWebModule = new File('./webConsole.js').content; // (TBD) filename from config
_term.Send(['AddModule', consoleWebModule]);
if (persisted) {
for each ( var message in _history )
_term.Send(message);
} else {
Send(['cout','Ready.<br/>']);
io.AddTimeout( 2000, function() {
Send(['cout', i+'(1/2)']);
Send(['cout', i+'(2/2)<br/>']);
io.AddTimeout( 500, arguments.callee );
i++;
});
}
}
_term.OnRequest = function([name, data]) {
if ( name != 'cin' )
return;
j++;
Send(['cout', 'echo '+j+':'+data+'<br/>']);
}
_term.OnClose = function() {}
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Terminal Manager
//
var _termCount = 0;
var _termList = NewDataObj();
function SendItemList(req, itemList) {
if ( !req.Respond )
return;
var data;
if ( itemList.length ) {
data = EncodeArray([ EncodeArray(item) for each (item in itemList) ]);
itemList.splice(0);
if ( data.length >= 512 && req.iHeaders.Has('Accept-Encoding') && req.iHeaders.Contain('Accept-Encoding', 'deflate') ) {
if ( !req.iHeaders.Contain('User-Agent', 'MSIE') ) {
req.oHeaders.Set('Content-Encoding', 'deflate');
data = new Z(Z.DEFLATE)(data, true); // send all at once
}
}
req.oHeaders.Set('Content-Type', 'application/x-www-form-urlencoded');
} else {
data = '';
}
req.oHeaders.Set('Content-Length', data.length);
req.Respond(200)(data);
req.End();
}
function ProcessTermAccess(req) {
var action = ParseHttpQueryString(req.iStatus.query||'').action;
var term = _termList[ParseHttpCookie(req.iHeaders.Get('Cookie')||'').sid];
if ( !action ) {
if ( !term ) {
if ( _termCount >= getData($MD.maxTerminal) ) {
req.oHeaders.Set('Connection', 'close');
req.Respond(503)('<h1>'+httpReasonPhrase[503]+'</h1><p>No more terminal available, please retry later</p>');
req.End();
return;
}
let sid = RandomString(32);
_termList[sid] = term = { pendingMessagesQueue:[], messageCount:0 };
_termCount++;
term.pub = new TermSession();
term.pub.Send = function(message) { // message is [arg1, arg2, ...]
term.pendingMessagesQueue.push(message);
term.Send && term.Send();
term.messageCount++;
}
term.pub.Close = function() { // a terminal close is not a HTTP connection close !!
delete term.pub.Close; // avoid Close() to be called in OnClose()
delete term.pub.OnRequest;
term.pub.OnClose && term.pub.OnClose();
delete term.pub.Send;
term.ResetTimeout();
delete _termList[sid];
_termCount--;
ReportNotice( _name+' @ProcessTermAccess - close by ' + req.peerName );
}
term.ResetTimeout = function(time) {
term.timeout && io.RemoveTimeout(term.timeout);
if (time)
term.timeout = io.AddTimeout( time, function() term.pub.Close() );
}
req.oHeaders.Set('Set-Cookie', 'sid='+sid+'; path='+req.iStatus.path); // Set-Cookie: <name>=<value>[; <name>=<value>]... [; expires=<date>][; domain=<domain_name>][; path=<some_path>][; secure][; httponly]
ReportNotice( _name+' @ProcessTermAccess - create by ' + req.peerName );
} else { // else if term
ReportNotice( _name+' @ProcessTermAccess - restored by ' + req.peerName );
}
term.pendingMessagesQueue.splice(0); // it is up to an 'histoy system' to restore previous things.
var content = new File('./webTerm.html').content; // (TBD) filename from config
req.oHeaders.Set('cache-control', 'no-store'); // cf. http://developer.mozilla.org/en/docs/Using_Firefox_1.5_caching
req.oHeaders.Set('Content-Length', content.length);
req.Respond(200)(content);
req.End();
term.pub.OnShow && term.pub.OnShow(term.messageCount > 0); // false on the initial load.
term.ResetTimeout(getData($MD.termSessionTimeout));
return;
}
if ( !term ) { // a 'sid' is given but no matching session is found.
let message = '<h1>Invalid session</h1><p>The required terminal session is closed</p>';
req.oHeaders.Set('Content-Length', message.length);
req.Respond(404)(message);
req.End();
return;
}
term.ResetTimeout(getData($MD.termSessionTimeout));
req._termData = '';
req.OnBodyData = function(req, buf) req._termData += buf;
req.OnEndOfBody = function(req) {
if ( req.iStatus.method == 'POST' ) {
DBG && DebugTrace( _name+' @ProcessTermAccess: processing term data from req #'+ObjectToId(req) );
let sendFct = term.Send; // we prefer sending the whole response at once to avoid out-of-order responses !
delete term.Send; // messages sent while OnRequest is called will be sent in pendingMessagesQueue.
for each ( let item in DecodeArray(req._termData) )
term.pub.OnRequest && term.pub.OnRequest.call(term.pub, DecodeArray(item));
delete req._termData;
term.Send = sendFct;
}
if ( term.pendingMessagesQueue.length ) {
DBG && DebugTrace( _name+' @ProcessTermAccess: sending pending term data using req #'+ObjectToId(req) );
SendItemList(req, term.pendingMessagesQueue); // misnamed: TryToSendItemList
return;
}
if ( term.Send ) {
DBG && DebugTrace( _name+' @ProcessTermAccess: replacing pending request' );
term.Send(); // end the current pending request (BUT the connection may be keep-alive)
delete term.Send;
}
DBG && DebugTrace( _name+' @ProcessTermAccess: setting pending request' );
term.Send = function() {
DBG && DebugTrace( _name+' @ProcessTermAccess: sending data using req #'+ObjectToId(req) );
SendItemList(req, term.pendingMessagesQueue); // misnamed: TryToSendItemList
delete term.Send; // if sucessful or not, this Send is no more usable.
}
// stop timeout
}
}
function CloseAllTerms() {
for each ( var c in _termList )
c.pub.Close && c.pub.Close();
}
INSPECT.push(function() 'TERMINAL '+ObjPropertyCount(_termList));
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// HTTP Server
//
var _serverConnection;
var _requestHandlerList = {};
var _httpConnectionsIndex = 0;
var _httpConnectionList = {};
var _totalConnectionCount = 0;
var _connectionCountByHost = new MultiCounter(getData($MD.maxConnectionsPerPeer));
var _incomingConnectionRatePerPeer = new MultiRateMeter(getData($MD.incomingConnectionRatePerPeer));
function FindRequestHandler(path) {
for each ( var [match, requestHandler] in _requestHandlerList )
if ( match(path) )
return requestHandler;
return undefined;
}
function Respond(statusCode, protoVersion) {
delete this.Respond; // we can respond only once
protoVersion = protoVersion || this.iStatus.protoVersion;
var connectionKeepAliveMax = getData($MD.connectionKeepAliveMax);
if ( this.iStatus.protoVersion >= 1.1
&& this.iHeaders.Is('Connection', 'keep-alive')
&& !this.oHeaders.Is('Connection', 'close')
&& this.count <= connectionKeepAliveMax
&& (this.oHeaders.Has('Content-Length') || this.oHeaders.Is('Transfer-Encoding', 'chunked')) ) {
this.oHeaders.Set('Connection', 'keep-klive' );
this.oHeaders.Set('Keep-Alive', 'timeout='+(getData($MD.connectionKeepAliveTimeout)/SECOND).toFixed()+', max='+(connectionKeepAliveMax-this.count) );
} else {
if ( this.oHeaders.Is('Transfer-Encoding', 'chunked') )
this.oHeaders.Remove('Transfer-Encoding'); // not HTTP/1.1
this.oHeaders.Set('Connection', 'close');
}
this.Send( CreateHttpHeaders( statusCode, protoVersion, this.oHeaders ) );
return this.Send;
}
function ProcessHttpConnection(connection) { // Entry point of a new incoming HTTP connection
DBG && DebugTrace( _name+' @ProcessHttpConnection: #'+ObjectToId(connection) );
_incomingConnectionRatePerPeer.Inc(connection.peerName, 1);
_connectionCountByHost.Add(connection.peerName, 1);
var currentConnectionIndex = _httpConnectionsIndex++;
_httpConnectionList[currentConnectionIndex] = connection;
_totalConnectionCount++;
var input = new Buffer();
var connectionDataRate = new SingleRateMeter(getData($MD.connectionDataRate));
var incomingRequestRate = new SingleRateMeter(getData($MD.maxRequestRate));
var count = 0, timeout;
var req = {}, OnData = ProcessHttpHeader;
function ResetTimeout(time) {
io.RemoveTimeout(timeout);
if ( time )
timeout = io.AddTimeout(time, Disconnect);
}
ResetTimeout(1*SECOND); // after accepting the connection, let 1 second to the client to send headers, else bye.
connection.OnData = function() {
var data = connection.Read();
input.Write(data);
OnData();
if ( !connectionDataRate.Inc(data.length) )
connection.Sleep( connectionDataRate.RestTime() );
}
function CloseConnection() {
DBG && DebugTrace( _name+' @CloseConnection: #'+ObjectToId(connection) );
ResetTimeout();
delete _httpConnectionList[currentConnectionIndex];
_totalConnectionCount--;
_connectionCountByHost.Add(connection.peerName, -1);
delete req.Respond;
delete req.Send;
delete req.End;
connection.Close(); // hard close / close the socket handler
}
connection.OnDisconnected = CloseConnection;
function Send(item) connection.Write(item, true);
function ProcessHttpHeader() {
OnData = arguments.callee;
if ( input.length > 8*KILOBYTE ) { // invalid headers size
ReportWarning( _name + ' @ProcessHttpHeader - incoming HTTP request header too long ('+input.length+') from '+_socket.peerName+':'+_socket.peerPort )
CloseConnection(); // connection.Disconnect(); is too gentle for this case
return;
}
if ( input.IndexOf(CRLF+CRLF) == -1 )
return;
ResetTimeout(getData($MD.connectionKeepAliveTimeout));
delete req.Respond; // the previous request is dead, references on it are legal but useless
delete req.Send;
delete req.End;
req = {};
req.count = ++count;
req.peerName = connection.peerName;
req.iStatus = ParseHttpStatus(input);
req.iHeaders = ParseHttpHeaders(input);
req.oHeaders = new HttpHeaders();
req.oHeaders.MSet({
'Date':new Date().toUTCString(),
'Server':_name,
'Expires':'0',
'Cache-Control':'no-cache',
// 'Cache-Control':'no-store, no-cache, must-revalidate',
// 'Pragma':'no-cache',
'Content-Type':'text/html'
}); // beware: do not set 'Connection' or 'Content-Length'
req.remainingBodyLength = req.iHeaders.Get('Content-Length');
ReportNotice( _name + ' @ProcessHttpHeader - incoming HTTP request: ' + req.iStatus.method + ' ' + req.iStatus.url ); // req.iHeaders.Serialize()
req.Respond = Respond;
req.Send = Send;
req.End = function() {
delete req.End;
if ( req.oHeaders.Is('Connection', 'close') )
Disconnect();
}
var requestHandler = FindRequestHandler(req.iStatus.path);
if ( !requestHandler ) {
var message = 'Unable to handle ' + req.iStatus.path;
req.oHeaders.MSet({'Content-Length':message.length, 'Content-Type':'text/plain'});
req.Respond(404)(message);
req.End();
return;
}
requestHandler(req);
if ( req.remainingBodyLength > 0 ) // (string > number) is valid
ProcessHttpBody();
else
ProcessEndOfRequest();
}
function ProcessHttpBody() {
OnData = arguments.callee;
if ( !input.length )
return;
if ( input.length >= req.remainingBodyLength ) {
req.OnBodyData && req.OnBodyData(req, input.Read(req.remainingBodyLength));
req.remainingBodyLength = 0;
} else {
req.remainingBodyLength -= input.length;
req.OnBodyData && req.OnBodyData(req, input.Read());
}
if ( req.remainingBodyLength == 0 )
ProcessEndOfRequest();
}
function ProcessEndOfRequest() {
OnData = Noop;
ResetTimeout(); // no timeout for the response. It's up to us to not block the request too long !
if ( !incomingRequestRate.Inc(1) )
connection.Sleep( incomingRequestRate.RestTime() );
if ( !req.End ) {
ProcessHttpHeader();
return;
}
req.End = function() {
delete req.End;
if ( req.oHeaders.Is('Connection', 'close') )
Disconnect();
else
ProcessHttpHeader();
}
req.OnEndOfBody && req.OnEndOfBody(req);
}
function Disconnect() {
DBG && DebugTrace( _name+' @Disconnect: #'+ObjectToId(connection) );
req.Send( function() void connection.Disconnect() );
delete req.Respond;
delete req.Send;
delete req.End;
OnData = Noop;
}
}
function StartServer() {
_serverConnection = new TCPServer( getData($MD.port), getData($MD.bind), getData($MD.socketBackLog) );
_serverConnection.OnIncoming = function(connection) {
if ( _totalConnectionCount > getData($MD.maxConnections) ) {
ReportWarning( _name+' incomming connection from '+connection.peerName+' refused: too many connections' );
connection.Close(); // hard close.
_serverConnection.Sleep(500); // ignore incomming connections for a while
return;
}
if ( !_incomingConnectionRatePerPeer.Check(connection.peerName) ) {
ReportWarning( _name+' incomming connection from '+connection.peerName+' refused: connection rate too high' );
if ( _incomingConnectionRatePerPeer.Ratio(connection.peerName) < 2 ) { // try to detect spam
connection.Write('HTTP/1.1 503 Service Unavailable'+CRLF+'Retry-After: 2'+CRLF+'Connection: close'+CRLF+CRLF, true);
connection.Write(function() connection.Disconnect(), true);
} else {
connection.Close(); // hard close.
}
return;
}
if ( !_connectionCountByHost.Check(connection.peerName) ) {
ReportWarning( _name+' incomming connection from '+connection.peerName+' refused: too many connections from this host' );
connection.Close(); // hard close.
return;
}
ProcessHttpConnection(connection);
}
}
function StopServer() {
_serverConnection.Close();
for each ( var connection in _httpConnectionList ) {
connection.Close();
}
Clear(_httpConnectionList);
}
INSPECT.push(function() 'HTTP CONNECTION '+ObjPropertyCount(_httpConnectionList));
this.moduleApi = {
AddRequestHandler: function( pathRegExpr, requestHandlerConstructor ) _requestHandlerList[String(pathRegExpr)] = [pathRegExpr, requestHandlerConstructor],
RemoveRequestListener: function( pathRegExpr ) delete _requestHandlerList[String(pathRegExpr)]
};
this.stateListener = [
{
set: function(s) s[STATE_RUNNING] && s[_name],
reset: function(s) !s[STATE_RUNNING] || !s[_name],
trigger: function(polarity) {
if (polarity) {
$A.AddRequestHandler( /^\/doc\//, ProcessFileRequest );
$A.AddRequestHandler( /^\/cons/, ProcessTermAccess );
StartServer();
} else {
StopServer();
CloseAllTerms();
}
}
}
];
})