Bug 1929458 - support setting OS version to use in failure annotations generated...
[gecko.git] / dom / html / test / form_submit_server.sjs
blob553809c01ffc1c3d1e323b3e6ac555312446ac25
1 const CC = Components.Constructor;
2 const BinaryInputStream = CC(
3   "@mozilla.org/binaryinputstream;1",
4   "nsIBinaryInputStream",
5   "setInputStream"
6 );
8 function utf8decode(s) {
9   return decodeURIComponent(escape(s));
12 function utf8encode(s) {
13   return unescape(encodeURIComponent(s));
16 function handleRequest(request, response) {
17   var bodyStream = new BinaryInputStream(request.bodyInputStream);
18   var result = [];
19   var requestBody = "";
20   while ((bodyAvail = bodyStream.available()) > 0) {
21     requestBody += bodyStream.readBytes(bodyAvail);
22   }
24   if (request.method == "POST") {
25     var contentTypeParams = {};
26     request
27       .getHeader("Content-Type")
28       .split(/\s*\;\s*/)
29       .forEach(function (s) {
30         if (s.indexOf("=") >= 0) {
31           let [name, value] = s.split("=");
32           contentTypeParams[name] = value;
33         } else {
34           contentTypeParams[""] = s;
35         }
36       });
38     if (
39       contentTypeParams[""] == "multipart/form-data" &&
40       request.queryString == ""
41     ) {
42       requestBody
43         .split("--" + contentTypeParams.boundary)
44         .slice(1, -1)
45         .forEach(function (s) {
46           let headers = {};
47           let headerEnd = s.indexOf("\r\n\r\n");
48           s.substr(2, headerEnd - 2)
49             .split("\r\n")
50             .forEach(function (str) {
51               // We're assuming UTF8 for now
52               let [name, value] = str.split(": ");
53               headers[name] = utf8decode(value);
54             });
56           let body = s.substring(headerEnd + 4, s.length - 2);
57           if (
58             !headers["Content-Type"] ||
59             headers["Content-Type"] == "text/plain"
60           ) {
61             // We're assuming UTF8 for now
62             body = utf8decode(body);
63           }
64           result.push({ headers, body });
65         });
66     }
67     if (
68       contentTypeParams[""] == "text/plain" &&
69       request.queryString == "plain"
70     ) {
71       result = utf8decode(requestBody);
72     }
73     if (
74       contentTypeParams[""] == "application/x-www-form-urlencoded" &&
75       request.queryString == "url"
76     ) {
77       result = requestBody;
78     }
79   } else if (request.method == "GET") {
80     result = request.queryString;
81   }
83   // Send response body
84   response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
85   response.write(utf8encode(JSON.stringify(result)));