Bug 443610 - Add body and PUT handling to httpd.js; "PUT" part; r=sayrer

This commit is contained in:
Honza Bambas 2008-09-07 17:18:06 +02:00
Родитель 741c241c5f
Коммит 7f0abab8dd
2 изменённых файлов: 290 добавлений и 10 удалений

Просмотреть файл

@ -988,6 +988,8 @@ function RequestReader(connection)
*/
this._data = new LineData();
this._contentLength = 0;
/** The current state of parsing the incoming request. */
this._state = READER_INITIAL;
@ -1041,14 +1043,13 @@ RequestReader.prototype =
moreAvailable = this._processHeaders(input, count);
break;
case READER_IN_BODY:
// XXX handle the request body! until then, just stop reading
break;
default:
NS_ASSERT(false);
}
if (this._state == READER_IN_BODY && moreAvailable)
moreAvailable = this._processBody(input, count);
if (moreAvailable)
input.asyncWait(this, 0, 0, gThreadManager.currentThread);
},
@ -1107,6 +1108,10 @@ RequestReader.prototype =
if (!this._parseHeaders())
return true;
dumpn("_processRequestLine, Content-length="+this._contentLength);
if (this._contentLength > 0)
return true;
// headers complete, do a data check and then forward to the handler
this._validateRequest();
return this._handleResponse();
@ -1145,6 +1150,10 @@ RequestReader.prototype =
if (!this._parseHeaders())
return true;
dumpn("_processHeaders, Content-length="+this._contentLength);
if (this._contentLength > 0)
return true;
// we have all the headers, continue with the body
this._validateRequest();
return this._handleResponse();
@ -1156,6 +1165,42 @@ RequestReader.prototype =
}
},
_processBody: function(input, count)
{
NS_ASSERT(this._state == READER_IN_BODY);
try
{
if (this._contentLength > 0)
{
var bodyData = this._data.purge();
if (bodyData.length == 0)
{
if (count > this._contentLength)
count = this._contentLength;
bodyData = readBytes(input, count);
}
dumpn("*** loading data="+bodyData+" len="+bodyData.length);
this._metadata._body.appendBytes(bodyData);
this._contentLength -= bodyData.length;
}
dumpn("*** remainig body data len="+this._contentLength);
if (this._contentLength > 0)
return true;
this._validateRequest();
return this._handleResponse();
}
catch (e)
{
this._handleError(e);
return false;
}
},
/**
* Does various post-header checks on the data in this request.
*
@ -1279,7 +1324,7 @@ RequestReader.prototype =
* the request to be handled.
*
* This method is called once per request, after the request line and all
* headers have been received.
* headers and the body, if any, have been received.
*
* @returns boolean
* true if more data must be read, false otherwise
@ -1288,8 +1333,6 @@ RequestReader.prototype =
{
NS_ASSERT(this._state == READER_IN_BODY);
// XXX set up a stream for data in the request body here
// We don't need the line-based data any more, so make attempted reuse an
// error.
this._data = null;
@ -1469,6 +1512,12 @@ RequestReader.prototype =
// either way, we're done processing headers
this._state = READER_IN_BODY;
try
{
this._contentLength = parseInt(headers.getHeader("Content-Length"));
dumpn("Content-Length="+this._contentLength);
}
catch (e) {}
return true;
}
else if (firstChar == " " || firstChar == "\t")
@ -1870,6 +1919,11 @@ function ServerHandler(server)
*/
this._overridePaths = {};
/**
* Put data overrides, privileged before _overridePaths.
*/
this._putDataOverrides = {};
/**
* Custom request handlers for the error handlers in the server in which this
* resides. Path-handler pairs are stored as property-value pairs in this
@ -1916,11 +1970,56 @@ ServerHandler.prototype =
try
{
try
{
if (metadata.method == "PUT")
{
// remotely set path override
var data = metadata.body.purge();
data = String.fromCharCode.apply(null, data.splice(0, data.length + 2));
var contentType;
try
{
contentType = metadata.getHeader("Content-Type");
}
catch (ex)
{
contentType = "application/octet-stream";
}
if (data.length)
{
dumpn("PUT data \'"+data+"\' for "+path);
this._putDataOverrides[path] =
function(ametadata, aresponse)
{
aresponse.setStatusLine(metadata.httpVersion, 200, "OK");
aresponse.setHeader("Content-Type", contentType, false);
dumpn("*** writting PUT data=\'"+data+"\'");
aresponse.bodyOutputStream.write(data, data.length);
};
}
else
{
delete this._putDataOverrides[path];
dumpn("clearing PUT data for "+path);
}
response.setStatusLine(metadata.httpVersion, 200, "OK");
}
else if (path in this._putDataOverrides)
{
// PUT data overrides are priviledged before all
// other overrides.
dumpn("calling PUT data override for "+path);
this._putDataOverrides[path](metadata, response);
}
else if (path in this._overridePaths)
{
// explicit paths first, then files based on existing directory mappings,
// then (if the file doesn't exist) built-in server default paths
if (path in this._overridePaths)
dumpn("calling override for "+path);
this._overridePaths[path](metadata, response);
}
else
this._handleDefault(metadata, response);
}
@ -3484,6 +3583,9 @@ function Request(port)
/** Port number over which the request was received. */
this._port = port;
/** Body data of the request */
this._body = new LineData();
/**
* The headers in this request.
*/
@ -3607,6 +3709,11 @@ Request.prototype =
{
if (!this._bag)
this._bag = new WritablePropertyBag();
},
get body()
{
return this._body;
}
};

Просмотреть файл

@ -0,0 +1,173 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is MozJSHTTP code.
*
* The Initial Developer of the Original Code is
* Jeff Walden <jwalden+code@mit.edu>.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// Make sure setIndexHandler works as expected
var paths =
[
"http://localhost:4444/my/first-path/override/",
"http://localhost:4444/my/second-path/override",
"http://localhost:4444/my/second-path/override"
];
var contents =
[
"First content",
"Second content",
"" // null means delete of the PUT data
];
var contents =
[
"First content",
"Second content",
""
];
var success =
[
true, true, false
];
var currPathIndex = 0;
var uploadListener =
{
// NSISTREAMLISTENER
onDataAvailable: function(request, cx, inputStream, offset, count)
{
makeBIS(inputStream).readByteArray(count); // required by API
},
// NSIREQUESTOBSERVER
onStartRequest: function(request, cx)
{
},
onStopRequest: function(request, cx, status)
{
do_check_true(Components.isSuccessCode(status));
var ch = makeChannel(paths[currPathIndex]);
ch.asyncOpen(downloadListener, null);
},
// NSISUPPORTS
QueryInterface: function(aIID)
{
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsIRequestObserver) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
var downloadListener =
{
// NSISTREAMLISTENER
onDataAvailable: function(request, cx, inputStream, offset, count)
{
var content = makeBIS(inputStream).readByteArray(count); // required by API
if (success[currPathIndex])
{
for (var i=0; i<count; ++i)
do_check_eq(contents[currPathIndex].charCodeAt(i), content[i])
}
},
// NSIREQUESTOBSERVER
onStartRequest: function(request, cx)
{
if (success[currPathIndex])
{
// expected success, check we get the correct content-type
var ch = request.QueryInterface(Ci.nsIHttpChannel)
.QueryInterface(Ci.nsIHttpChannelInternal);
do_check_eq(ch.getResponseHeader("Content-Type"), "application/x-moz-put-test");
}
},
onStopRequest: function(request, cx, status)
{
do_check_true(Components.isSuccessCode(status));
var ch = request.QueryInterface(Ci.nsIHttpChannel)
.QueryInterface(Ci.nsIHttpChannelInternal);
do_check_true(ch.requestSucceeded == success[currPathIndex]);
if (++currPathIndex == paths.length)
srv.stop();
else
performNextTest();
do_test_finished();
},
// NSISUPPORTS
QueryInterface: function(aIID)
{
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsIRequestObserver) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
function performNextTest()
{
do_test_pending();
var ch = makeChannel(paths[currPathIndex]);
var stream = Cc["@mozilla.org/io/string-input-stream;1"]
.createInstance(Ci.nsIStringInputStream);
stream.setData(contents[currPathIndex], contents[currPathIndex].length);
var upch = ch.QueryInterface(Ci.nsIUploadChannel);
upch.setUploadStream(stream, "application/x-moz-put-test", stream.available());
ch.asyncOpen(uploadListener, null);
}
var srv, serverBasePath;
function run_test()
{
srv = createServer();
srv.start(4444);
performNextTest();
}