This repository was archived by the owner on Aug 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttpd.js.upstream
More file actions
5179 lines (4489 loc) · 147 KB
/
httpd.js.upstream
File metadata and controls
5179 lines (4489 loc) · 147 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
/* -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* 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.
*
* The Original Code is the httpd.js server.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher (v1, netwerk/test/TestServ.js)
* Christian Biesinger (v2, netwerk/test/unit/head_http_server.js)
* Jeff Walden <jwalden+code@mit.edu> (v3, netwerk/test/httpserver/httpd.js)
* Robert Sayre <sayrer@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* An implementation of an HTTP server both as a loadable script and as an XPCOM
* component. See the accompanying README file for user documentation on
* httpd.js.
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const CC = Components.Constructor;
const PR_UINT32_MAX = Math.pow(2, 32) - 1;
/** True if debugging output is enabled, false otherwise. */
var DEBUG = false; // non-const *only* so tweakable in server tests
/** True if debugging output should be timestamped. */
var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests
var gGlobalObject = this;
/**
* Asserts that the given condition holds. If it doesn't, the given message is
* dumped, a stack trace is printed, and an exception is thrown to attempt to
* stop execution (which unfortunately must rely upon the exception not being
* accidentally swallowed by the code that uses it).
*/
function NS_ASSERT(cond, msg)
{
if (DEBUG && !cond)
{
dumpn("###!!!");
dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!"));
dumpn("###!!! Stack follows:");
var stack = new Error().stack.split(/\n/);
dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n"));
throw Cr.NS_ERROR_ABORT;
}
}
/** Constructs an HTTP error object. */
function HttpError(code, description)
{
this.code = code;
this.description = description;
}
HttpError.prototype =
{
toString: function()
{
return this.code + " " + this.description;
}
};
/**
* Errors thrown to trigger specific HTTP server responses.
*/
const HTTP_400 = new HttpError(400, "Bad Request");
const HTTP_401 = new HttpError(401, "Unauthorized");
const HTTP_402 = new HttpError(402, "Payment Required");
const HTTP_403 = new HttpError(403, "Forbidden");
const HTTP_404 = new HttpError(404, "Not Found");
const HTTP_405 = new HttpError(405, "Method Not Allowed");
const HTTP_406 = new HttpError(406, "Not Acceptable");
const HTTP_407 = new HttpError(407, "Proxy Authentication Required");
const HTTP_408 = new HttpError(408, "Request Timeout");
const HTTP_409 = new HttpError(409, "Conflict");
const HTTP_410 = new HttpError(410, "Gone");
const HTTP_411 = new HttpError(411, "Length Required");
const HTTP_412 = new HttpError(412, "Precondition Failed");
const HTTP_413 = new HttpError(413, "Request Entity Too Large");
const HTTP_414 = new HttpError(414, "Request-URI Too Long");
const HTTP_415 = new HttpError(415, "Unsupported Media Type");
const HTTP_417 = new HttpError(417, "Expectation Failed");
const HTTP_500 = new HttpError(500, "Internal Server Error");
const HTTP_501 = new HttpError(501, "Not Implemented");
const HTTP_502 = new HttpError(502, "Bad Gateway");
const HTTP_503 = new HttpError(503, "Service Unavailable");
const HTTP_504 = new HttpError(504, "Gateway Timeout");
const HTTP_505 = new HttpError(505, "HTTP Version Not Supported");
/** Creates a hash with fields corresponding to the values in arr. */
function array2obj(arr)
{
var obj = {};
for (var i = 0; i < arr.length; i++)
obj[arr[i]] = arr[i];
return obj;
}
/** Returns an array of the integers x through y, inclusive. */
function range(x, y)
{
var arr = [];
for (var i = x; i <= y; i++)
arr.push(i);
return arr;
}
/** An object (hash) whose fields are the numbers of all HTTP error codes. */
const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505)));
/**
* The character used to distinguish hidden files from non-hidden files, a la
* the leading dot in Apache. Since that mechanism also hides files from
* easy display in LXR, ls output, etc. however, we choose instead to use a
* suffix character. If a requested file ends with it, we append another
* when getting the file on the server. If it doesn't, we just look up that
* file. Therefore, any file whose name ends with exactly one of the character
* is "hidden" and available for use by the server.
*/
const HIDDEN_CHAR = "^";
/**
* The file name suffix indicating the file containing overridden headers for
* a requested file.
*/
const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR;
/** Type used to denote SJS scripts for CGI-like functionality. */
const SJS_TYPE = "sjs";
/** Base for relative timestamps produced by dumpn(). */
var firstStamp = 0;
/** dump(str) with a trailing "\n" -- only outputs if DEBUG. */
function dumpn(str)
{
if (DEBUG)
{
var prefix = "HTTPD-INFO | ";
if (DEBUG_TIMESTAMP)
{
if (firstStamp === 0)
firstStamp = Date.now();
var elapsed = Date.now() - firstStamp; // milliseconds
var min = Math.floor(elapsed / 60000);
var sec = (elapsed % 60000) / 1000;
if (sec < 10)
prefix += min + ":0" + sec.toFixed(3) + " | ";
else
prefix += min + ":" + sec.toFixed(3) + " | ";
}
dump(prefix + str + "\n");
}
}
/** Dumps the current JS stack if DEBUG. */
function dumpStack()
{
// peel off the frames for dumpStack() and Error()
var stack = new Error().stack.split(/\n/).slice(2);
stack.forEach(dumpn);
}
/** The XPCOM thread manager. */
var gThreadManager = null;
/** The XPCOM prefs service. */
var gRootPrefBranch = null;
function getRootPrefBranch()
{
if (!gRootPrefBranch)
{
gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
}
return gRootPrefBranch;
}
/**
* JavaScript constructors for commonly-used classes; precreating these is a
* speedup over doing the same from base principles. See the docs at
* http://developer.mozilla.org/en/docs/Components.Constructor for details.
*/
const ServerSocket = CC("@mozilla.org/network/server-socket;1",
"nsIServerSocket",
"init");
const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1",
"nsIScriptableInputStream",
"init");
const Pipe = CC("@mozilla.org/pipe;1",
"nsIPipe",
"init");
const FileInputStream = CC("@mozilla.org/network/file-input-stream;1",
"nsIFileInputStream",
"init");
const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1",
"nsIConverterInputStream",
"init");
const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1",
"nsIWritablePropertyBag2");
const SupportsString = CC("@mozilla.org/supports-string;1",
"nsISupportsString");
/* These two are non-const only so a test can overwrite them. */
var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1",
"nsIBinaryOutputStream",
"setOutputStream");
/**
* Returns the RFC 822/1123 representation of a date.
*
* @param date : Number
* the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT
* @returns string
* the representation of the given date
*/
function toDateString(date)
{
//
// rfc1123-date = wkday "," SP date1 SP time SP "GMT"
// date1 = 2DIGIT SP month SP 4DIGIT
// ; day month year (e.g., 02 Jun 1982)
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
// ; 00:00:00 - 23:59:59
// wkday = "Mon" | "Tue" | "Wed"
// | "Thu" | "Fri" | "Sat" | "Sun"
// month = "Jan" | "Feb" | "Mar" | "Apr"
// | "May" | "Jun" | "Jul" | "Aug"
// | "Sep" | "Oct" | "Nov" | "Dec"
//
const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/**
* Processes a date and returns the encoded UTC time as a string according to
* the format specified in RFC 2616.
*
* @param date : Date
* the date to process
* @returns string
* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
*/
function toTime(date)
{
var hrs = date.getUTCHours();
var rv = (hrs < 10) ? "0" + hrs : hrs;
var mins = date.getUTCMinutes();
rv += ":";
rv += (mins < 10) ? "0" + mins : mins;
var secs = date.getUTCSeconds();
rv += ":";
rv += (secs < 10) ? "0" + secs : secs;
return rv;
}
/**
* Processes a date and returns the encoded UTC date as a string according to
* the date1 format specified in RFC 2616.
*
* @param date : Date
* the date to process
* @returns string
* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
*/
function toDate1(date)
{
var day = date.getUTCDate();
var month = date.getUTCMonth();
var year = date.getUTCFullYear();
var rv = (day < 10) ? "0" + day : day;
rv += " " + monthStrings[month];
rv += " " + year;
return rv;
}
date = new Date(date);
const fmtString = "%wkday%, %date1% %time% GMT";
var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]);
rv = rv.replace("%time%", toTime(date));
return rv.replace("%date1%", toDate1(date));
}
/**
* Prints out a human-readable representation of the object o and its fields,
* omitting those whose names begin with "_" if showMembers != true (to ignore
* "private" properties exposed via getters/setters).
*/
function printObj(o, showMembers)
{
var s = "******************************\n";
s += "o = {\n";
for (var i in o)
{
if (typeof(i) != "string" ||
(showMembers || (i.length > 0 && i[0] != "_")))
s+= " " + i + ": " + o[i] + ",\n";
}
s += " };\n";
s += "******************************";
dumpn(s);
}
/**
* Instantiates a new HTTP server.
*/
function nsHttpServer()
{
if (!gThreadManager)
gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService();
/** The port on which this server listens. */
this._port = undefined;
/** The socket associated with this. */
this._socket = null;
/** The handler used to process requests to this server. */
this._handler = new ServerHandler(this);
/** Naming information for this server. */
this._identity = new ServerIdentity();
/**
* Indicates when the server is to be shut down at the end of the request.
*/
this._doQuit = false;
/**
* True if the socket in this is closed (and closure notifications have been
* sent and processed if the socket was ever opened), false otherwise.
*/
this._socketClosed = true;
/**
* Used for tracking existing connections and ensuring that all connections
* are properly cleaned up before server shutdown; increases by 1 for every
* new incoming connection.
*/
this._connectionGen = 0;
/**
* Hash of all open connections, indexed by connection number at time of
* creation.
*/
this._connections = {};
}
nsHttpServer.prototype =
{
classID: Components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"),
// NSISERVERSOCKETLISTENER
/**
* Processes an incoming request coming in on the given socket and contained
* in the given transport.
*
* @param socket : nsIServerSocket
* the socket through which the request was served
* @param trans : nsISocketTransport
* the transport for the request/response
* @see nsIServerSocketListener.onSocketAccepted
*/
onSocketAccepted: function(socket, trans)
{
dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")");
dumpn(">>> new connection on " + trans.host + ":" + trans.port);
const SEGMENT_SIZE = 8192;
const SEGMENT_COUNT = 1024;
try
{
var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT)
.QueryInterface(Ci.nsIAsyncInputStream);
var output = trans.openOutputStream(0, 0, 0);
}
catch (e)
{
dumpn("*** error opening transport streams: " + e);
trans.close(Cr.NS_BINDING_ABORTED);
return;
}
var connectionNumber = ++this._connectionGen;
try
{
var conn = new Connection(input, output, this, socket.port, trans.port,
connectionNumber);
var reader = new RequestReader(conn);
// XXX add request timeout functionality here!
// Note: must use main thread here, or we might get a GC that will cause
// threadsafety assertions. We really need to fix XPConnect so that
// you can actually do things in multi-threaded JS. :-(
input.asyncWait(reader, 0, 0, gThreadManager.mainThread);
}
catch (e)
{
// Assume this connection can't be salvaged and bail on it completely;
// don't attempt to close it so that we can assert that any connection
// being closed is in this._connections.
dumpn("*** error in initial request-processing stages: " + e);
trans.close(Cr.NS_BINDING_ABORTED);
return;
}
this._connections[connectionNumber] = conn;
dumpn("*** starting connection " + connectionNumber);
},
/**
* Called when the socket associated with this is closed.
*
* @param socket : nsIServerSocket
* the socket being closed
* @param status : nsresult
* the reason the socket stopped listening (NS_BINDING_ABORTED if the server
* was stopped using nsIHttpServer.stop)
* @see nsIServerSocketListener.onStopListening
*/
onStopListening: function(socket, status)
{
dumpn(">>> shutting down server on port " + socket.port);
this._socketClosed = true;
if (!this._hasOpenConnections())
{
dumpn("*** no open connections, notifying async from onStopListening");
// Notify asynchronously so that any pending teardown in stop() has a
// chance to run first.
var self = this;
var stopEvent =
{
run: function()
{
dumpn("*** _notifyStopped async callback");
self._notifyStopped();
}
};
gThreadManager.currentThread
.dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL);
}
},
// NSIHTTPSERVER
//
// see nsIHttpServer.start
//
start: function(port)
{
this._start(port, "localhost")
},
_start: function(port, host)
{
if (this._socket)
throw Cr.NS_ERROR_ALREADY_INITIALIZED;
this._port = port;
this._doQuit = this._socketClosed = false;
this._host = host;
// The listen queue needs to be long enough to handle
// network.http.max-connections-per-server concurrent connections,
// plus a safety margin in case some other process is talking to
// the server as well.
var prefs = getRootPrefBranch();
var maxConnections =
prefs.getIntPref("network.http.max-connections-per-server") + 5;
try
{
var loopback = true;
if (this._host != "127.0.0.1" && this._host != "localhost") {
var loopback = false;
}
var socket = new ServerSocket(this._port,
loopback, // true = localhost, false = everybody
maxConnections);
dumpn(">>> listening on port " + socket.port + ", " + maxConnections +
" pending connections");
socket.asyncListen(this);
this._identity._initialize(port, host, true);
this._socket = socket;
}
catch (e)
{
dumpn("!!! could not start server on port " + port + ": " + e);
throw Cr.NS_ERROR_NOT_AVAILABLE;
}
},
//
// see nsIHttpServer.stop
//
stop: function(callback)
{
if (!callback)
throw Cr.NS_ERROR_NULL_POINTER;
if (!this._socket)
throw Cr.NS_ERROR_UNEXPECTED;
this._stopCallback = typeof callback === "function"
? callback
: function() { callback.onStopped(); };
dumpn(">>> stopping listening on port " + this._socket.port);
this._socket.close();
this._socket = null;
// We can't have this identity any more, and the port on which we're running
// this server now could be meaningless the next time around.
this._identity._teardown();
this._doQuit = false;
// socket-close notification and pending request completion happen async
},
//
// see nsIHttpServer.registerFile
//
registerFile: function(path, file)
{
if (file && (!file.exists() || file.isDirectory()))
throw Cr.NS_ERROR_INVALID_ARG;
this._handler.registerFile(path, file);
},
//
// see nsIHttpServer.registerDirectory
//
registerDirectory: function(path, directory)
{
// XXX true path validation!
if (path.charAt(0) != "/" ||
path.charAt(path.length - 1) != "/" ||
(directory &&
(!directory.exists() || !directory.isDirectory())))
throw Cr.NS_ERROR_INVALID_ARG;
// XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping
// exists!
this._handler.registerDirectory(path, directory);
},
//
// see nsIHttpServer.registerPathHandler
//
registerPathHandler: function(path, handler)
{
this._handler.registerPathHandler(path, handler);
},
//
// see nsIHttpServer.registerErrorHandler
//
registerErrorHandler: function(code, handler)
{
this._handler.registerErrorHandler(code, handler);
},
//
// see nsIHttpServer.setIndexHandler
//
setIndexHandler: function(handler)
{
this._handler.setIndexHandler(handler);
},
//
// see nsIHttpServer.registerContentType
//
registerContentType: function(ext, type)
{
this._handler.registerContentType(ext, type);
},
//
// see nsIHttpServer.serverIdentity
//
get identity()
{
return this._identity;
},
//
// see nsIHttpServer.getState
//
getState: function(path, k)
{
return this._handler._getState(path, k);
},
//
// see nsIHttpServer.setState
//
setState: function(path, k, v)
{
return this._handler._setState(path, k, v);
},
//
// see nsIHttpServer.getSharedState
//
getSharedState: function(k)
{
return this._handler._getSharedState(k);
},
//
// see nsIHttpServer.setSharedState
//
setSharedState: function(k, v)
{
return this._handler._setSharedState(k, v);
},
//
// see nsIHttpServer.getObjectState
//
getObjectState: function(k)
{
return this._handler._getObjectState(k);
},
//
// see nsIHttpServer.setObjectState
//
setObjectState: function(k, v)
{
return this._handler._setObjectState(k, v);
},
// NSISUPPORTS
//
// see nsISupports.QueryInterface
//
QueryInterface: function(iid)
{
if (iid.equals(Ci.nsIHttpServer) ||
iid.equals(Ci.nsIServerSocketListener) ||
iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
// NON-XPCOM PUBLIC API
/**
* Returns true iff this server is not running (and is not in the process of
* serving any requests still to be processed when the server was last
* stopped after being run).
*/
isStopped: function()
{
return this._socketClosed && !this._hasOpenConnections();
},
// PRIVATE IMPLEMENTATION
/** True if this server has any open connections to it, false otherwise. */
_hasOpenConnections: function()
{
//
// If we have any open connections, they're tracked as numeric properties on
// |this._connections|. The non-standard __count__ property could be used
// to check whether there are any properties, but standard-wise, even
// looking forward to ES5, there's no less ugly yet still O(1) way to do
// this.
//
for (var n in this._connections)
return true;
return false;
},
/** Calls the server-stopped callback provided when stop() was called. */
_notifyStopped: function()
{
NS_ASSERT(this._stopCallback !== null, "double-notifying?");
NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now");
//
// NB: We have to grab this now, null out the member, *then* call the
// callback here, or otherwise the callback could (indirectly) futz with
// this._stopCallback by starting and immediately stopping this, at
// which point we'd be nulling out a field we no longer have a right to
// modify.
//
var callback = this._stopCallback;
this._stopCallback = null;
try
{
callback();
}
catch (e)
{
// not throwing because this is specified as being usually (but not
// always) asynchronous
dump("!!! error running onStopped callback: " + e + "\n");
}
},
/**
* Notifies this server that the given connection has been closed.
*
* @param connection : Connection
* the connection that was closed
*/
_connectionClosed: function(connection)
{
NS_ASSERT(connection.number in this._connections,
"closing a connection " + this + " that we never added to the " +
"set of open connections?");
NS_ASSERT(this._connections[connection.number] === connection,
"connection number mismatch? " +
this._connections[connection.number]);
delete this._connections[connection.number];
// Fire a pending server-stopped notification if it's our responsibility.
if (!this._hasOpenConnections() && this._socketClosed)
this._notifyStopped();
},
/**
* Requests that the server be shut down when possible.
*/
_requestQuit: function()
{
dumpn(">>> requesting a quit");
dumpStack();
this._doQuit = true;
}
};
//
// RFC 2396 section 3.2.2:
//
// host = hostname | IPv4address
// hostname = *( domainlabel "." ) toplabel [ "." ]
// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
// toplabel = alpha | alpha *( alphanum | "-" ) alphanum
// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit
//
const HOST_REGEX =
new RegExp("^(?:" +
// *( domainlabel "." )
"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" +
// toplabel
"[a-z](?:[a-z0-9-]*[a-z0-9])?" +
"|" +
// IPv4 address
"\\d+\\.\\d+\\.\\d+\\.\\d+" +
")$",
"i");
/**
* Represents the identity of a server. An identity consists of a set of
* (scheme, host, port) tuples denoted as locations (allowing a single server to
* serve multiple sites or to be used behind both HTTP and HTTPS proxies for any
* host/port). Any incoming request must be to one of these locations, or it
* will be rejected with an HTTP 400 error. One location, denoted as the
* primary location, is the location assigned in contexts where a location
* cannot otherwise be endogenously derived, such as for HTTP/1.0 requests.
*
* A single identity may contain at most one location per unique host/port pair;
* other than that, no restrictions are placed upon what locations may
* constitute an identity.
*/
function ServerIdentity()
{
/** The scheme of the primary location. */
this._primaryScheme = "http";
/** The hostname of the primary location. */
this._primaryHost = "127.0.0.1"
/** The port number of the primary location. */
this._primaryPort = -1;
/**
* The current port number for the corresponding server, stored so that a new
* primary location can always be set if the current one is removed.
*/
this._defaultPort = -1;
/**
* Maps hosts to maps of ports to schemes, e.g. the following would represent
* https://example.com:789/ and http://example.org/:
*
* {
* "xexample.com": { 789: "https" },
* "xexample.org": { 80: "http" }
* }
*
* Note the "x" prefix on hostnames, which prevents collisions with special
* JS names like "prototype".
*/
this._locations = { "xlocalhost": {} };
}
ServerIdentity.prototype =
{
// NSIHTTPSERVERIDENTITY
//
// see nsIHttpServerIdentity.primaryScheme
//
get primaryScheme()
{
if (this._primaryPort === -1)
throw Cr.NS_ERROR_NOT_INITIALIZED;
return this._primaryScheme;
},
//
// see nsIHttpServerIdentity.primaryHost
//
get primaryHost()
{
if (this._primaryPort === -1)
throw Cr.NS_ERROR_NOT_INITIALIZED;
return this._primaryHost;
},
//
// see nsIHttpServerIdentity.primaryPort
//
get primaryPort()
{
if (this._primaryPort === -1)
throw Cr.NS_ERROR_NOT_INITIALIZED;
return this._primaryPort;
},
//
// see nsIHttpServerIdentity.add
//
add: function(scheme, host, port)
{
this._validate(scheme, host, port);
var entry = this._locations["x" + host];
if (!entry)
this._locations["x" + host] = entry = {};
entry[port] = scheme;
},
//
// see nsIHttpServerIdentity.remove
//
remove: function(scheme, host, port)
{
this._validate(scheme, host, port);
var entry = this._locations["x" + host];
if (!entry)
return false;
var present = port in entry;
delete entry[port];
if (this._primaryScheme == scheme &&
this._primaryHost == host &&
this._primaryPort == port &&
this._defaultPort !== -1)
{
// Always keep at least one identity in existence at any time, unless
// we're in the process of shutting down (the last condition above).
this._primaryPort = -1;
this._initialize(this._defaultPort, host, false);
}
return present;
},
//
// see nsIHttpServerIdentity.has
//
has: function(scheme, host, port)
{
this._validate(scheme, host, port);
return "x" + host in this._locations &&
scheme === this._locations["x" + host][port];
},
//
// see nsIHttpServerIdentity.has
//
getScheme: function(host, port)
{
this._validate("http", host, port);
var entry = this._locations["x" + host];
if (!entry)
return "";
return entry[port] || "";
},
//
// see nsIHttpServerIdentity.setPrimary
//
setPrimary: function(scheme, host, port)
{
this._validate(scheme, host, port);
this.add(scheme, host, port);
this._primaryScheme = scheme;
this._primaryHost = host;
this._primaryPort = port;
},
// NSISUPPORTS
//
// see nsISupports.QueryInterface
//
QueryInterface: function(iid)
{
if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},