!import
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et: */
3 /* ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is the MozJSHTTP server.
17 *
18 * The Initial Developer of the Original Code is
19 * Mozilla Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 2006
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 * Darin Fisher (v1, netwerk/test/TestServ.js)
25 * Christian Biesinger (v2, netwerk/test/unit/head_http_server.js)
26 * Jeff Walden <jwalden+code@mit.edu> (v3, netwerk/test/httpserver/httpd.js)
27 * Robert Sayre <sayrer@gmail.com>
28 *
29 * Alternatively, the contents of this file may be used under the terms of
30 * either the GNU General Public License Version 2 or later (the "GPL"), or
31 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
32 * in which case the provisions of the GPL or the LGPL are applicable instead
33 * of those above. If you wish to allow use of your version of this file only
34 * under the terms of either the GPL or the LGPL, and not to allow others to
35 * use your version of this file under the terms of the MPL, indicate your
36 * decision by deleting the provisions above and replace them with the notice
37 * and other provisions required by the GPL or the LGPL. If you do not delete
38 * the provisions above, a recipient may use your version of this file under
39 * the terms of any one of the MPL, the GPL or the LGPL.
40 *
41 * ***** END LICENSE BLOCK ***** */
42
43 /*
44 * An implementation of an HTTP server both as a loadable script and as an XPCOM
45 * component. See the accompanying README file for user documentation on
46 * MozJSHTTP.
47 */
48
49 const Cc = Components.classes;
50 const Ci = Components.interfaces;
51 const Cr = Components.results;
52 const Cu = Components.utils;
53 const CC = Components.Constructor;
54
55 /** True if debugging output is enabled, false otherwise. */
56 var DEBUG = false; // non-const *only* so tweakable in server tests
57
58 var gGlobalObject = this;
59
60 /**
61 * Asserts that the given condition holds. If it doesn't, the given message is
62 * dumped, a stack trace is printed, and an exception is thrown to attempt to
63 * stop execution (which unfortunately must rely upon the exception not being
64 * accidentally swallowed by the code that uses it).
65 */
NS_ASSERT
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
66 function NS_ASSERT(cond, msg)
67 {
68 if (DEBUG && !cond)
69 {
70 dumpn("###!!!");
71 dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!"));
72 dumpn("###!!! Stack follows:");
73
74 var stack = new Error().stack.split(/\n/);
anon:75:20
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
75 dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n"));
76
77 throw Cr.NS_ERROR_ABORT;
78 }
79 }
80
81 /** Constructs an HTTP error object. */
HttpError
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
82 function HttpError(code, description)
83 {
84 this.code = code;
85 this.description = description;
86 }
87 HttpError.prototype =
88 {
toString
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
89 toString: function()
90 {
91 return this.code + " " + this.description;
92 }
93 };
94
95 /**
96 * Errors thrown to trigger specific HTTP server responses.
97 */
98 const HTTP_400 = new HttpError(400, "Bad Request");
99 const HTTP_401 = new HttpError(401, "Unauthorized");
100 const HTTP_402 = new HttpError(402, "Payment Required");
101 const HTTP_403 = new HttpError(403, "Forbidden");
102 const HTTP_404 = new HttpError(404, "Not Found");
103 const HTTP_405 = new HttpError(405, "Method Not Allowed");
104 const HTTP_406 = new HttpError(406, "Not Acceptable");
105 const HTTP_407 = new HttpError(407, "Proxy Authentication Required");
106 const HTTP_408 = new HttpError(408, "Request Timeout");
107 const HTTP_409 = new HttpError(409, "Conflict");
108 const HTTP_410 = new HttpError(410, "Gone");
109 const HTTP_411 = new HttpError(411, "Length Required");
110 const HTTP_412 = new HttpError(412, "Precondition Failed");
111 const HTTP_413 = new HttpError(413, "Request Entity Too Large");
112 const HTTP_414 = new HttpError(414, "Request-URI Too Long");
113 const HTTP_415 = new HttpError(415, "Unsupported Media Type");
114 const HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable");
115 const HTTP_417 = new HttpError(417, "Expectation Failed");
116
117 const HTTP_500 = new HttpError(500, "Internal Server Error");
118 const HTTP_501 = new HttpError(501, "Not Implemented");
119 const HTTP_502 = new HttpError(502, "Bad Gateway");
120 const HTTP_503 = new HttpError(503, "Service Unavailable");
121 const HTTP_504 = new HttpError(504, "Gateway Timeout");
122 const HTTP_505 = new HttpError(505, "HTTP Version Not Supported");
123
124 /** Creates a hash with fields corresponding to the values in arr. */
array2obj
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
125 function array2obj(arr)
126 {
127 var obj = {};
128 for (var i = 0; i < arr.length; i++)
129 obj[arr[i]] = arr[i];
130 return obj;
131 }
132
133 /** Returns an array of the integers x through y, inclusive. */
range
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
134 function range(x, y)
135 {
136 var arr = [];
137 for (var i = x; i <= y; i++)
138 arr.push(i);
139 return arr;
140 }
141
142 /** An object (hash) whose fields are the numbers of all HTTP error codes. */
143 const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505)));
144
145
146 /**
147 * The character used to distinguish hidden files from non-hidden files, a la
148 * the leading dot in Apache. Since that mechanism also hides files from
149 * easy display in LXR, ls output, etc. however, we choose instead to use a
150 * suffix character. If a requested file ends with it, we append another
151 * when getting the file on the server. If it doesn't, we just look up that
152 * file. Therefore, any file whose name ends with exactly one of the character
153 * is "hidden" and available for use by the server.
154 */
155 const HIDDEN_CHAR = "^";
156
157 /**
158 * The file name suffix indicating the file containing overridden headers for
159 * a requested file.
160 */
161 const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR;
162
163 /** Type used to denote SJS scripts for CGI-like functionality. */
164 const SJS_TYPE = "sjs";
165
166
167 /** dump(str) with a trailing "\n" -- only outputs if DEBUG */
dumpn
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
168 function dumpn(str)
169 {
170 if (DEBUG)
171 dump(str + "\n");
172 }
173
174 /** Dumps the current JS stack if DEBUG. */
dumpStack
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
175 function dumpStack()
176 {
177 // peel off the frames for dumpStack() and Error()
178 var stack = new Error().stack.split(/\n/).slice(2);
179 stack.forEach(dumpn);
180 }
181
182
183 /** The XPCOM thread manager. */
184 var gThreadManager = null;
185
186
187 /**
188 * JavaScript constructors for commonly-used classes; precreating these is a
189 * speedup over doing the same from base principles. See the docs at
190 * http://developer.mozilla.org/en/docs/Components.Constructor for details.
191 */
192 const ServerSocket = CC("@mozilla.org/network/server-socket;1",
193 "nsIServerSocket",
194 "init");
195 const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
196 "nsIBinaryInputStream",
197 "setInputStream");
198 const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1",
199 "nsIScriptableInputStream",
200 "init");
201 const Pipe = CC("@mozilla.org/pipe;1",
202 "nsIPipe",
203 "init");
204 const FileInputStream = CC("@mozilla.org/network/file-input-stream;1",
205 "nsIFileInputStream",
206 "init");
207 const StreamCopier = CC("@mozilla.org/network/async-stream-copier;1",
208 "nsIAsyncStreamCopier",
209 "init");
210 const Pump = CC("@mozilla.org/network/input-stream-pump;1",
211 "nsIInputStreamPump",
212 "init");
213 const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1",
214 "nsIConverterInputStream",
215 "init");
216 const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1",
217 "nsIWritablePropertyBag2");
218 const SupportsString = CC("@mozilla.org/supports-string;1",
219 "nsISupportsString");
220
221
222 /**
223 * Returns the RFC 822/1123 representation of a date.
224 *
225 * @param date : Number
226 * the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT
227 * @returns string
228 * the representation of the given date
229 */
toDateString
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
230 function toDateString(date)
231 {
232 //
233 // rfc1123-date = wkday "," SP date1 SP time SP "GMT"
234 // date1 = 2DIGIT SP month SP 4DIGIT
235 // ; day month year (e.g., 02 Jun 1982)
236 // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
237 // ; 00:00:00 - 23:59:59
238 // wkday = "Mon" | "Tue" | "Wed"
239 // | "Thu" | "Fri" | "Sat" | "Sun"
240 // month = "Jan" | "Feb" | "Mar" | "Apr"
241 // | "May" | "Jun" | "Jul" | "Aug"
242 // | "Sep" | "Oct" | "Nov" | "Dec"
243 //
244
245 const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
246 const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
247 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
248
249 /**
250 * Processes a date and returns the encoded UTC time as a string according to
251 * the format specified in RFC 2616.
252 *
253 * @param date : Date
254 * the date to process
255 * @returns string
256 * a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
257 */
toTime
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
258 function toTime(date)
259 {
260 var hrs = date.getUTCHours();
261 var rv = (hrs < 10) ? "0" + hrs : hrs;
262
263 var mins = date.getUTCMinutes();
264 rv += ":";
265 rv += (mins < 10) ? "0" + mins : mins;
266
267 var secs = date.getUTCSeconds();
268 rv += ":";
269 rv += (secs < 10) ? "0" + secs : secs;
270
271 return rv;
272 }
273
274 /**
275 * Processes a date and returns the encoded UTC date as a string according to
276 * the date1 format specified in RFC 2616.
277 *
278 * @param date : Date
279 * the date to process
280 * @returns string
281 * a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
282 */
toDate1
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
283 function toDate1(date)
284 {
285 var day = date.getUTCDate();
286 var month = date.getUTCMonth();
287 var year = date.getUTCFullYear();
288
289 var rv = (day < 10) ? "0" + day : day;
290 rv += " " + monthStrings[month];
291 rv += " " + year;
292
293 return rv;
294 }
295
296 date = new Date(date);
297
298 const fmtString = "%wkday%, %date1% %time% GMT";
299 var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]);
300 rv = rv.replace("%time%", toTime(date));
301 return rv.replace("%date1%", toDate1(date));
302 }
303
304 /**
305 * Prints out a human-readable representation of the object o and its fields,
306 * omitting those whose names begin with "_" if showMembers != true (to ignore
307 * "private" properties exposed via getters/setters).
308 */
printObj
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
309 function printObj(o, showMembers)
310 {
311 var s = "******************************\n";
312 s += "o = {\n";
313 for (var i in o)
314 {
315 if (typeof(i) != "string" ||
316 (showMembers || (i.length > 0 && i[0] != "_")))
317 s+= " " + i + ": " + o[i] + ",\n";
318 }
319 s += " };\n";
320 s += "******************************";
321 dumpn(s);
322 }
323
324 /**
325 * Instantiates a new HTTP server.
326 */
nsHttpServer
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
327 function nsHttpServer()
328 {
329 if (!gThreadManager)
330 gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService();
331
332 /** The port on which this server listens. */
333 this._port = undefined;
334
335 /** The socket associated with this. */
336 this._socket = null;
337
338 /** The handler used to process requests to this server. */
339 this._handler = new ServerHandler(this);
340
341 /**
342 * Indicates when the server is to be shut down at the end of the request.
343 */
344 this._doQuit = false;
345
346 /**
347 * True if the socket in this is closed (and closure notifications have been
348 * sent and processed if the socket was ever opened), false otherwise.
349 */
350 this._socketClosed = true;
351 }
352 nsHttpServer.prototype =
353 {
354 // NSISERVERSOCKETLISTENER
355
356 /**
357 * Processes an incoming request coming in on the given socket and contained
358 * in the given transport.
359 *
360 * @param socket : nsIServerSocket
361 * the socket through which the request was served
362 * @param trans : nsISocketTransport
363 * the transport for the request/response
364 * @see nsIServerSocketListener.onSocketAccepted
365 */
onSocketAccepted
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
366 onSocketAccepted: function(socket, trans)
367 {
368 dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ") " +
369 "on thread " + gThreadManager.currentThread +
370 " (main is " + gThreadManager.mainThread + ")");
371
372 dumpn(">>> new connection on " + trans.host + ":" + trans.port);
373
374 const SEGMENT_SIZE = 8192;
375 const SEGMENT_COUNT = 1024;
376 var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT)
377 .QueryInterface(Ci.nsIAsyncInputStream);
378 var output = trans.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
379
380 var conn = new Connection(input, output, this, socket.port);
381 var reader = new RequestReader(conn);
382
383 // XXX add request timeout functionality here!
384
385 // Note: must use main thread here, or we might get a GC that will cause
386 // threadsafety assertions. We really need to fix XPConnect so that
387 // you can actually do things in multi-threaded JS. :-(
388 input.asyncWait(reader, 0, 0, gThreadManager.mainThread);
389 },
390
391 /**
392 * Called when the socket associated with this is closed.
393 *
394 * @param socket : nsIServerSocket
395 * the socket being closed
396 * @param status : nsresult
397 * the reason the socket stopped listening (NS_BINDING_ABORTED if the server
398 * was stopped using nsIHttpServer.stop)
399 * @see nsIServerSocketListener.onStopListening
400 */
onStopListening
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
401 onStopListening: function(socket, status)
402 {
403 dumpn(">>> shutting down server");
404 this._socketClosed = true;
405 },
406
407 // NSIHTTPSERVER
408
409 //
410 // see nsIHttpServer.start
411 //
start
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
412 start: function(port)
413 {
414 if (this._socket)
415 throw Cr.NS_ERROR_ALREADY_INITIALIZED;
416
417 this._port = port;
418 this._doQuit = this._socketClosed = false;
419
420 var socket = new ServerSocket(this._port,
421 true, // loopback only
422 -1); // default number of pending connections
423
424 dumpn(">>> listening on port " + socket.port);
425 socket.asyncListen(this);
426 this._socket = socket;
427 },
428
429 //
430 // see nsIHttpServer.stop
431 //
stop
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
432 stop: function()
433 {
434 if (!this._socket)
435 return;
436
437 dumpn(">>> stopping listening on port " + this._socket.port);
438 this._socket.close();
439 this._socket = null;
440 this._doQuit = false;
441
442 // spin an event loop and wait for the socket-close notification
443 var thr = gThreadManager.currentThread;
444 while (!this._socketClosed || this._handler.hasPendingRequests())
445 thr.processNextEvent(true);
446 },
447
448 //
449 // see nsIHttpServer.registerFile
450 //
registerFile
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
451 registerFile: function(path, file)
452 {
453 if (file && (!file.exists() || file.isDirectory()))
454 throw Cr.NS_ERROR_INVALID_ARG;
455
456 this._handler.registerFile(path, file);
457 },
458
459 //
460 // see nsIHttpServer.registerDirectory
461 //
registerDirectory
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
462 registerDirectory: function(path, directory)
463 {
464 // XXX true path validation!
465 if (path.charAt(0) != "/" ||
466 path.charAt(path.length - 1) != "/" ||
467 (directory &&
468 (!directory.exists() || !directory.isDirectory())))
469 throw Cr.NS_ERROR_INVALID_ARG;
470
471 // XXX determine behavior of non-existent /foo/bar when a /foo/bar/ mapping
472 // exists!
473
474 this._handler.registerDirectory(path, directory);
475 },
476
477 //
478 // see nsIHttpServer.registerPathHandler
479 //
registerPathHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
480 registerPathHandler: function(path, handler)
481 {
482 this._handler.registerPathHandler(path, handler);
483 },
484
485 //
486 // see nsIHttpServer.registerErrorHandler
487 //
registerErrorHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
488 registerErrorHandler: function(code, handler)
489 {
490 this._handler.registerErrorHandler(code, handler);
491 },
492
493 //
494 // see nsIHttpServer.setIndexHandler
495 //
setIndexHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
496 setIndexHandler: function(handler)
497 {
498 this._handler.setIndexHandler(handler);
499 },
500
501 //
502 // see nsIHttpServer.registerContentType
503 //
registerContentType
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
504 registerContentType: function(ext, type)
505 {
506 this._handler.registerContentType(ext, type);
507 },
508
509 // NSISUPPORTS
510
511 //
512 // see nsISupports.QueryInterface
513 //
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
514 QueryInterface: function(iid)
515 {
516 if (iid.equals(Ci.nsIHttpServer) ||
517 iid.equals(Ci.nsIServerSocketListener) ||
518 iid.equals(Ci.nsISupports))
519 return this;
520
521 throw Cr.NS_ERROR_NO_INTERFACE;
522 },
523
524
525 // NON-XPCOM PUBLIC API
526
527 /**
528 * Returns true iff this server is not running (and is not in the process of
529 * serving any requests still to be processed when the server was last
530 * stopped after being run).
531 */
isStopped
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
532 isStopped: function()
533 {
534 return this._socketClosed && !this._handler.hasPendingRequests();
535 },
536
537
538 // PRIVATE IMPLEMENTATION
539
540 /**
541 * Closes the passed-in connection.
542 *
543 * @param connection : Connection
544 * the connection to close
545 */
_endConnection
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
546 _endConnection: function(connection)
547 {
548 //
549 // Order is important below: we must decrement handler._pendingRequests
550 // BEFORE calling this.stop(), if needed, in connection.destroy().
551 // this.stop() returns only when the server socket's closed AND all pending
552 // requests are complete, which clearly isn't (and never will be) the case
553 // if it were the other way around.
554 //
555
556 connection.close();
557
558 NS_ASSERT(this == connection.server);
559
560 this._handler._pendingRequests--;
561
562 connection.destroy();
563 },
564
565 /**
566 * Requests that the server be shut down when possible.
567 */
_requestQuit
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
568 _requestQuit: function()
569 {
570 dumpn(">>> requesting a quit");
571 dumpStack();
572 this._doQuit = true;
573 }
574
575 };
576
577
578 /**
579 * Represents a connection to the server (and possibly in the future the thread
580 * on which the connection is processed).
581 *
582 * @param input : nsIInputStream
583 * stream from which incoming data on the connection is read
584 * @param output : nsIOutputStream
585 * stream to write data out the connection
586 * @param server : nsHttpServer
587 * the server handling the connection
588 * @param port : int
589 * the port on which the server is running
590 */
Connection
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
591 function Connection(input, output, server, port)
592 {
593 /** Stream of incoming data. */
594 this.input = input;
595
596 /** Stream for outgoing data. */
597 this.output = output;
598
599 /** The server associated with this request. */
600 this.server = server;
601
602 /** The port on which the server is running. */
603 this.port = port;
604
605 /** State variables for debugging. */
606 this._closed = this._processed = false;
607 }
608 Connection.prototype =
609 {
610 /** Closes this connection's input/output streams. */
close
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
611 close: function()
612 {
613 this.input.close();
614 this.output.close();
615 this._closed = true;
616 },
617
618 /**
619 * Initiates processing of this connection, using the data in the given
620 * request.
621 *
622 * @param request : Request
623 * the request which should be processed
624 */
process
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
625 process: function(request)
626 {
627 NS_ASSERT(!this._closed && !this._processed);
628
629 this._processed = true;
630
631 this.server._handler.handleResponse(this, request);
632 },
633
634 /**
635 * Initiates processing of this connection, generating a response with the
636 * given HTTP error code.
637 *
638 * @param code : uint
639 * an HTTP code, so in the range [0, 1000)
640 * @param metadata : Request
641 * incomplete data about the incoming request (since there were errors
642 * during its processing
643 */
processError
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
644 processError: function(code, metadata)
645 {
646 NS_ASSERT(!this._closed && !this._processed);
647
648 this._processed = true;
649
650 this.server._handler.handleError(code, this, metadata);
651 },
652
653 /** Ends this connection, destroying the resources it uses. */
end
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
654 end: function()
655 {
656 this.server._endConnection(this);
657 },
658
659 /** Destroys resources used by this. */
destroy
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
660 destroy: function()
661 {
662 if (!this._closed)
663 this.close();
664
665 // If an error triggered a server shutdown, act on it now
666 var server = this.server;
667 if (server._doQuit)
668 server.stop();
669 }
670 };
671
672
673
674 /** Returns an array of count bytes from the given input stream. */
readBytes
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
675 function readBytes(inputStream, count)
676 {
677 return new BinaryInputStream(inputStream).readByteArray(count);
678 }
679
680
681
682 /** Request reader processing states; see RequestReader for details. */
683 const READER_INITIAL = 0;
684 const READER_IN_HEADERS = 1;
685 const READER_IN_BODY = 2;
686
687
688 /**
689 * Reads incoming request data asynchronously, does any necessary preprocessing,
690 * and forwards it to the request handler. Processing occurs in three states:
691 *
692 * READER_INITIAL Haven't read the entire request line yet
693 * READER_IN_HEADERS Reading headers in the request
694 * READER_IN_BODY Finished reading all request headers (when body
695 * support's added, will be reading the body)
696 *
697 * During the first two stages, initial metadata about the request is gathered
698 * into a Request object. Once the status line and headers have been processed,
699 * we create a Response and hand it off to the ServerHandler to be given to the
700 * appropriate request handler.
701 *
702 * XXX we should set up a stream to provide lazy access to the request body
703 *
704 * @param connection : Connection
705 * the connection for the request being read
706 */
RequestReader
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
707 function RequestReader(connection)
708 {
709 /** Connection metadata for this request. */
710 this._connection = connection;
711
712 /**
713 * A container providing line-by-line access to the raw bytes that make up the
714 * data which has been read from the connection but has not yet been acted
715 * upon (by passing it to the request handler or by extracting request
716 * metadata from it).
717 */
718 this._data = new LineData();
719
720 /** The current state of parsing the incoming request. */
721 this._state = READER_INITIAL;
722
723 /** Metadata constructed from the incoming request for the request handler. */
724 this._metadata = new Request(connection.port);
725
726 /**
727 * Used to preserve state if we run out of line data midway through a
728 * multi-line header. _lastHeaderName stores the name of the header, while
729 * _lastHeaderValue stores the value we've seen so far for the header.
730 *
731 * These fields are always either both undefined or both strings.
732 */
733 this._lastHeaderName = this._lastHeaderValue = undefined;
734 }
735 RequestReader.prototype =
736 {
737 // NSIINPUTSTREAMCALLBACK
738
739 /**
740 * Called when more data from the incoming request is available. This method
741 * then reads the available data from input and deals with that data as
742 * necessary, depending upon the syntax of already-downloaded data.
743 *
744 * @param input : nsIAsyncInputStream
745 * the stream of incoming data from the connection
746 */
onInputStreamReady
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
747 onInputStreamReady: function(input)
748 {
749 dumpn("*** onInputStreamReady(input=" + input + ") on thread " +
750 gThreadManager.currentThread + " (main is " +
751 gThreadManager.mainThread + ")");
752 dumpn("*** this._state == " + this._state);
753
754 var count = input.available();
755
756 // Handle cases where we get more data after a request error has been
757 // discovered but *before* we can close the connection.
758 if (!this._data)
759 return;
760
761 var moreAvailable = false;
762
763 switch (this._state)
764 {
765 case READER_INITIAL:
766 moreAvailable = this._processRequestLine(input, count);
767 break;
768
769 case READER_IN_HEADERS:
770 moreAvailable = this._processHeaders(input, count);
771 break;
772
773 case READER_IN_BODY:
774 // XXX handle the request body! until then, just stop reading
775 break;
776
777 default:
778 NS_ASSERT(false);
779 }
780
781 if (moreAvailable)
782 input.asyncWait(this, 0, 0, gThreadManager.currentThread);
783 },
784
785 //
786 // see nsISupports.QueryInterface
787 //
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
788 QueryInterface: function(aIID)
789 {
790 if (aIID.equals(Ci.nsIInputStreamCallback) ||
791 aIID.equals(Ci.nsISupports))
792 return this;
793
794 throw Cr.NS_ERROR_NO_INTERFACE;
795 },
796
797
798 // PRIVATE API
799
800 /**
801 * Reads count bytes from input and processes unprocessed, downloaded data as
802 * a request line.
803 *
804 * @param input : nsIInputStream
805 * stream from which count bytes of data must be read
806 * @param count : PRUint32
807 * the number of bytes of data which must be read from input
808 * @returns boolean
809 * true if more data must be read from the request, false otherwise
810 */
_processRequestLine
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
811 _processRequestLine: function(input, count)
812 {
813 NS_ASSERT(this._state == READER_INITIAL);
814
815 var data = this._data;
816 data.appendBytes(readBytes(input, count));
817
818
819 // servers SHOULD ignore any empty line(s) received where a Request-Line
820 // is expected (section 4.1)
821 var line = {};
822 var readSuccess;
823 while ((readSuccess = data.readLine(line)) && line.value == "")
824 dumpn("*** ignoring beginning blank line...");
825
826 // if we don't have a full line, wait until we do
827 if (!readSuccess)
828 return true;
829
830 // we have the first non-blank line
831 try
832 {
833 this._parseRequestLine(line.value);
834
835 // do we have more header data to read?
836 if (!this._parseHeaders())
837 return true;
838
839 // headers complete, do a data check and then forward to the handler
840 this._validateRequest();
841 return this._handleResponse();
842 }
843 catch (e)
844 {
845 this._handleError(e);
846 return false;
847 }
848 },
849
850 /**
851 * Reads data from input and processes it, assuming it is either at the
852 * beginning or in the middle of processing request headers.
853 *
854 * @param input : nsIInputStream
855 * stream from which count bytes of data must be read
856 * @param count : PRUint32
857 * the number of bytes of data which must be read from input
858 * @returns boolean
859 * true if more data must be read from the request, false otherwise
860 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
861 _processHeaders: function(input, count)
862 {
863 NS_ASSERT(this._state == READER_IN_HEADERS);
864
865 // XXX things to fix here:
866 //
867 // - need to support RFC 2047-encoded non-US-ASCII characters
868 // - really support absolute URLs (requires telling the server all its
869 // hostnames, beyond just localhost:port or 127.0.0.1:port)
870
871 this._data.appendBytes(readBytes(input, count));
872
873 try
874 {
875 // do we have all the headers?
876 if (!this._parseHeaders())
877 return true;
878
879 // we have all the headers, continue with the body
880 this._validateRequest();
881 return this._handleResponse();
882 }
883 catch (e)
884 {
885 this._handleError(e);
886 return false;
887 }
888 },
889
890 /**
891 * Does various post-header checks on the data in this request.
892 *
893 * @throws : HttpError
894 * if the request was malformed in some way
895 */
_validateRequest
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
896 _validateRequest: function()
897 {
898 NS_ASSERT(this._state == READER_IN_BODY);
899
900 dumpn("*** _validateRequest");
901
902 var metadata = this._metadata;
903 var headers = metadata._headers;
904
905 var isHttp11 = metadata._httpVersion.equals(nsHttpVersion.HTTP_1_1);
906
907 // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header
908 if (isHttp11 && !headers.hasHeader("Host"))
909 throw HTTP_400;
910 },
911
912 /**
913 * Handles responses in case of error, either in the server or in the request.
914 *
915 * @param e
916 * the specific error encountered, which is an HttpError in the case where
917 * the request is in some way invalid or cannot be fulfilled; if this isn't
918 * an HttpError we're going to be paranoid and shut down, because that
919 * shouldn't happen, ever
920 */
_handleError
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
921 _handleError: function(e)
922 {
923 var server = this._connection.server;
924 if (e instanceof HttpError)
925 {
926 var code = e.code;
927 }
928 else
929 {
930 // no idea what happened -- be paranoid and shut down
931 code = 500;
932 server._requestQuit();
933 }
934
935 // make attempted reuse of data an error
936 this._data = null;
937
938 this._connection.processError(code, this._metadata);
939 },
940
941 /**
942 * Now that we've read the request line and headers, we can actually hand off
943 * the request to be handled.
944 *
945 * This method is called once per request, after the request line and all
946 * headers have been received.
947 *
948 * @returns boolean
949 * true if more data must be read, false otherwise
950 */
_handleResponse
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
951 _handleResponse: function()
952 {
953 NS_ASSERT(this._state == READER_IN_BODY);
954
955 // XXX set up a stream for data in the request body here
956
957 // We don't need the line-based data any more, so make attempted reuse an
958 // error.
959 this._data = null;
960
961 this._connection.process(this._metadata);
962
963 return false;
964 },
965
966
967 // PARSING
968
969 /**
970 * Parses the request line for the HTTP request associated with this.
971 *
972 * @param line : string
973 * the request line
974 */
_parseRequestLine
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
975 _parseRequestLine: function(line)
976 {
977 NS_ASSERT(this._state == READER_INITIAL);
978
979 dumpn("*** _parseRequestLine('" + line + "')");
980
981 var metadata = this._metadata;
982
983 // clients and servers SHOULD accept any amount of SP or HT characters
984 // between fields, even though only a single SP is required (section 19.3)
985 var request = line.split(/[ \t]+/);
986 if (!request || request.length != 3)
987 throw HTTP_400;
988
989 metadata._method = request[0];
990
991 // get the HTTP version
992 var ver = request[2];
993 var match = ver.match(/^HTTP\/(\d+\.\d+)$/);
994 if (!match)
995 throw HTTP_400;
996
997 // determine HTTP version
998 try
999 {
1000 metadata._httpVersion = new nsHttpVersion(match[1]);
1001 if (!metadata._httpVersion.equals(nsHttpVersion.HTTP_1_0) &&
1002 !metadata._httpVersion.equals(nsHttpVersion.HTTP_1_1))
1003 throw "unsupported HTTP version";
1004 }
1005 catch (e)
1006 {
1007 // we support HTTP/1.0 and HTTP/1.1 only
1008 throw HTTP_501;
1009 }
1010
1011
1012 var fullPath = request[1];
1013
1014 if (fullPath.charAt(0) != "/")
1015 {
1016 // XXX we don't really support absolute URIs yet -- a MUST for HTTP/1.1;
1017 // for now just get the path and use that, ignoring hostport
1018 try
1019 {
1020 var uri = Cc["@mozilla.org/network/io-service;1"]
1021 .getService(Ci.nsIIOService)
1022 .newURI(fullPath, null, null);
1023 fullPath = uri.path;
1024 }
1025 catch (e) { /* invalid URI */ }
1026 if (fullPath.charAt(0) != "/")
1027 {
1028 this.errorCode = 400;
1029 return;
1030 }
1031 }
1032
1033 var splitter = fullPath.indexOf("?");
1034 if (splitter < 0)
1035 {
1036 // _queryString already set in ctor
1037 metadata._path = fullPath;
1038 }
1039 else
1040 {
1041 metadata._path = fullPath.substring(0, splitter);
1042 metadata._queryString = fullPath.substring(splitter + 1);
1043 }
1044
1045 // our work here is finished
1046 this._state = READER_IN_HEADERS;
1047 },
1048
1049 /**
1050 * Parses all available HTTP headers in this until the header-ending CRLFCRLF,
1051 * adding them to the store of headers in the request.
1052 *
1053 * @throws
1054 * HTTP_400 if the headers are malformed
1055 * @returns boolean
1056 * true if all headers have now been processed, false otherwise
1057 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1058 _parseHeaders: function()
1059 {
1060 NS_ASSERT(this._state == READER_IN_HEADERS);
1061
1062 dumpn("*** _parseHeaders");
1063
1064 var data = this._data;
1065
1066 var headers = this._metadata._headers;
1067 var lastName = this._lastHeaderName;
1068 var lastVal = this._lastHeaderValue;
1069
1070 var line = {};
1071 while (true)
1072 {
1073 NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)),
1074 lastName === undefined ?
1075 "lastVal without lastName? lastVal: '" + lastVal + "'" :
1076 "lastName without lastVal? lastName: '" + lastName + "'");
1077
1078 if (!data.readLine(line))
1079 {
1080 // save any data we have from the header we might still be processing
1081 this._lastHeaderName = lastName;
1082 this._lastHeaderValue = lastVal;
1083 return false;
1084 }
1085
1086 var lineText = line.value;
1087 var firstChar = lineText.charAt(0);
1088
1089 // blank line means end of headers
1090 if (lineText == "")
1091 {
1092 // we're finished with the previous header
1093 if (lastName)
1094 {
1095 try
1096 {
1097 headers.setHeader(lastName, lastVal, true);
1098 }
1099 catch (e)
1100 {
1101 dumpn("*** e == " + e);
1102 throw HTTP_400;
1103 }
1104 }
1105 else
1106 {
1107 // no headers in request -- valid for HTTP/1.0 requests
1108 }
1109
1110 // either way, we're done processing headers
1111 this._state = READER_IN_BODY;
1112 return true;
1113 }
1114 else if (firstChar == " " || firstChar == "\t")
1115 {
1116 // multi-line header if we've already seen a header line
1117 if (!lastName)
1118 {
1119 // we don't have a header to continue!
1120 throw HTTP_400;
1121 }
1122
1123 // append this line's text to the value; starts with SP/HT, so no need
1124 // for separating whitespace
1125 lastVal += lineText;
1126 }
1127 else
1128 {
1129 // we have a new header, so set the old one (if one existed)
1130 if (lastName)
1131 {
1132 try
1133 {
1134 headers.setHeader(lastName, lastVal, true);
1135 }
1136 catch (e)
1137 {
1138 dumpn("*** e == " + e);
1139 throw HTTP_400;
1140 }
1141 }
1142
1143 var colon = lineText.indexOf(":"); // first colon must be splitter
1144 if (colon < 1)
1145 {
1146 // no colon or missing header field-name
1147 throw HTTP_400;
1148 }
1149
1150 // set header name, value (to be set in the next loop, usually)
1151 lastName = lineText.substring(0, colon);
1152 lastVal = lineText.substring(colon + 1);
1153 } // empty, continuation, start of header
1154 } // while (true)
1155 }
1156 };
1157
1158
1159 /** The character codes for CR and LF. */
1160 const CR = 0x0D, LF = 0x0A;
1161
1162 /**
1163 * Calculates the number of characters before the first CRLF pair in array, or
1164 * -1 if the array contains no CRLF pair.
1165 *
1166 * @param array : Array
1167 * an array of numbers in the range [0, 256), each representing a single
1168 * character; the first CRLF is the lowest index i where
1169 * |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|,
1170 * if such an |i| exists, and -1 otherwise
1171 * @returns int
1172 * the index of the first CRLF if any were present, -1 otherwise
1173 */
findCRLF
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1174 function findCRLF(array)
1175 {
1176 for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1))
1177 {
1178 if (array[i + 1] == LF)
1179 return i;
1180 }
1181 return -1;
1182 }
1183
1184
1185 /**
1186 * A container which provides line-by-line access to the arrays of bytes with
1187 * which it is seeded.
1188 */
LineData
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1189 function LineData()
1190 {
1191 /** An array of queued bytes from which to get line-based characters. */
1192 this._data = [];
1193 }
1194 LineData.prototype =
1195 {
1196 /**
1197 * Appends the bytes in the given array to the internal data cache maintained
1198 * by this.
1199 */
appendBytes
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1200 appendBytes: function(bytes)
1201 {
1202 Array.prototype.push.apply(this._data, bytes);
1203 },
1204
1205 /**
1206 * Removes and returns a line of data, delimited by CRLF, from this.
1207 *
1208 * @param out
1209 * an object whose "value" property will be set to the first line of text
1210 * present in this, sans CRLF, if this contains a full CRLF-delimited line
1211 * of text; if this doesn't contain enough data, the value of the property
1212 * is undefined
1213 * @returns boolean
1214 * true if a full line of data could be read from the data in this, false
1215 * otherwise
1216 */
readLine
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1217 readLine: function(out)
1218 {
1219 var data = this._data;
1220 var length = findCRLF(data);
1221 if (length < 0)
1222 return false;
1223
1224 //
1225 // We have the index of the CR, so remove all the characters, including
1226 // CRLF, from the array with splice, and convert the removed array into the
1227 // corresponding string, from which we then strip the trailing CRLF.
1228 //
1229 // Getting the line in this matter acknowledges that substring is an O(1)
1230 // operation in SpiderMonkey because strings are immutable, whereas two
1231 // splices, both from the beginning of the data, are less likely to be as
1232 // cheap as a single splice plus two extra character conversions.
1233 //
1234 var line = String.fromCharCode.apply(null, data.splice(0, length + 2));
1235 out.value = line.substring(0, length);
1236
1237 return true;
1238 },
1239
1240 /**
1241 * Retrieve any bytes we may have overread from the request's postdata. After
1242 * this method is called, this must not be used in any way.
1243 *
1244 * @returns Array
1245 * the bytes read past the CRLFCRLF at the end of request headers
1246 */
purge
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1247 purge: function()
1248 {
1249 var data = this._data;
1250 this._data = null;
1251 return data;
1252 }
1253 };
1254
1255
1256
1257 /**
1258 * Creates a request-handling function for an nsIHttpRequestHandler object.
1259 */
createHandlerFunc
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1260 function createHandlerFunc(handler)
1261 {
anon:1262:9
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1262 return function(metadata, response) { handler.handle(metadata, response); };
1263 }
1264
1265
1266 /**
1267 * The default handler for directories; writes an HTML response containing a
1268 * slightly-formatted directory listing.
1269 */
defaultIndexHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1270 function defaultIndexHandler(metadata, response)
1271 {
1272 response.setHeader("Content-Type", "text/html", false);
1273
1274 var path = htmlEscape(decodeURI(metadata.path));
1275
1276 //
1277 // Just do a very basic bit of directory listings -- no need for too much
1278 // fanciness, especially since we don't have a style sheet in which we can
1279 // stick rules (don't want to pollute the default path-space).
1280 //
1281
1282 var body = '<html>\
1283 <head>\
1284 <title>' + path + '</title>\
1285 </head>\
1286 <body>\
1287 <h1>' + path + '</h1>\
1288 <ol style="list-style-type: none">';
1289
1290 var directory = metadata.getProperty("directory");
1291 NS_ASSERT(directory && directory.isDirectory());
1292
1293 var fileList = [];
1294 var files = directory.directoryEntries;
1295 while (files.hasMoreElements())
1296 {
1297 var f = files.getNext().QueryInterface(Ci.nsIFile);
1298 var name = f.leafName;
1299 if (!f.isHidden() &&
1300 (name.charAt(name.length - 1) != HIDDEN_CHAR ||
1301 name.charAt(name.length - 2) == HIDDEN_CHAR))
1302 fileList.push(f);
1303 }
1304
1305 fileList.sort(fileSort);
1306
1307 for (var i = 0; i < fileList.length; i++)
1308 {
1309 var file = fileList[i];
1310 try
1311 {
1312 var name = file.leafName;
1313 if (name.charAt(name.length - 1) == HIDDEN_CHAR)
1314 name = name.substring(0, name.length - 1);
1315 var sep = file.isDirectory() ? "/" : "";
1316
1317 // Note: using " to delimit the attribute here because encodeURIComponent
1318 // passes through '.
1319 var item = '<li><a href="' + encodeURIComponent(name) + sep + '">' +
1320 htmlEscape(name) + sep +
1321 '</a></li>';
1322
1323 body += item;
1324 }
1325 catch (e) { /* some file system error, ignore the file */ }
1326 }
1327
1328 body += ' </ol>\
1329 </body>\
1330 </html>';
1331
1332 response.bodyOutputStream.write(body, body.length);
1333 }
1334
1335 /**
1336 * Sorts a and b (nsIFile objects) into an aesthetically pleasing order.
1337 */
fileSort
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1338 function fileSort(a, b)
1339 {
1340 var dira = a.isDirectory(), dirb = b.isDirectory();
1341
1342 if (dira && !dirb)
1343 return -1;
1344 if (dirb && !dira)
1345 return 1;
1346
1347 var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase();
1348 return nameb > namea ? -1 : 1;
1349 }
1350
1351
1352 /**
1353 * Converts an externally-provided path into an internal path for use in
1354 * determining file mappings.
1355 *
1356 * @param path
1357 * the path to convert
1358 * @param encoded
1359 * true if the given path should be passed through decodeURI prior to
1360 * conversion
1361 * @throws URIError
1362 * if path is incorrectly encoded
1363 */
toInternalPath
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1364 function toInternalPath(path, encoded)
1365 {
1366 if (encoded)
1367 path = decodeURI(path);
1368
1369 var comps = path.split("/");
1370 for (var i = 0, sz = comps.length; i < sz; i++)
1371 {
1372 var comp = comps[i];
1373 if (comp.charAt(comp.length - 1) == HIDDEN_CHAR)
1374 comps[i] = comp + HIDDEN_CHAR;
1375 }
1376 return comps.join("/");
1377 }
1378
1379
1380 /**
1381 * Adds custom-specified headers for the given file to the given response, if
1382 * any such headers are specified.
1383 *
1384 * @param file
1385 * the file on the disk which is to be written
1386 * @param metadata
1387 * metadata about the incoming request
1388 * @param response
1389 * the Response to which any specified headers/data should be written
1390 * @throws HTTP_500
1391 * if an error occurred while processing custom-specified headers
1392 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1393 function maybeAddHeaders(file, metadata, response)
1394 {
1395 var name = file.leafName;
1396 if (name.charAt(name.length - 1) == HIDDEN_CHAR)
1397 name = name.substring(0, name.length - 1);
1398
1399 var headerFile = file.parent;
1400 headerFile.append(name + HEADERS_SUFFIX);
1401
1402 if (!headerFile.exists())
1403 return;
1404
1405 const PR_RDONLY = 0x01;
1406 var fis = new FileInputStream(headerFile, PR_RDONLY, 0444,
1407 Ci.nsIFileInputStream.CLOSE_ON_EOF);
1408
1409 var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0);
1410 lis.QueryInterface(Ci.nsIUnicharLineInputStream);
1411
1412 try
1413 {
1414 var line = {value: ""};
1415 var more = lis.readLine(line);
1416
1417 if (!more && line.value == "")
1418 return;
1419
1420
1421 // request line
1422
1423 var status = line.value;
1424 if (status.indexOf("HTTP ") == 0)
1425 {
1426 status = status.substring(5);
1427 var space = status.indexOf(" ");
1428 var code, description;
1429 if (space < 0)
1430 {
1431 code = status;
1432 description = "";
1433 }
1434 else
1435 {
1436 code = status.substring(0, space);
1437 description = status.substring(space + 1, status.length);
1438 }
1439
1440 response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description);
1441
1442 line.value = "";
1443 more = lis.readLine(line);
1444 }
1445
1446 // headers
1447 while (more || line.value != "")
1448 {
1449 var header = line.value;
1450 var colon = header.indexOf(":");
1451
1452 response.setHeader(header.substring(0, colon),
1453 header.substring(colon + 1, header.length),
1454 false); // allow overriding server-set headers
1455
1456 line.value = "";
1457 more = lis.readLine(line);
1458 }
1459 }
1460 catch (e)
1461 {
1462 dumpn("WARNING: error in headers for " + metadata.path + ": " + e);
1463 throw HTTP_500;
1464 }
1465 }
1466
1467
1468 /**
1469 * An object which handles requests for a server, executing default and
1470 * overridden behaviors as instructed by the code which uses and manipulates it.
1471 * Default behavior includes the paths / and /trace (diagnostics), with some
1472 * support for HTTP error pages for various codes and fallback to HTTP 500 if
1473 * those codes fail for any reason.
1474 *
1475 * @param server : nsHttpServer
1476 * the server in which this handler is being used
1477 */
ServerHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1478 function ServerHandler(server)
1479 {
1480 // FIELDS
1481
1482 /**
1483 * The nsHttpServer instance associated with this handler.
1484 */
1485 this._server = server;
1486
1487 /**
1488 * A variable used to ensure that all requests are fully complete before the
1489 * server shuts down, to avoid callbacks from compiled code calling back into
1490 * empty contexts. See also the comment before this field is next modified.
1491 */
1492 this._pendingRequests = 0;
1493
1494 /**
1495 * A FileMap object containing the set of path->nsILocalFile mappings for
1496 * all directory mappings set in the server (e.g., "/" for /var/www/html/,
1497 * "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2).
1498 *
1499 * Note carefully: the leading and trailing "/" in each path (not file) are
1500 * removed before insertion to simplify the code which uses this. You have
1501 * been warned!
1502 */
1503 this._pathDirectoryMap = new FileMap();
1504
1505 /**
1506 * Custom request handlers for the server in which this resides. Path-handler
1507 * pairs are stored as property-value pairs in this property.
1508 *
1509 * @see ServerHandler.prototype._defaultPaths
1510 */
1511 this._overridePaths = {};
1512
1513 /**
1514 * Custom request handlers for the error handlers in the server in which this
1515 * resides. Path-handler pairs are stored as property-value pairs in this
1516 * property.
1517 *
1518 * @see ServerHandler.prototype._defaultErrors
1519 */
1520 this._overrideErrors = {};
1521
1522 /**
1523 * Maps file extensions to their MIME types in the server, overriding any
1524 * mapping that might or might not exist in the MIME service.
1525 */
1526 this._mimeMappings = {};
1527
1528 /**
1529 * The default handler for requests for directories, used to serve directories
1530 * when no index file is present.
1531 */
1532 this._indexHandler = defaultIndexHandler;
1533 }
1534 ServerHandler.prototype =
1535 {
1536 // PUBLIC API
1537
1538 /**
1539 * Handles a request to this server, responding to the request appropriately
1540 * and initiating server shutdown if necessary.
1541 *
1542 * This method never throws an exception.
1543 *
1544 * @param connection : Connection
1545 * the connection for this request
1546 * @param metadata : Request
1547 * request metadata as generated from the initial request
1548 */
handleResponse
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1549 handleResponse: function(connection, metadata)
1550 {
1551 var response = new Response();
1552
1553 var path = metadata.path;
1554 dumpn("*** path == " + path);
1555
1556 try
1557 {
1558 try
1559 {
1560 // explicit paths first, then files based on existing directory mappings,
1561 // then (if the file doesn't exist) built-in server default paths
1562 if (path in this._overridePaths)
1563 this._overridePaths[path](metadata, response);
1564 else
1565 this._handleDefault(metadata, response);
1566 }
1567 catch (e)
1568 {
1569 response.recycle();
1570
1571 if (!(e instanceof HttpError))
1572 {
1573 dumpn("*** unexpected error: e == " + e);
1574 throw HTTP_500;
1575 }
1576 if (e.code != 404)
1577 throw e;
1578
1579 dumpn("*** default: " + (path in this._defaultPaths));
1580
1581 if (path in this._defaultPaths)
1582 this._defaultPaths[path](metadata, response);
1583 else
1584 throw HTTP_404;
1585 }
1586 }
1587 catch (e)
1588 {
1589 var errorCode = "internal";
1590
1591 try
1592 {
1593 if (!(e instanceof HttpError))
1594 throw e;
1595
1596 errorCode = e.code;
1597 dumpn("*** errorCode == " + errorCode);
1598
1599 response.recycle();
1600
1601 this._handleError(errorCode, metadata, response);
1602 }
1603 catch (e2)
1604 {
1605 dumpn("*** error handling " + errorCode + " error: " +
1606 "e2 == " + e2 + ", shutting down server");
1607
1608 response.destroy();
1609 connection.close();
1610 connection.server.stop();
1611 return;
1612 }
1613 }
1614
1615 this._end(response, connection);
1616 },
1617
1618 //
1619 // see nsIHttpServer.registerFile
1620 //
registerFile
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1621 registerFile: function(path, file)
1622 {
1623 if (!file)
1624 {
1625 dumpn("*** unregistering '" + path + "' mapping");
1626 delete this._overridePaths[path];
1627 return;
1628 }
1629
1630 dumpn("*** registering '" + path + "' as mapping to " + file.path);
1631 file = file.clone();
1632
1633 var self = this;
1634 this._overridePaths[path] =
anon:1635:6
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1635 function(metadata, response)
1636 {
1637 if (!file.exists())
1638 throw HTTP_404;
1639
1640 response.setStatusLine(metadata.httpVersion, 200, "OK");
1641 self._writeFileResponse(metadata, file, response);
1642 };
1643 },
1644
1645 //
1646 // see nsIHttpServer.registerPathHandler
1647 //
registerPathHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1648 registerPathHandler: function(path, handler)
1649 {
1650 // XXX true path validation!
1651 if (path.charAt(0) != "/")
1652 throw Cr.NS_ERROR_INVALID_ARG;
1653
1654 this._handlerToField(handler, this._overridePaths, path);
1655 },
1656
1657 //
1658 // see nsIHttpServer.registerDirectory
1659 //
registerDirectory
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1660 registerDirectory: function(path, directory)
1661 {
1662 // strip off leading and trailing '/' so that we can use lastIndexOf when
1663 // determining exactly how a path maps onto a mapped directory --
1664 // conditional is required here to deal with "/".substring(1, 0) being
1665 // converted to "/".substring(0, 1) per the JS specification
1666 var key = path.length == 1 ? "" : path.substring(1, path.length - 1);
1667
1668 // the path-to-directory mapping code requires that the first character not
1669 // be "/", or it will go into an infinite loop
1670 if (key.charAt(0) == "/")
1671 throw Cr.NS_ERROR_INVALID_ARG;
1672
1673 key = toInternalPath(key, false);
1674
1675 if (directory)
1676 {
1677 dumpn("*** mapping '" + path + "' to the location " + directory.path);
1678 this._pathDirectoryMap.put(key, directory);
1679 }
1680 else
1681 {
1682 dumpn("*** removing mapping for '" + path + "'");
1683 this._pathDirectoryMap.put(key, null);
1684 }
1685 },
1686
1687 //
1688 // see nsIHttpServer.registerErrorHandler
1689 //
registerErrorHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1690 registerErrorHandler: function(err, handler)
1691 {
1692 if (!(err in HTTP_ERROR_CODES))
1693 dumpn("*** WARNING: registering non-HTTP/1.1 error code " +
1694 "(" + err + ") handler -- was this intentional?");
1695
1696 this._handlerToField(handler, this._overrideErrors, err);
1697 },
1698
1699 //
1700 // see nsIHttpServer.setIndexHandler
1701 //
setIndexHandler
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1702 setIndexHandler: function(handler)
1703 {
1704 if (!handler)
1705 handler = defaultIndexHandler;
1706 else if (typeof(handler) != "function")
1707 handler = createHandlerFunc(handler);
1708
1709 this._indexHandler = handler;
1710 },
1711
1712 //
1713 // see nsIHttpServer.registerContentType
1714 //
registerContentType
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1715 registerContentType: function(ext, type)
1716 {
1717 if (!type)
1718 delete this._mimeMappings[ext];
1719 else
1720 this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type);
1721 },
1722
1723 // NON-XPCOM PUBLIC API
1724
1725 /**
1726 * Returns true if this handler is in the middle of handling any current
1727 * requests; this must be false before the server in which this is used may be
1728 * safely shut down.
1729 */
hasPendingRequests
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1730 hasPendingRequests: function()
1731 {
1732 return this._pendingRequests > 0;
1733 },
1734
1735
1736 // PRIVATE API
1737
1738 /**
1739 * Sets or remove (if handler is null) a handler in an object with a key.
1740 *
1741 * @param handler
1742 * a handler, either function or an nsIHttpRequestHandler
1743 * @param dict
1744 * The object to attach the handler to.
1745 * @param key
1746 * The field name of the handler.
1747 */
_handlerToField
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1748 _handlerToField: function(handler, dict, key)
1749 {
1750 // for convenience, handler can be a function if this is run from xpcshell
1751 if (typeof(handler) == "function")
1752 dict[key] = handler;
1753 else if (handler)
1754 dict[key] = createHandlerFunc(handler);
1755 else
1756 delete dict[key];
1757 },
1758
1759 /**
1760 * Handles a request which maps to a file in the local filesystem (if a base
1761 * path has already been set; otherwise the 404 error is thrown).
1762 *
1763 * @param metadata : Request
1764 * metadata for the incoming request
1765 * @param response : Response
1766 * an uninitialized Response to the given request, to be initialized by a
1767 * request handler
1768 * @throws HTTP_###
1769 * if an HTTP error occurred (usually HTTP_404); note that in this case the
1770 * calling code must handle cleanup of the response by calling .destroy()
1771 * or .recycle()
1772 */
_handleDefault
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1773 _handleDefault: function(metadata, response)
1774 {
1775 response.setStatusLine(metadata.httpVersion, 200, "OK");
1776
1777 var path = metadata.path;
1778 NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">");
1779
1780 // determine the actual on-disk file; this requires finding the deepest
1781 // path-to-directory mapping in the requested URL
1782 var file = this._getFileForPath(path);
1783
1784 // the "file" might be a directory, in which case we either serve the
1785 // contained index.html or make the index handler write the response
1786 if (file.exists() && file.isDirectory())
1787 {
1788 file.append("index.html"); // make configurable?
1789 if (!file.exists() || file.isDirectory())
1790 {
1791 metadata._ensurePropertyBag();
1792 metadata._bag.setPropertyAsInterface("directory", file.parent);
1793 this._indexHandler(metadata, response);
1794 return;
1795 }
1796 }
1797
1798 // alternately, the file might not exist
1799 if (!file.exists())
1800 throw HTTP_404;
1801
1802 // finally...
1803 dumpn("*** handling '" + path + "' as mapping to " + file.path);
1804 this._writeFileResponse(metadata, file, response);
1805 },
1806
1807 /**
1808 * Writes an HTTP response for the given file, including setting headers for
1809 * file metadata.
1810 *
1811 * @param metadata : Request
1812 * the Request for which a response is being generated
1813 * @param file : nsILocalFile
1814 * the file which is to be sent in the response
1815 * @param response : Response
1816 * the response to which the file should be written
1817 */
_writeFileResponse
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1818 _writeFileResponse: function(metadata, file, response)
1819 {
1820 const PR_RDONLY = 0x01;
1821
1822 var type = this._getTypeFromFile(file);
1823 if (type == SJS_TYPE)
1824 {
1825 try
1826 {
1827 var fis = new FileInputStream(file, PR_RDONLY, 0444,
1828 Ci.nsIFileInputStream.CLOSE_ON_EOF);
1829 var sis = new ScriptableInputStream(fis);
1830 var s = Cu.Sandbox(gGlobalObject);
1831 Cu.evalInSandbox(sis.read(file.fileSize), s);
1832 s.handleRequest(metadata, response);
1833 }
1834 catch (e)
1835 {
1836 dumpn("*** error running SJS: " + e);
1837 throw HTTP_500;
1838 }
1839 }
1840 else
1841 {
1842 try
1843 {
1844 response.setHeader("Last-Modified",
1845 toDateString(file.lastModifiedTime),
1846 false);
1847 }
1848 catch (e) { /* lastModifiedTime threw, ignore */ }
1849
1850 response.setHeader("Content-Type", type, false);
1851
1852 var fis = new FileInputStream(file, PR_RDONLY, 0444,
1853 Ci.nsIFileInputStream.CLOSE_ON_EOF);
1854 response.bodyOutputStream.writeFrom(fis, file.fileSize);
1855 fis.close();
1856
1857 maybeAddHeaders(file, metadata, response);
1858 }
1859 },
1860
1861 /**
1862 * Gets a content-type for the given file, first by checking for any custom
1863 * MIME-types registered with this handler for the file's extension, second by
1864 * asking the global MIME service for a content-type, and finally by failing
1865 * over to application/octet-stream.
1866 *
1867 * @param file : nsIFile
1868 * the nsIFile for which to get a file type
1869 * @returns string
1870 * the best content-type which can be determined for the file
1871 */
_getTypeFromFile
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1872 _getTypeFromFile: function(file)
1873 {
1874 try
1875 {
1876 var name = file.leafName;
1877 var dot = name.lastIndexOf(".");
1878 if (dot > 0)
1879 {
1880 var ext = name.slice(dot + 1);
1881 if (ext in this._mimeMappings)
1882 return this._mimeMappings[ext];
1883 }
1884 return Cc["@mozilla.org/uriloader/external-helper-app-service;1"]
1885 .getService(Ci.nsIMIMEService)
1886 .getTypeFromFile(file);
1887 }
1888 catch (e)
1889 {
1890 return "application/octet-stream";
1891 }
1892 },
1893
1894 /**
1895 * Returns the nsILocalFile which corresponds to the path, as determined using
1896 * all registered path->directory mappings and any paths which are explicitly
1897 * overridden.
1898 *
1899 * @param path : string
1900 * the server path for which a file should be retrieved, e.g. "/foo/bar"
1901 * @throws HttpError
1902 * when the correct action is the corresponding HTTP error (i.e., because no
1903 * mapping was found for a directory in path, the referenced file doesn't
1904 * exist, etc.)
1905 * @returns nsILocalFile
1906 * the file to be sent as the response to a request for the path
1907 */
_getFileForPath
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1908 _getFileForPath: function(path)
1909 {
1910 // decode and add underscores as necessary
1911 try
1912 {
1913 path = toInternalPath(path, true);
1914 }
1915 catch (e)
1916 {
1917 throw HTTP_400; // malformed path
1918 }
1919
1920 // next, get the directory which contains this path
1921 var pathMap = this._pathDirectoryMap;
1922
1923 // An example progression of tmp for a path "/foo/bar/baz/" might be:
1924 // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", ""
1925 var tmp = path.substring(1);
1926 while (true)
1927 {
1928 // do we have a match for current head of the path?
1929 var file = pathMap.get(tmp);
1930 if (file)
1931 {
1932 // XXX hack; basically disable showing mapping for /foo/bar/ when the
1933 // requested path was /foo/bar, because relative links on the page
1934 // will all be incorrect -- we really need the ability to easily
1935 // redirect here instead
1936 if (tmp == path.substring(1) &&
1937 tmp.length != 0 &&
1938 tmp.charAt(tmp.length - 1) != "/")
1939 file = null;
1940 else
1941 break;
1942 }
1943
1944 // if we've finished trying all prefixes, exit
1945 if (tmp == "")
1946 break;
1947
1948 tmp = tmp.substring(0, tmp.lastIndexOf("/"));
1949 }
1950
1951 // no mapping applies, so 404
1952 if (!file)
1953 throw HTTP_404;
1954
1955
1956 // last, get the file for the path within the determined directory
1957 var parentFolder = file.parent;
1958 var dirIsRoot = (parentFolder == null);
1959
1960 // Strategy here is to append components individually, making sure we
1961 // never move above the given directory; this allows paths such as
1962 // "<file>/foo/../bar" but prevents paths such as "<file>/../base-sibling";
1963 // this component-wise approach also means the code works even on platforms
1964 // which don't use "/" as the directory separator, such as Windows
1965 var leafPath = path.substring(tmp.length + 1);
1966 var comps = leafPath.split("/");
1967 for (var i = 0, sz = comps.length; i < sz; i++)
1968 {
1969 var comp = comps[i];
1970
1971 if (comp == "..")
1972 file = file.parent;
1973 else if (comp == "." || comp == "")
1974 continue;
1975 else
1976 file.append(comp);
1977
1978 if (!dirIsRoot && file.equals(parentFolder))
1979 throw HTTP_403;
1980 }
1981
1982 return file;
1983 },
1984
1985 /**
1986 * Writes the error page for the given HTTP error code over the given
1987 * connection.
1988 *
1989 * @param errorCode : uint
1990 * the HTTP error code to be used
1991 * @param connection : Connection
1992 * the connection on which the error occurred
1993 */
handleError
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
1994 handleError: function(errorCode, connection)
1995 {
1996 var response = new Response();
1997
1998 dumpn("*** error in request: " + errorCode);
1999
2000 try
2001 {
2002 this._handleError(errorCode, new Request(connection.port), response);
2003 this._end(response, connection);
2004 }
2005 catch (e)
2006 {
2007 connection.close();
2008 connection.server.stop();
2009 }
2010 },
2011
2012 /**
2013 * Handles a request which generates the given error code, using the
2014 * user-defined error handler if one has been set, gracefully falling back to
2015 * the x00 status code if the code has no handler, and failing to status code
2016 * 500 if all else fails.
2017 *
2018 * @param errorCode : uint
2019 * the HTTP error which is to be returned
2020 * @param metadata : Request
2021 * metadata for the request, which will often be incomplete since this is an
2022 * error
2023 * @param response : Response
2024 * an uninitialized Response should be initialized when this method
2025 * completes with information which represents the desired error code in the
2026 * ideal case or a fallback code in abnormal circumstances (i.e., 500 is a
2027 * fallback for 505, per HTTP specs)
2028 */
_handleError
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2029 _handleError: function(errorCode, metadata, response)
2030 {
2031 if (!metadata)
2032 throw Cr.NS_ERROR_NULL_POINTER;
2033
2034 var errorX00 = errorCode - (errorCode % 100);
2035
2036 try
2037 {
2038 if (!(errorCode in HTTP_ERROR_CODES))
2039 dumpn("*** WARNING: requested invalid error: " + errorCode);
2040
2041 // RFC 2616 says that we should try to handle an error by its class if we
2042 // can't otherwise handle it -- if that fails, we revert to handling it as
2043 // a 500 internal server error, and if that fails we throw and shut down
2044 // the server
2045
2046 // actually handle the error
2047 try
2048 {
2049 if (errorCode in this._overrideErrors)
2050 this._overrideErrors[errorCode](metadata, response);
2051 else if (errorCode in this._defaultErrors)
2052 this._defaultErrors[errorCode](metadata, response);
2053 }
2054 catch (e)
2055 {
2056 // don't retry the handler that threw
2057 if (errorX00 == errorCode)
2058 throw HTTP_500;
2059
2060 dumpn("*** error in handling for error code " + errorCode + ", " +
2061 "falling back to " + errorX00 + "...");
2062 if (errorX00 in this._overrideErrors)
2063 this._overrideErrors[errorX00](metadata, response);
2064 else if (errorX00 in this._defaultErrors)
2065 this._defaultErrors[errorX00](metadata, response);
2066 else
2067 throw HTTP_500;
2068 }
2069 }
2070 catch (e)
2071 {
2072 response.recycle();
2073
2074 // we've tried everything possible for a meaningful error -- now try 500
2075 dumpn("*** error in handling for error code " + errorX00 + ", falling " +
2076 "back to 500...");
2077
2078 try
2079 {
2080 if (500 in this._overrideErrors)
2081 this._overrideErrors[500](metadata, response);
2082 else
2083 this._defaultErrors[500](metadata, response);
2084 }
2085 catch (e2)
2086 {
2087 dumpn("*** multiple errors in default error handlers!");
2088 dumpn("*** e == " + e + ", e2 == " + e2);
2089 throw e2;
2090 }
2091 }
2092 },
2093
2094 /**
2095 * Called when all processing necessary for the current request has completed
2096 * and response headers and data have been determined. This method takes
2097 * those headers and data, sends them to the HTTP client, and halts further
2098 * processing. It will also send a quit message to the server if necessary.
2099 *
2100 * This method never throws an exception.
2101 *
2102 * @param response : Response
2103 * the desired response
2104 * @param connection : Connection
2105 * the connection associated with the given response
2106 * @note
2107 * after completion, response must be considered "dead", and none of its
2108 * methods or properties may be accessed
2109 */
_end
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2110 _end: function(response, connection)
2111 {
2112 // post-processing
2113 response.setHeader("Connection", "close", false);
2114 response.setHeader("Server", "httpd.js", false);
2115 response.setHeader("Date", toDateString(Date.now()), false);
2116
2117 var bodyStream = response.bodyInputStream;
2118
2119 // XXX suckage time!
2120 //
2121 // If the body of the response has had no data written to it (or has never
2122 // been accessed -- same deal internally since we'll create one if we have
2123 // to access bodyInputStream but have neither an input stream nor an
2124 // output stream), the in-tree implementation of nsIPipe is such that
2125 // when we try to close the pipe's output stream with no data in it, this
2126 // is interpreted as an error and closing the output stream also closes
2127 // the input stream. .available then throws, so we catch and deal as best
2128 // as we can.
2129 //
2130 // Unfortunately, the easy alternative (substitute a storage stream for a
2131 // pipe) also doesn't work. There's no problem writing zero bytes to the
2132 // output end of the stream, but then attempting to get an input stream to
2133 // read fails because the seek position must be strictly less than the
2134 // buffer size.
2135 //
2136 // Much as I'd like the zero-byte body to be a mostly-unimportant problem,
2137 // there are some HTTP responses such as 304 Not Modified which MUST have
2138 // zero-byte bodies, so this *is* a necessary hack.
2139 try
2140 {
2141 var available = bodyStream.available();
2142 }
2143 catch (e)
2144 {
2145 available = 0;
2146 }
2147
2148 response.setHeader("Content-Length", available.toString(), false);
2149
2150
2151 // construct and send response
2152
2153 // request-line
2154 var preamble = "HTTP/" + response.httpVersion + " " +
2155 response.httpCode + " " +
2156 response.httpDescription + "\r\n";
2157
2158 // headers
2159 var head = response.headers;
2160 var headEnum = head.enumerator;
2161 while (headEnum.hasMoreElements())
2162 {
2163 var fieldName = headEnum.getNext()
2164 .QueryInterface(Ci.nsISupportsString)
2165 .data;
2166 preamble += fieldName + ": " + head.getHeader(fieldName) + "\r\n";
2167 }
2168
2169 // end request-line/headers
2170 preamble += "\r\n";
2171
2172 var outStream = connection.output;
2173 try
2174 {
2175 outStream.write(preamble, preamble.length);
2176 }
2177 catch (e)
2178 {
2179 // Connection closed already? Even if not, failure to write the response
2180 // means we probably will fail later anyway, so in the interests of
2181 // avoiding exceptions we'll (possibly) close the connection and return.
2182 response.destroy();
2183 connection.close();
2184 return;
2185 }
2186
2187 // In certain situations, it's possible for us to have a race between
2188 // the copy observer's onStopRequest and the listener for a channel
2189 // opened to this server. Since we include a Content-Length header with
2190 // every response, if the channel snarfs up all the data we promise,
2191 // calls onStopRequest on the listener (and the server is shut down
2192 // by that listener, causing the script to finish executing), and then
2193 // tries to call onStopRequest on the copyObserver, we'll call into a
2194 // scope with no Components and cause assertions *and* fail to close the
2195 // connection properly. To combat this, during server shutdown we delay
2196 // full shutdown until any pending requests are fully copied using this
2197 // property on the server handler. We increment before (possibly)
2198 // starting the copy observer and decrement when the copy completes,
2199 // ensuring that all copies complete before the server fully shuts down.
2200 //
2201 // We do this for every request primarily to simplify maintenance of this
2202 // property (and also because it's less fragile when we can remove the
2203 // zero-sized body hack used above).
2204 this._pendingRequests++;
2205
2206 var server = this._server;
2207
2208 // If we have a body, send it -- if we don't, then don't bother with a
2209 // heavyweight async copy which doesn't need to happen and just do
2210 // response post-processing (usually handled by the copy observer)
2211 // directly
2212 if (available != 0)
2213 {
2214 /**
2215 * Observer of the copying of data from the body stream generated by a
2216 * request handler to the output stream for the server socket. It
2217 * handles all post-request-writing cleanup details, such as closing
2218 * open streams and shutting down the server in case of errors.
2219 */
2220 var copyObserver =
2221 {
onStartRequest
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2222 onStartRequest: function(request, context) { /* don't care */ },
2223
2224 /**
2225 * Called when the async stream copy completes. This is place where
2226 * final cleanup should occur, including stream closures and
2227 * response destruction. Note that errors which are detected here
2228 * should still shut down the server, for safety.
2229 */
onStopRequest
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2230 onStopRequest: function(request, cx, statusCode)
2231 {
2232 // statusCode can indicate user-triggered failures (e.g. if the user
2233 // closes the connection during the copy, which would cause a status
2234 // of NS_ERROR_NET_RESET), so don't treat its value being an error
2235 // code as catastrophic. I can create this situation when running
2236 // Mochitests in a debug build by clicking the Stop button during
2237 // test execution, but it's not exactly a surefire way to reproduce
2238 // the problem.
2239 if (!Components.isSuccessCode(statusCode))
2240 {
2241 dumpn("*** WARNING: non-success statusCode in onStopRequest: " +
2242 statusCode);
2243 }
2244
2245 // we're completely finished with this response
2246 response.destroy();
2247
2248 connection.end();
2249 },
2250
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
NUMBER
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
STRING
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
STRING
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2251 QueryInterface: function(aIID)
2252 {
2253 if (aIID.equals(Ci.nsIRequestObserver) ||
2254 aIID.equals(Ci.nsISupports))
2255 return this;
2256
2257 throw Cr.NS_ERROR_NO_INTERFACE;
2258 }
2259 };
2260
2261
2262 //
2263 // Now write out the body, async since we might be serving this to
2264 // ourselves on the same thread, and writing too much data would deadlock.
2265 //
2266 var copier = new StreamCopier(bodyStream, outStream,
2267 null,
2268 true, true, 8192);
2269 copier.asyncCopy(copyObserver, null);
2270 }
2271 else
2272 {
2273 // finished with the response -- destroy
2274 response.destroy();
2275 this._server._endConnection(connection);
2276 }
2277 },
2278
2279 // FIELDS
2280
2281 /**
2282 * This object contains the default handlers for the various HTTP error codes.
2283 */
2284 _defaultErrors:
2285 {
2286 400: function(metadata, response)
2287 {
2288 // none of the data in metadata is reliable, so hard-code everything here
2289 response.setStatusLine("1.1", 400, "Bad Request");
2290 response.setHeader("Content-Type", "text/plain", false);
2291
2292 var body = "Bad request\n";
2293 response.bodyOutputStream.write(body, body.length);
2294 },
2295 403: function(metadata, response)
2296 {
2297 response.setStatusLine(metadata.httpVersion, 403, "Forbidden");
2298 response.setHeader("Content-Type", "text/html", false);
2299
2300 var body = "<html>\
2301 <head><title>403 Forbidden</title></head>\
2302 <body>\
2303 <h1>403 Forbidden</h1>\
2304 </body>\
2305 </html>";
2306 response.bodyOutputStream.write(body, body.length);
2307 },
2308 404: function(metadata, response)
2309 {
2310 response.setStatusLine(metadata.httpVersion, 404, "Not Found");
2311 response.setHeader("Content-Type", "text/html", false);
2312
2313 var body = "<html>\
2314 <head><title>404 Not Found</title></head>\
2315 <body>\
2316 <h1>404 Not Found</h1>\
2317 <p>\
2318 <span style='font-family: monospace;'>" +
2319 htmlEscape(metadata.path) +
2320 "</span> was not found.\
2321 </p>\
2322 </body>\
2323 </html>";
2324 response.bodyOutputStream.write(body, body.length);
2325 },
2326 500: function(metadata, response)
2327 {
2328 response.setStatusLine(metadata.httpVersion,
2329 500,
2330 "Internal Server Error");
2331 response.setHeader("Content-Type", "text/html", false);
2332
2333 var body = "<html>\
2334 <head><title>500 Internal Server Error</title></head>\
2335 <body>\
2336 <h1>500 Internal Server Error</h1>\
2337 <p>Something's broken in this server and\
2338 needs to be fixed.</p>\
2339 </body>\
2340 </html>";
2341 response.bodyOutputStream.write(body, body.length);
2342 },
2343 501: function(metadata, response)
2344 {
2345 response.setStatusLine(metadata.httpVersion, 501, "Not Implemented");
2346 response.setHeader("Content-Type", "text/html", false);
2347
2348 var body = "<html>\
2349 <head><title>501 Not Implemented</title></head>\
2350 <body>\
2351 <h1>501 Not Implemented</h1>\
2352 <p>This server is not (yet) Apache.</p>\
2353 </body>\
2354 </html>";
2355 response.bodyOutputStream.write(body, body.length);
2356 },
2357 505: function(metadata, response)
2358 {
2359 response.setStatusLine("1.1", 505, "HTTP Version Not Supported");
2360 response.setHeader("Content-Type", "text/html", false);
2361
2362 var body = "<html>\
2363 <head><title>505 HTTP Version Not Supported</title></head>\
2364 <body>\
2365 <h1>505 HTTP Version Not Supported</h1>\
2366 <p>This server only supports HTTP/1.0 and HTTP/1.1\
2367 connections.</p>\
2368 </body>\
2369 </html>";
2370 response.bodyOutputStream.write(body, body.length);
2371 }
2372 },
2373
2374 /**
2375 * Contains handlers for the default set of URIs contained in this server.
2376 */
2377 _defaultPaths:
2378 {
2379 "/": function(metadata, response)
2380 {
2381 response.setStatusLine(metadata.httpVersion, 200, "OK");
2382 response.setHeader("Content-Type", "text/html", false);
2383
2384 var body = "<html>\
2385 <head><title>MozJSHTTP</title></head>\
2386 <body>\
2387 <h1>MozJSHTTP</h1>\
2388 <p>If you're seeing this page, MozJSHTTP is up and\
2389 serving requests! Now set a base path and serve some\
2390 files!</p>\
2391 </body>\
2392 </html>";
2393
2394 response.bodyOutputStream.write(body, body.length);
2395 },
2396
2397 "/trace": function(metadata, response)
2398 {
2399 response.setStatusLine(metadata.httpVersion, 200, "OK");
2400 response.setHeader("Content-Type", "text/plain", false);
2401
2402 var body = "Request (semantically equivalent, slightly reformatted):\n\n";
2403 body += metadata.method + " " + metadata.path;
2404
2405 if (metadata.queryString)
2406 body += "?" + metadata.queryString;
2407
2408 body += " HTTP/" + metadata.httpVersion + "\r\n";
2409
2410 var headEnum = metadata.headers;
2411 while (headEnum.hasMoreElements())
2412 {
2413 var fieldName = headEnum.getNext()
2414 .QueryInterface(Ci.nsISupportsString)
2415 .data;
2416 body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n";
2417 }
2418
2419 response.bodyOutputStream.write(body, body.length);
2420 }
2421 }
2422 };
2423
2424
2425 /**
2426 * Maps absolute paths to files on the local file system (as nsILocalFiles).
2427 */
FileMap
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2428 function FileMap()
2429 {
2430 /** Hash which will map paths to nsILocalFiles. */
2431 this._map = {};
2432 }
2433 FileMap.prototype =
2434 {
2435 // PUBLIC API
2436
2437 /**
2438 * Maps key to a clone of the nsILocalFile value if value is non-null;
2439 * otherwise, removes any extant mapping for key.
2440 *
2441 * @param key : string
2442 * string to which a clone of value is mapped
2443 * @param value : nsILocalFile
2444 * the file to map to key, or null to remove a mapping
2445 */
put
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2446 put: function(key, value)
2447 {
2448 if (value)
2449 this._map[key] = value.clone();
2450 else
2451 delete this._map[key];
2452 },
2453
2454 /**
2455 * Returns a clone of the nsILocalFile mapped to key, or null if no such
2456 * mapping exists.
2457 *
2458 * @param key : string
2459 * key to which the returned file maps
2460 * @returns nsILocalFile
2461 * a clone of the mapped file, or null if no mapping exists
2462 */
get
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2463 get: function(key)
2464 {
2465 var val = this._map[key];
2466 return val ? val.clone() : null;
2467 }
2468 };
2469
2470
2471 // Response CONSTANTS
2472
2473 // token = *<any CHAR except CTLs or separators>
2474 // CHAR = <any US-ASCII character (0-127)>
2475 // CTL = <any US-ASCII control character (0-31) and DEL (127)>
2476 // separators = "(" | ")" | "<" | ">" | "@"
2477 // | "," | ";" | ":" | "\" | <">
2478 // | "/" | "[" | "]" | "?" | "="
2479 // | "{" | "}" | SP | HT
2480 const IS_TOKEN_ARRAY =
2481 [0, 0, 0, 0, 0, 0, 0, 0, // 0
2482 0, 0, 0, 0, 0, 0, 0, 0, // 8
2483 0, 0, 0, 0, 0, 0, 0, 0, // 16
2484 0, 0, 0, 0, 0, 0, 0, 0, // 24
2485
2486 0, 1, 0, 1, 1, 1, 1, 1, // 32
2487 0, 0, 1, 1, 0, 1, 1, 0, // 40
2488 1, 1, 1, 1, 1, 1, 1, 1, // 48
2489 1, 1, 0, 0, 0, 0, 0, 0, // 56
2490
2491 0, 1, 1, 1, 1, 1, 1, 1, // 64
2492 1, 1, 1, 1, 1, 1, 1, 1, // 72
2493 1, 1, 1, 1, 1, 1, 1, 1, // 80
2494 1, 1, 1, 0, 0, 0, 1, 1, // 88
2495
2496 1, 1, 1, 1, 1, 1, 1, 1, // 96
2497 1, 1, 1, 1, 1, 1, 1, 1, // 104
2498 1, 1, 1, 1, 1, 1, 1, 1, // 112
2499 1, 1, 1, 0, 1, 0, 1]; // 120
2500
2501
2502 /**
2503 * Determines whether the given character code is a CTL.
2504 *
2505 * @param code : uint
2506 * the character code
2507 * @returns boolean
2508 * true if code is a CTL, false otherwise
2509 */
isCTL
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2510 function isCTL(code)
2511 {
2512 return (code >= 0 && code <= 31) || (code == 127);
2513 }
2514
2515 /**
2516 * Represents a response to an HTTP request, encapsulating all details of that
2517 * response. This includes all headers, the HTTP version, status code and
2518 * explanation, and the entity itself.
2519 */
Response
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2520 function Response()
2521 {
2522 // delegate initialization behavior to .recycle(), for code-sharing;
2523 // see there for field descriptions as well
2524 this.recycle();
2525 }
2526 Response.prototype =
2527 {
2528 // PUBLIC CONSTRUCTION API
2529
2530 //
2531 // see nsIHttpResponse.bodyOutputStream
2532 //
get_bodyOutputStream
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2533 get bodyOutputStream()
2534 {
2535 this._ensureAlive();
2536
2537 if (!this._bodyOutputStream && !this._outputProcessed)
2538 {
2539 const PR_UINT32_MAX = Math.pow(2, 32) - 1;
2540 var pipe = new Pipe(false, false, 0, PR_UINT32_MAX, null);
2541 this._bodyOutputStream = pipe.outputStream;
2542 this._bodyInputStream = pipe.inputStream;
2543 }
2544
2545 return this._bodyOutputStream;
2546 },
2547
2548 //
2549 // see nsIHttpResponse.write
2550 //
write
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2551 write: function(data)
2552 {
2553 var dataAsString = String(data);
2554 this.bodyOutputStream.write(dataAsString, dataAsString.length);
2555 },
2556
2557 //
2558 // see nsIHttpResponse.setStatusLine
2559 //
setStatusLine
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2560 setStatusLine: function(httpVersion, code, description)
2561 {
2562 this._ensureAlive();
2563
2564 if (!(code >= 0 && code < 1000))
2565 throw Cr.NS_ERROR_INVALID_ARG;
2566
2567 try
2568 {
2569 var httpVer;
2570 // avoid version construction for the most common cases
2571 if (!httpVersion || httpVersion == "1.1")
2572 httpVer = nsHttpVersion.HTTP_1_1;
2573 else if (httpVersion == "1.0")
2574 httpVer = nsHttpVersion.HTTP_1_0;
2575 else
2576 httpVer = new nsHttpVersion(httpVersion);
2577 }
2578 catch (e)
2579 {
2580 throw Cr.NS_ERROR_INVALID_ARG;
2581 }
2582
2583 // Reason-Phrase = *<TEXT, excluding CR, LF>
2584 // TEXT = <any OCTET except CTLs, but including LWS>
2585 //
2586 // XXX this ends up disallowing octets which aren't Unicode, I think -- not
2587 // much to do if description is IDL'd as string
2588 if (!description)
2589 description = "";
2590 for (var i = 0; i < description.length; i++)
2591 if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t")
2592 throw Cr.NS_ERROR_INVALID_ARG;
2593
2594 // set the values only after validation to preserve atomicity
2595 this._httpDescription = description;
2596 this._httpCode = code;
2597 this._httpVersion = httpVer;
2598 },
2599
2600 //
2601 // see nsIHttpResponse.setHeader
2602 //
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2603 setHeader: function(name, value, merge)
2604 {
2605 this._ensureAlive();
2606
2607 this._headers.setHeader(name, value, merge);
2608 },
2609
2610 // POST-CONSTRUCTION API (not exposed externally)
2611
2612 /**
2613 * The HTTP version number of this, as a string (e.g. "1.1").
2614 */
get_httpVersion
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2615 get httpVersion()
2616 {
2617 this._ensureAlive();
2618
2619 return this._httpVersion.toString();
2620 },
2621
2622 /**
2623 * The HTTP status code of this response, as a string of three characters per
2624 * RFC 2616.
2625 */
get_httpCode
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2626 get httpCode()
2627 {
2628 this._ensureAlive();
2629
2630 var codeString = (this._httpCode < 10 ? "0" : "") +
2631 (this._httpCode < 100 ? "0" : "") +
2632 this._httpCode;
2633 return codeString;
2634 },
2635
2636 /**
2637 * The description of the HTTP status code of this response, or "" if none is
2638 * set.
2639 */
get_httpDescription
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2640 get httpDescription()
2641 {
2642 this._ensureAlive();
2643
2644 return this._httpDescription;
2645 },
2646
2647 /**
2648 * The headers in this response, as an nsHttpHeaders object.
2649 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2650 get headers()
2651 {
2652 this._ensureAlive();
2653
2654 return this._headers;
2655 },
2656
2657 //
2658 // see nsHttpHeaders.getHeader
2659 //
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2660 getHeader: function(name)
2661 {
2662 this._ensureAlive();
2663
2664 return this._headers.getHeader(name);
2665 },
2666
2667 /**
2668 * A stream containing the data stored in the body of this response, which is
2669 * the data written to this.bodyOutputStream. Accessing this property will
2670 * prevent further writes to bodyOutputStream and will remove that property
2671 * from this, so the only time this should be accessed should be after this
2672 * Response has been fully processed by a request handler.
2673 */
get_bodyInputStream
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2674 get bodyInputStream()
2675 {
2676 this._ensureAlive();
2677
2678 if (!this._outputProcessed)
2679 {
2680 // if nothing was ever written to bodyOutputStream, we never created a
2681 // pipe -- do so now by writing the empty string to this.bodyOutputStream
2682 if (!this._bodyOutputStream)
2683 this.bodyOutputStream.write("", 0);
2684
2685 this._outputProcessed = true;
2686 }
2687 if (this._bodyOutputStream)
2688 {
2689 this._bodyOutputStream.close(); // flushes buffered data
2690 this._bodyOutputStream = null; // don't try closing again
2691 }
2692 return this._bodyInputStream;
2693 },
2694
2695 /**
2696 * Resets this response to its original state, destroying any currently-held
2697 * resources in the process. Use this method to invalidate an existing
2698 * response and reuse it later, such as when an arbitrary handler has
2699 * failed and may have altered the visible state of this (such as by
2700 * setting headers).
2701 *
2702 * This method may be called on Responses which have been .destroy()ed.
2703 */
recycle
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2704 recycle: function()
2705 {
2706 if (this._bodyOutputStream)
2707 {
2708 this._bodyOutputStream.close();
2709 this._bodyOutputStream = null;
2710 }
2711 if (this._bodyInputStream)
2712 {
2713 this._bodyInputStream.close();
2714 this._bodyInputStream = null;
2715 }
2716
2717 /**
2718 * The HTTP version of this response; defaults to 1.1 if not set by the
2719 * handler.
2720 */
2721 this._httpVersion = nsHttpVersion.HTTP_1_1;
2722
2723 /**
2724 * The HTTP code of this response; defaults to 200.
2725 */
2726 this._httpCode = 200;
2727
2728 /**
2729 * The description of the HTTP code in this response; defaults to "OK".
2730 */
2731 this._httpDescription = "OK";
2732
2733 /**
2734 * An nsIHttpHeaders object in which the headers in this response should be
2735 * stored.
2736 */
2737 this._headers = new nsHttpHeaders();
2738
2739 /**
2740 * Set to true when this has its .destroy() method called; further actions on
2741 * this will then fail.
2742 */
2743 this._destroyed = false;
2744
2745 /**
2746 * Flipped when this.bodyOutputStream is closed; prevents the body from being
2747 * reopened after it has data written to it and has been closed.
2748 */
2749 this._outputProcessed = false;
2750 },
2751
2752 /**
2753 * Destroys all resources held by this. After this method is called, no other
2754 * method or property on this must be accessed (except .recycle, which may be
2755 * used to reuse this Response). Although in many situations resources may be
2756 * automagically cleaned up, it is highly recommended that this method be
2757 * called whenever a Response is no longer used, both as a precaution and
2758 * because this implementation may not always do so.
2759 *
2760 * This method is idempotent.
2761 */
destroy
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2762 destroy: function()
2763 {
2764 if (this._destroyed)
2765 return;
2766
2767 if (this._bodyOutputStream)
2768 {
2769 this._bodyOutputStream.close();
2770 this._bodyOutputStream = null;
2771 }
2772 if (this._bodyInputStream)
2773 {
2774 this._bodyInputStream.close();
2775 this._bodyInputStream = null;
2776 }
2777
2778 this._destroyed = true;
2779 },
2780
2781 // PRIVATE IMPLEMENTATION
2782
2783 /** Ensures that this hasn't had its .destroy() method called. */
_ensureAlive
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2784 _ensureAlive: function()
2785 {
2786 if (this._destroyed)
2787 throw Cr.NS_ERROR_FAILURE;
2788 }
2789 };
2790
2791
2792 /**
2793 * A container for utility functions used with HTTP headers.
2794 */
2795 const headerUtils =
2796 {
2797 /**
2798 * Normalizes fieldName (by converting it to lowercase) and ensures it is a
2799 * valid header field name (although not necessarily one specified in RFC
2800 * 2616).
2801 *
2802 * @throws NS_ERROR_INVALID_ARG
2803 * if fieldName does not match the field-name production in RFC 2616
2804 * @returns string
2805 * fieldName converted to lowercase if it is a valid header, for characters
2806 * where case conversion is possible
2807 */
normalizeFieldName
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2808 normalizeFieldName: function(fieldName)
2809 {
2810 if (fieldName == "")
2811 throw Cr.NS_ERROR_INVALID_ARG;
2812
2813 for (var i = 0, sz = fieldName.length; i < sz; i++)
2814 {
2815 if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)])
2816 {
2817 dumpn(fieldName + " is not a valid header field name!");
2818 throw Cr.NS_ERROR_INVALID_ARG;
2819 }
2820 }
2821
2822 return fieldName.toLowerCase();
2823 },
2824
2825 /**
2826 * Ensures that fieldValue is a valid header field value (although not
2827 * necessarily as specified in RFC 2616 if the corresponding field name is
2828 * part of the HTTP protocol), normalizes the value if it is, and
2829 * returns the normalized value.
2830 *
2831 * @param fieldValue : string
2832 * a value to be normalized as an HTTP header field value
2833 * @throws NS_ERROR_INVALID_ARG
2834 * if fieldValue does not match the field-value production in RFC 2616
2835 * @returns string
2836 * fieldValue as a normalized HTTP header field value
2837 */
normalizeFieldValue
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2838 normalizeFieldValue: function(fieldValue)
2839 {
2840 // field-value = *( field-content | LWS )
2841 // field-content = <the OCTETs making up the field-value
2842 // and consisting of either *TEXT or combinations
2843 // of token, separators, and quoted-string>
2844 // TEXT = <any OCTET except CTLs,
2845 // but including LWS>
2846 // LWS = [CRLF] 1*( SP | HT )
2847 //
2848 // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
2849 // qdtext = <any TEXT except <">>
2850 // quoted-pair = "\" CHAR
2851 // CHAR = <any US-ASCII character (octets 0 - 127)>
2852
2853 // Any LWS that occurs between field-content MAY be replaced with a single
2854 // SP before interpreting the field value or forwarding the message
2855 // downstream (section 4.2); we replace 1*LWS with a single SP
2856 var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " ");
2857
2858 // remove leading/trailing LWS (which has been converted to SP)
2859 val = val.replace(/^ +/, "").replace(/ +$/, "");
2860
2861 // that should have taken care of all CTLs, so val should contain no CTLs
2862 for (var i = 0, len = val.length; i < len; i++)
2863 if (isCTL(val.charCodeAt(i)))
2864 throw Cr.NS_ERROR_INVALID_ARG;
2865
2866 // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly
2867 // normalize, however, so this can be construed as a tightening of the
2868 // spec and not entirely as a bug
2869 return val;
2870 }
2871 };
2872
2873
2874
2875 /**
2876 * Converts the given string into a string which is safe for use in an HTML
2877 * context.
2878 *
2879 * @param str : string
2880 * the string to make HTML-safe
2881 * @returns string
2882 * an HTML-safe version of str
2883 */
htmlEscape
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2884 function htmlEscape(str)
2885 {
2886 // this is naive, but it'll work
2887 var s = "";
2888 for (var i = 0; i < str.length; i++)
2889 s += "&#" + str.charCodeAt(i) + ";";
2890 return s;
2891 }
2892
2893
2894 /**
2895 * Constructs an object representing an HTTP version (see section 3.1).
2896 *
2897 * @param versionString
2898 * a string of the form "#.#", where # is an non-negative decimal integer with
2899 * or without leading zeros
2900 * @throws
2901 * if versionString does not specify a valid HTTP version number
2902 */
nsHttpVersion
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2903 function nsHttpVersion(versionString)
2904 {
2905 var matches = /^(\d+)\.(\d+)$/.exec(versionString);
2906 if (!matches)
2907 throw "Not a valid HTTP version!";
2908
2909 /** The major version number of this, as a number. */
2910 this.major = parseInt(matches[1], 10);
2911
2912 /** The minor version number of this, as a number. */
2913 this.minor = parseInt(matches[2], 10);
2914
2915 if (isNaN(this.major) || isNaN(this.minor) ||
2916 this.major < 0 || this.minor < 0)
2917 throw "Not a valid HTTP version!";
2918 }
2919 nsHttpVersion.prototype =
2920 {
2921 /**
2922 * Returns the standard string representation of the HTTP version represented
2923 * by this (e.g., "1.1").
2924 */
toString
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2925 toString: function ()
2926 {
2927 return this.major + "." + this.minor;
2928 },
2929
2930 /**
2931 * Returns true if this represents the same HTTP version as otherVersion,
2932 * false otherwise.
2933 *
2934 * @param otherVersion : nsHttpVersion
2935 * the version to compare against this
2936 */
equals
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2937 equals: function (otherVersion)
2938 {
2939 return this.major == otherVersion.major &&
2940 this.minor == otherVersion.minor;
2941 }
2942 };
2943
2944 nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0");
2945 nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1");
2946
2947
2948 /**
2949 * An object which stores HTTP headers for a request or response.
2950 *
2951 * Note that since headers are case-insensitive, this object converts headers to
2952 * lowercase before storing them. This allows the getHeader and hasHeader
2953 * methods to work correctly for any case of a header, but it means that the
2954 * values returned by .enumerator may not be equal case-sensitively to the
2955 * values passed to setHeader when adding headers to this.
2956 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2957 function nsHttpHeaders()
2958 {
2959 /**
2960 * A hash of headers, with header field names as the keys and header field
2961 * values as the values. Header field names are case-insensitive, but upon
2962 * insertion here they are converted to lowercase. Header field values are
2963 * normalized upon insertion to contain no leading or trailing whitespace.
2964 *
2965 * Note also that per RFC 2616, section 4.2, two headers with the same name in
2966 * a message may be treated as one header with the same field name and a field
2967 * value consisting of the separate field values joined together with a "," in
2968 * their original order. This hash stores multiple headers with the same name
2969 * in this manner.
2970 */
2971 this._headers = {};
2972 }
2973 nsHttpHeaders.prototype =
2974 {
2975 /**
2976 * Sets the header represented by name and value in this.
2977 *
2978 * @param name : string
2979 * the header name
2980 * @param value : string
2981 * the header value
2982 * @throws NS_ERROR_INVALID_ARG
2983 * if name or value is not a valid header component
2984 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
2985 setHeader: function(fieldName, fieldValue, merge)
2986 {
2987 var name = headerUtils.normalizeFieldName(fieldName);
2988 var value = headerUtils.normalizeFieldValue(fieldValue);
2989
2990 if (merge && name in this._headers)
2991 this._headers[name] = this._headers[name] + "," + value;
2992 else
2993 this._headers[name] = value;
2994 },
2995
2996 /**
2997 * Returns the value for the header specified by this.
2998 *
2999 * @throws NS_ERROR_INVALID_ARG
3000 * if fieldName does not constitute a valid header field name
3001 * @throws NS_ERROR_NOT_AVAILABLE
3002 * if the given header does not exist in this
3003 * @returns string
3004 * the field value for the given header, possibly with non-semantic changes
3005 * (i.e., leading/trailing whitespace stripped, whitespace runs replaced
3006 * with spaces, etc.) at the option of the implementation
3007 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3008 getHeader: function(fieldName)
3009 {
3010 var name = headerUtils.normalizeFieldName(fieldName);
3011
3012 if (name in this._headers)
3013 return this._headers[name];
3014 else
3015 throw Cr.NS_ERROR_NOT_AVAILABLE;
3016 },
3017
3018 /**
3019 * Returns true if a header with the given field name exists in this, false
3020 * otherwise.
3021 *
3022 * @param fieldName : string
3023 * the field name whose existence is to be determined in this
3024 * @throws NS_ERROR_INVALID_ARG
3025 * if fieldName does not constitute a valid header field name
3026 * @returns boolean
3027 * true if the header's present, false otherwise
3028 */
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3029 hasHeader: function(fieldName)
3030 {
3031 var name = headerUtils.normalizeFieldName(fieldName);
3032 return (name in this._headers);
3033 },
3034
3035 /**
3036 * Returns a new enumerator over the field names of the headers in this, as
3037 * nsISupportsStrings. The names returned will be in lowercase, regardless of
3038 * how they were input using setHeader (header names are case-insensitive per
3039 * RFC 2616).
3040 */
get_enumerator
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3041 get enumerator()
3042 {
3043 var headers = [];
3044 for (var i in this._headers)
3045 {
3046 var supports = new SupportsString();
3047 supports.data = i;
3048 headers.push(supports);
3049 }
3050
3051 return new nsSimpleEnumerator(headers);
3052 }
3053 };
3054
3055
3056 /**
3057 * Constructs an nsISimpleEnumerator for the given array of items.
3058 *
3059 * @param items : Array
3060 * the items, which must all implement nsISupports
3061 */
nsSimpleEnumerator
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3062 function nsSimpleEnumerator(items)
3063 {
3064 this._items = items;
3065 this._nextIndex = 0;
3066 }
3067 nsSimpleEnumerator.prototype =
3068 {
hasMoreElements
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3069 hasMoreElements: function()
3070 {
3071 return this._nextIndex < this._items.length;
3072 },
getNext
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3073 getNext: function()
3074 {
3075 if (!this.hasMoreElements())
3076 throw Cr.NS_ERROR_NOT_AVAILABLE;
3077
3078 return this._items[this._nextIndex++];
3079 },
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3080 QueryInterface: function(aIID)
3081 {
3082 if (Ci.nsISimpleEnumerator.equals(aIID) ||
3083 Ci.nsISupports.equals(aIID))
3084 return this;
3085
3086 throw Cr.NS_ERROR_NO_INTERFACE;
3087 }
3088 };
3089
3090
3091 /**
3092 * A representation of the data in an HTTP request.
3093 *
3094 * @param port : uint
3095 * the port on which the server receiving this request runs
3096 */
Request
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3097 function Request(port)
3098 {
3099 this._method = "";
3100 this._path = "";
3101 this._queryString = "";
3102 this._host = "";
3103 this._port = port;
3104 this._host = "localhost"; // XXX or from environment or server itself?
3105
3106 /**
3107 * The headers in this request.
3108 */
3109 this._headers = new nsHttpHeaders();
3110
3111 /**
3112 * For the addition of ad-hoc properties and new functionality without having
3113 * to change nsIHttpRequestMetadata every time; currently lazily created,
3114 * as its only use is in directory listings.
3115 */
3116 this._bag = null;
3117 }
3118 Request.prototype =
3119 {
3120 // SERVER METADATA
3121
3122 //
3123 // see nsIHttpRequestMetadata.host
3124 //
get_host
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3125 get host()
3126 {
3127 return this._host;
3128 },
3129
3130 //
3131 // see nsIHttpRequestMetadata.port
3132 //
get_port
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3133 get port()
3134 {
3135 return this._port;
3136 },
3137
3138 // REQUEST LINE
3139
3140 //
3141 // see nsIHttpRequestMetadata.method
3142 //
get_method
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3143 get method()
3144 {
3145 return this._method;
3146 },
3147
3148 //
3149 // see nsIHttpRequestMetadata.httpVersion
3150 //
get_httpVersion
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3151 get httpVersion()
3152 {
3153 return this._httpVersion.toString();
3154 },
3155
3156 //
3157 // see nsIHttpRequestMetadata.path
3158 //
get_path
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3159 get path()
3160 {
3161 return this._path;
3162 },
3163
3164 //
3165 // see nsIHttpRequestMetadata.queryString
3166 //
get_queryString
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3167 get queryString()
3168 {
3169 return this._queryString;
3170 },
3171
3172 // HEADERS
3173
3174 //
3175 // see nsIHttpRequestMetadata.getHeader
3176 //
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3177 getHeader: function(name)
3178 {
3179 return this._headers.getHeader(name);
3180 },
3181
3182 //
3183 // see nsIHttpRequestMetadata.hasHeader
3184 //
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3185 hasHeader: function(name)
3186 {
3187 return this._headers.hasHeader(name);
3188 },
3189
3190 //
3191 // see nsIHttpRequestMetadata.headers
3192 //
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3193 get headers()
3194 {
3195 return this._headers.enumerator;
3196 },
3197
3198 //
3199 // see nsIPropertyBag.enumerator
3200 //
get_enumerator
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3201 get enumerator()
3202 {
3203 this._ensurePropertyBag();
3204 return this._bag.enumerator;
3205 },
3206
3207 //
3208 // see nsIPropertyBag.getProperty
3209 //
getProperty
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3210 getProperty: function(name)
3211 {
3212 this._ensurePropertyBag();
3213 return this._bag.getProperty(name);
3214 },
3215
3216 /** Ensures a property bag has been created for ad-hoc behaviors. */
_ensurePropertyBag
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3217 _ensurePropertyBag: function()
3218 {
3219 if (!this._bag)
3220 this._bag = new WritablePropertyBag();
3221 }
3222 };
3223
3224
3225 // XPCOM trappings
3226
3227 /**
3228 * Creates a factory for instances of an object created using the passed-in
3229 * constructor.
3230 */
makeFactory
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3231 function makeFactory(ctor)
3232 {
ci
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3233 function ci(outer, iid)
3234 {
3235 if (outer != null)
3236 throw Components.results.NS_ERROR_NO_AGGREGATION;
3237 return (new ctor()).QueryInterface(iid);
3238 }
3239
3240 return {
3241 createInstance: ci,
lockFactory
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3242 lockFactory: function(lock) { },
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3243 QueryInterface: function(aIID)
3244 {
3245 if (Ci.nsIFactory.equals(aIID) ||
3246 Ci.nsISupports.equals(aIID))
3247 return this;
3248 throw Cr.NS_ERROR_NO_INTERFACE;
3249 }
3250 };
3251 }
3252
3253 /** The XPCOM module containing the HTTP server. */
3254 const module =
3255 {
3256 // nsISupports
QueryInterface
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3257 QueryInterface: function(aIID)
3258 {
3259 if (Ci.nsIModule.equals(aIID) ||
3260 Ci.nsISupports.equals(aIID))
3261 return this;
3262 throw Cr.NS_ERROR_NO_INTERFACE;
3263 },
3264
3265 // nsIModule
registerSelf
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3266 registerSelf: function(compMgr, fileSpec, location, type)
3267 {
3268 compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
3269
3270 for (var key in this._objects)
3271 {
3272 var obj = this._objects[key];
3273 compMgr.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
3274 fileSpec, location, type);
3275 }
3276 },
unregisterSelf
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3277 unregisterSelf: function (compMgr, location, type)
3278 {
3279 compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
3280
3281 for (var key in this._objects)
3282 {
3283 var obj = this._objects[key];
3284 compMgr.unregisterFactoryLocation(obj.CID, location);
3285 }
3286 },
getClassObject
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3287 getClassObject: function(compMgr, cid, iid)
3288 {
3289 if (!iid.equals(Ci.nsIFactory))
3290 throw Cr.NS_ERROR_NOT_IMPLEMENTED;
3291
3292 for (var key in this._objects)
3293 {
3294 if (cid.equals(this._objects[key].CID))
3295 return this._objects[key].factory;
3296 }
3297
3298 throw Cr.NS_ERROR_NO_INTERFACE;
3299 },
canUnload
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3300 canUnload: function(compMgr)
3301 {
3302 return true;
3303 },
3304
3305 // private implementation
3306 _objects:
3307 {
3308 server:
3309 {
3310 CID: Components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"),
3311 contractID: "@mozilla.org/server/jshttp;1",
3312 className: "MozJSHTTP server",
3313 factory: makeFactory(nsHttpServer)
3314 }
3315 }
3316 };
3317
3318
3319 /** NSGetModule, so this code can be used as a JS component. */
NSGetModule
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3320 function NSGetModule(compMgr, fileSpec)
3321 {
3322 return module;
3323 }
3324
3325
3326 /**
3327 * Creates a new HTTP server listening for loopback traffic on the given port,
3328 * starts it, and runs the server until the server processes a shutdown request,
3329 * spinning an event loop so that events posted by the server's socket are
3330 * processed.
3331 *
3332 * This method is primarily intended for use in running this script from within
3333 * xpcshell and running a functional HTTP server without having to deal with
3334 * non-essential details.
3335 *
3336 * Note that running multiple servers using variants of this method probably
3337 * doesn't work, simply due to how the internal event loop is spun and stopped.
3338 *
3339 * @note
3340 * This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code);
3341 * you should use this server as a component in Mozilla 1.8.
3342 * @param port
3343 * the port on which the server will run, or -1 if there exists no preference
3344 * for a specific port; note that attempting to use some values for this
3345 * parameter (particularly those below 1024) may cause this method to throw or
3346 * may result in the server being prematurely shut down
3347 * @param basePath
3348 * a local directory from which requests will be served (i.e., if this is
3349 * "/home/jwalden/" then a request to /index.html will load
3350 * /home/jwalden/index.html); if this is omitted, only the default URLs in
3351 * this server implementation will be functional
3352 */
server
(0 calls, 0 incl. v-uS, 0 excl. v-uS)
3353 function server(port, basePath)
3354 {
3355 if (basePath)
3356 {
3357 var lp = Cc["@mozilla.org/file/local;1"]
3358 .createInstance(Ci.nsILocalFile);
3359 lp.initWithPath(basePath);
3360 }
3361
3362 // if you're running this, you probably want to see debugging info
3363 DEBUG = true;
3364
3365 var srv = new nsHttpServer();
3366 if (lp)
3367 srv.registerDirectory("/", lp);
3368 srv.registerContentType("sjs", SJS_TYPE);
3369 srv.start(port);
3370
3371 var thread = gThreadManager.currentThread;
3372 while (!srv.isStopped())
3373 thread.processNextEvent(true);
3374
3375 // get rid of any pending requests
3376 while (thread.hasPendingEvents())
3377 thread.processNextEvent(true);
3378
3379 DEBUG = false;
3380 }