summaryrefslogtreecommitdiff
path: root/dom/base/test/file_bug1250148.sjs
blob: a85347896bc36d6ce151e66a243d57963da85118 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
                             "nsIBinaryInputStream",
                             "setInputStream");

function utf8decode(s) {
  return decodeURIComponent(escape(s));
}

function utf8encode(s) {
  return unescape(encodeURIComponent(s));
}

function handleRequest(request, response) {
  var bodyStream = new BinaryInputStream(request.bodyInputStream);

  var requestBody = "";
  while ((bodyAvail = bodyStream.available()) > 0) {
    requestBody += bodyStream.readBytes(bodyAvail);
  }

  var result = [];

  if (request.method == "POST") {
    var contentTypeParams = {};
    request.getHeader("Content-Type").split(/\s*\;\s*/).forEach(function(s) {
      if (s.indexOf('=') >= 0) {
        let [name, value] = s.split('=');
        contentTypeParams[name] = value;
      }
      else {
        contentTypeParams[''] = s;
      }
    });
    
    if (contentTypeParams[''] == "multipart/form-data" &&
        request.queryString == "") {
      requestBody.split("--" + contentTypeParams.boundary).slice(1, -1).forEach(function (s) {

        let headers = {};
        let headerEnd = s.indexOf("\r\n\r\n");
        s.substr(2, headerEnd-2).split("\r\n").forEach(function(s) {
          // We're assuming UTF8 for now
          let [name, value] = s.split(': ');
          headers[name] = utf8decode(value);
        });

        let body = s.substring(headerEnd + 4, s.length - 2);
        if (!headers["Content-Type"] || headers["Content-Type"] == "text/plain") {
          // We're assuming UTF8 for now
          body = utf8decode(body);
        }
        result.push({ headers: headers, body: body});
      });
    }
  }

  response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
  response.write(utf8encode(JSON.stringify(result)));
}