summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/accountcreation/FetchHTTP.jsm
blob: 54b3629906a551be817909fde782a2a90a880976 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * This is a small wrapper around XMLHttpRequest, which solves various
 * inadequacies of the API, e.g. error handling. It is entirely generic and
 * can be used for purposes outside of even mail.
 *
 * It does not provide download progress, but assumes that the
 * fetched resource is so small (<1 10 KB) that the roundtrip and
 * response generation is far more significant than the
 * download time of the response. In other words, it's fine for RPC,
 * but not for bigger file downloads.
 */

const EXPORTED_SYMBOLS = ["FetchHTTP"];

const { AccountCreationUtils } = ChromeUtils.import(
  "resource:///modules/accountcreation/AccountCreationUtils.jsm"
);
const lazy = {};
ChromeUtils.defineModuleGetter(
  lazy,
  "Sanitizer",
  "resource:///modules/accountcreation/Sanitizer.jsm"
);

const { JXON } = ChromeUtils.import("resource:///modules/JXON.jsm");

const {
  Abortable,
  alertPrompt,
  assert,
  ddump,
  Exception,
  gAccountSetupLogger,
  getStringBundle,
  UserCancelledException,
} = AccountCreationUtils;

/**
 * Set up a fetch.
 *
 * @param {string} url - URL of the server function.
 *    ATTENTION: The caller needs to make sure that the URL is secure to call.
 * @param {object} args - Additional parameters as properties, see below
 *
 * @param {Function({string} result)} successCallback
 *   Called when the server call worked (no errors).
 *   |result| will contain the body of the HTTP response, as string.
 * @param {Function(ex)} errorCallback
 *   Called in case of error. ex contains the error
 *   with a user-displayable but not localized |.message| and maybe a
 *   |.code|, which can be either
 *  - an nsresult error code,
 *  - an HTTP result error code (0...1000) or
 *  - negative: 0...-100 :
 *     -2 = can't resolve server in DNS etc.
 *     -4 = response body (e.g. XML) malformed
 *
 * The following optional parameters are supported as properties of the |args| object:
 *
 * @param {Object, associative array} urlArgs - Parameters to add
 *   to the end of the URL as query string. E.g.
 *   { foo: "bla", bar: "blub blub" } will add "?foo=bla&bar=blub%20blub"
 *   to the URL
 *   (unless the URL already has a "?", then it adds "&foo...").
 *   The values will be urlComponentEncoded, so pass them unencoded.
 * @param {Object, associative array} headers - HTTP headers to be added
 *   to the HTTP request.
 *   { foo: "blub blub" } will add HTTP header "Foo: Blub blub".
 *   The values will be passed verbatim.
 * @param {boolean} post - HTTP GET or POST
 *   Only influences the HTTP request method,
 *   i.e. first line of the HTTP request, not the body or parameters.
 *   Use POST when you modify server state,
 *   GET when you only request information.
 *   Default is GET.
 * @param {Object, associative array} bodyFormArgs - Like urlArgs,
 *   just that the params will be sent x-url-encoded in the body,
 *   like a HTML form post.
 *   The values will be urlComponentEncoded, so pass them unencoded.
 *   This cannot be used together with |uploadBody|.
 * @param {object} uploadBody - Arbitrary object, which to use as
 *   body of the HTTP request. Will also set the mimetype accordingly.
 *   Only supported object types, currently only JXON is supported
 *   (sending XML).
 *   Usually, you have nothing to upload, so just pass |null|.
 *   Only supported object types, currently supported:
 *   JXON -> sending XML
 *   JS object -> sending JSON
 *   string -> sending text/plain
 *   If you want to override the body mimetype, set header Content-Type below.
 *   Usually, you have nothing to upload, so just leave it at |null|.
 *   Default |null|.
 * @param {boolean} allowCache (default true)
 * @param {string} username (default null = no authentication)
 * @param {string} password (default null = no authentication)
 * @param {boolean} allowAuthPrompt (default true)
 * @param {boolean} requireSecureAuth (default false)
 *   Ignore the username and password unless we are using https:
 *   This also applies to both https: to http: and http: to https: redirects.
 */
function FetchHTTP(url, args, successCallback, errorCallback) {
  assert(typeof successCallback == "function", "BUG: successCallback");
  assert(typeof errorCallback == "function", "BUG: errorCallback");
  this._url = lazy.Sanitizer.string(url);
  if (!args) {
    args = {};
  }
  if (!args.urlArgs) {
    args.urlArgs = {};
  }
  if (!args.headers) {
    args.headers = {};
  }

  this._args = args;
  this._args.post = lazy.Sanitizer.boolean(args.post || false); // default false
  this._args.allowCache =
    "allowCache" in args ? lazy.Sanitizer.boolean(args.allowCache) : true; // default true
  this._args.allowAuthPrompt = lazy.Sanitizer.boolean(
    args.allowAuthPrompt || false
  ); // default false
  this._args.requireSecureAuth = lazy.Sanitizer.boolean(
    args.requireSecureAuth || false
  ); // default false
  this._args.timeout = lazy.Sanitizer.integer(args.timeout || 5000); // default 5 seconds
  this._successCallback = successCallback;
  this._errorCallback = errorCallback;
  this._logger = gAccountSetupLogger;
  this._logger.info("Requesting <" + url + ">");
}
FetchHTTP.prototype = {
  __proto__: Abortable.prototype,
  _url: null, // URL as passed to ctor, without arguments
  _args: null,
  _successCallback: null,
  _errorCallback: null,
  _request: null, // the XMLHttpRequest object
  result: null,

  start() {
    let url = this._url;
    for (let name in this._args.urlArgs) {
      url +=
        (!url.includes("?") ? "?" : "&") +
        name +
        "=" +
        encodeURIComponent(this._args.urlArgs[name]);
    }
    this._request = new XMLHttpRequest();
    let request = this._request;
    request.mozBackgroundRequest = !this._args.allowAuthPrompt;
    let username = null,
      password = null;
    if (url.startsWith("https:") || !this._args.requireSecureAuth) {
      username = this._args.username;
      password = this._args.password;
    }
    request.open(
      this._args.post ? "POST" : "GET",
      url,
      true,
      username,
      password
    );
    request.channel.loadGroup = null;
    request.timeout = this._args.timeout;
    // needs bug 407190 patch v4 (or higher) - uncomment if that lands.
    // try {
    //    var channel = request.channel.QueryInterface(Ci.nsIHttpChannel2);
    //    channel.connectTimeout = 5;
    //    channel.requestTimeout = 5;
    //    } catch (e) { dump(e + "\n"); }

    if (!this._args.allowCache) {
      // Disable Mozilla HTTP cache
      request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
    }

    // body
    let mimetype = null;
    let body = this._args.uploadBody;
    if (typeof body == "object" && "nodeType" in body) {
      // XML
      mimetype = "text/xml; charset=UTF-8";
      body = new XMLSerializer().serializeToString(body);
    } else if (typeof body == "object") {
      // JSON
      mimetype = "text/json; charset=UTF-8";
      body = JSON.stringify(body);
    } else if (typeof body == "string") {
      // Plaintext
      // You can override the mimetype with { headers: {"Content-Type" : "text/foo" } }
      mimetype = "text/plain; charset=UTF-8";
      // body already set above
    } else if (this._args.bodyFormArgs) {
      mimetype = "application/x-www-form-urlencoded; charset=UTF-8";
      body = "";
      for (let name in this._args.bodyFormArgs) {
        body +=
          (body ? "&" : "") +
          name +
          "=" +
          encodeURIComponent(this._args.bodyFormArgs[name]);
      }
    }

    // Headers
    if (mimetype && !("Content-Type" in this._args.headers)) {
      request.setRequestHeader("Content-Type", mimetype);
    }
    if (username && password) {
      // workaround, because open(..., username, password) does not work.
      request.setRequestHeader(
        "Authorization",
        "Basic " +
          btoa(
            // btoa() takes a BinaryString.
            String.fromCharCode(
              ...new TextEncoder().encode(username + ":" + password)
            )
          )
      );
    }
    for (let name in this._args.headers) {
      request.setRequestHeader(name, this._args.headers[name]);
      if (name == "Cookie") {
        // Websites are not allowed to set this, but chrome is.
        // Nevertheless, the cookie lib later overwrites our header.
        // request.channel.setCookie(this._args.headers[name]); -- crashes
        // So, deactivate that Firefox cookie lib.
        request.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS;
      }
    }

    var me = this;
    request.onload = function () {
      me._response(true);
    };
    request.onerror = function () {
      me._response(false);
    };
    request.ontimeout = function () {
      me._response(false);
    };
    request.send(body);
    // Store the original stack so we can use it if there is an exception
    this._callStack = Error().stack;
  },
  _response(success, exStored) {
    try {
      var errorCode = null;
      var errorStr = null;

      if (
        success &&
        this._request.status >= 200 &&
        this._request.status < 300
      ) {
        // HTTP level success
        try {
          // response
          var mimetype = this._request.getResponseHeader("Content-Type");
          if (!mimetype) {
            mimetype = "";
          }
          mimetype = mimetype.split(";")[0];
          if (
            mimetype == "text/xml" ||
            mimetype == "application/xml" ||
            mimetype == "text/rdf"
          ) {
            // XML
            this.result = JXON.build(this._request.responseXML);
          } else if (
            mimetype == "text/json" ||
            mimetype == "application/json"
          ) {
            // JSON
            this.result = JSON.parse(this._request.responseText);
          } else {
            // Plaintext (fallback)
            // ddump("mimetype: " + mimetype + " only supported as text");
            this.result = this._request.responseText;
          }
        } catch (e) {
          success = false;
          errorStr = getStringBundle(
            "chrome://messenger/locale/accountCreationUtil.properties"
          ).GetStringFromName("bad_response_content.error");
          errorCode = -4;
        }
      } else if (
        this._args.username &&
        this._request.responseURL.replace(/\/\/.*@/, "//") != this._url &&
        this._request.responseURL.startsWith(
          this._args.requireSecureAuth ? "https" : "http"
        ) &&
        !this._isRetry
      ) {
        // Redirects lack auth, see <https://stackoverflow.com/a/28411170>
        this._logger.info(
          "Call to <" +
            this._url +
            "> was redirected to <" +
            this._request.responseURL +
            ">, and failed. Re-trying the new URL with authentication again."
        );
        this._url = this._request.responseURL;
        this._isRetry = true;
        this.start();
        return;
      } else {
        success = false;
        try {
          errorCode = this._request.status;
          errorStr = this._request.statusText;
        } catch (e) {
          // In case .statusText throws (it's marked as [Throws] in the webidl),
          // continue with empty errorStr.
        }
        if (!errorStr) {
          // If we can't resolve the hostname in DNS etc., .statusText is empty.
          errorCode = -2;
          errorStr = getStringBundle(
            "chrome://messenger/locale/accountCreationUtil.properties"
          ).GetStringFromName("cannot_contact_server.error");
          ddump(errorStr + " on <" + this._url + ">");
        }
      }

      // Callbacks
      if (success) {
        try {
          this._successCallback(this.result);
        } catch (e) {
          e.stack = this._callStack;
          this._error(e);
        }
      } else if (exStored) {
        this._error(exStored);
      } else {
        // Put the caller's stack into the exception
        let e = new ServerException(errorStr, errorCode, this._url);
        e.stack = this._callStack;
        this._error(e);
      }

      if (this._finishedCallback) {
        try {
          this._finishedCallback(this);
        } catch (e) {
          console.error(e);
        }
      }
    } catch (e) {
      // error in our fetchhttp._response() code
      this._error(e);
    }
  },
  _error(e) {
    try {
      this._errorCallback(e);
    } catch (e) {
      // error in errorCallback, too!
      console.error(e);
      alertPrompt("Error in errorCallback for fetchhttp", e);
    }
  },
  /**
   * Call this between start() and finishedCallback fired.
   */
  cancel(ex) {
    assert(!this.result, "Call already returned");

    this._request.abort();

    // Need to manually call error handler
    // <https://bugzilla.mozilla.org/show_bug.cgi?id=218236#c11>
    this._response(false, ex ? ex : new UserCancelledException());
  },
  /**
   * Allows caller or lib to be notified when the call is done.
   * This is useful to enable and disable a Cancel button in the UI,
   * which allows to cancel the network request.
   */
  setFinishedCallback(finishedCallback) {
    this._finishedCallback = finishedCallback;
  },
};

function ServerException(msg, code, uri) {
  Exception.call(this, msg);
  this.code = code;
  this.uri = uri;
}
ServerException.prototype = Object.create(Exception.prototype);
ServerException.prototype.constructor = ServerException;