form_submit_server.sjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const CC = Components.Constructor;
  2. const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
  3. "nsIBinaryInputStream",
  4. "setInputStream");
  5. function utf8decode(s) {
  6. return decodeURIComponent(escape(s));
  7. }
  8. function utf8encode(s) {
  9. return unescape(encodeURIComponent(s));
  10. }
  11. function handleRequest(request, response)
  12. {
  13. var bodyStream = new BinaryInputStream(request.bodyInputStream);
  14. var result = [];
  15. var requestBody = "";
  16. while ((bodyAvail = bodyStream.available()) > 0)
  17. requestBody += bodyStream.readBytes(bodyAvail);
  18. if (request.method == "POST") {
  19. var contentTypeParams = {};
  20. request.getHeader("Content-Type").split(/\s*\;\s*/).forEach(function(s) {
  21. if (s.indexOf('=') >= 0) {
  22. let [name, value] = s.split('=');
  23. contentTypeParams[name] = value;
  24. }
  25. else {
  26. contentTypeParams[''] = s;
  27. }
  28. });
  29. if (contentTypeParams[''] == "multipart/form-data" &&
  30. request.queryString == "") {
  31. requestBody.split("--" + contentTypeParams.boundary).slice(1, -1).forEach(function (s) {
  32. let headers = {};
  33. let headerEnd = s.indexOf("\r\n\r\n");
  34. s.substr(2, headerEnd-2).split("\r\n").forEach(function(s) {
  35. // We're assuming UTF8 for now
  36. let [name, value] = s.split(': ');
  37. headers[name] = utf8decode(value);
  38. });
  39. let body = s.substring(headerEnd + 4, s.length - 2);
  40. if (!headers["Content-Type"] || headers["Content-Type"] == "text/plain") {
  41. // We're assuming UTF8 for now
  42. body = utf8decode(body);
  43. }
  44. result.push({ headers: headers, body: body});
  45. });
  46. }
  47. if (contentTypeParams[''] == "text/plain" &&
  48. request.queryString == "plain") {
  49. result = utf8decode(requestBody);
  50. }
  51. if (contentTypeParams[''] == "application/x-www-form-urlencoded" &&
  52. request.queryString == "url") {
  53. result = requestBody;
  54. }
  55. }
  56. else if (request.method == "GET") {
  57. result = request.queryString;
  58. }
  59. // Send response body
  60. response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
  61. response.write(utf8encode(JSON.stringify(result)));
  62. }