summaryrefslogtreecommitdiffstats
path: root/mobile/android/components/extensions/ext-downloads.js
blob: 116f976cbf641542bbc7af337a6c3e45b957e07a (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
/* 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/. */

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  DownloadPaths: "resource://gre/modules/DownloadPaths.sys.mjs",
  DownloadTracker: "resource://gre/modules/GeckoViewWebExtension.sys.mjs",
});

Cu.importGlobalProperties(["PathUtils"]);

var { ignoreEvent } = ExtensionCommon;

const REQUEST_DOWNLOAD_MESSAGE = "GeckoView:WebExtension:Download";

const FORBIDDEN_HEADERS = [
  "ACCEPT-CHARSET",
  "ACCEPT-ENCODING",
  "ACCESS-CONTROL-REQUEST-HEADERS",
  "ACCESS-CONTROL-REQUEST-METHOD",
  "CONNECTION",
  "CONTENT-LENGTH",
  "COOKIE",
  "COOKIE2",
  "DATE",
  "DNT",
  "EXPECT",
  "HOST",
  "KEEP-ALIVE",
  "ORIGIN",
  "TE",
  "TRAILER",
  "TRANSFER-ENCODING",
  "UPGRADE",
  "VIA",
];

const FORBIDDEN_PREFIXES = /^PROXY-|^SEC-/i;

const State = {
  IN_PROGRESS: "in_progress",
  INTERRUPTED: "interrupted",
  COMPLETE: "complete",
};

const STATE_MAP = new Map([
  [0, State.IN_PROGRESS],
  [1, State.INTERRUPTED],
  [2, State.COMPLETE],
]);

const INTERRUPT_REASON_MAP = new Map([
  [0, undefined],
  [1, "FILE_FAILED"],
  [2, "FILE_ACCESS_DENIED"],
  [3, "FILE_NO_SPACE"],
  [4, "FILE_NAME_TOO_LONG"],
  [5, "FILE_TOO_LARGE"],
  [6, "FILE_VIRUS_INFECTED"],
  [7, "FILE_TRANSIENT_ERROR"],
  [8, "FILE_BLOCKED"],
  [9, "FILE_SECURITY_CHECK_FAILED"],
  [10, "FILE_TOO_SHORT"],
  [11, "NETWORK_FAILED"],
  [12, "NETWORK_TIMEOUT"],
  [13, "NETWORK_DISCONNECTED"],
  [14, "NETWORK_SERVER_DOWN"],
  [15, "NETWORK_INVALID_REQUEST"],
  [16, "SERVER_FAILED"],
  [17, "SERVER_NO_RANGE"],
  [18, "SERVER_BAD_CONTENT"],
  [19, "SERVER_UNAUTHORIZED"],
  [20, "SERVER_CERT_PROBLEM"],
  [21, "SERVER_FORBIDDEN"],
  [22, "USER_CANCELED"],
  [23, "USER_SHUTDOWN"],
  [24, "CRASH"],
]);

// TODO Bug 1247794: make id and extension info persistent
class DownloadItem {
  /**
   * Initializes an object that represents a download
   *
   * @param {object} downloadInfo - an object from Java when creating a download
   * @param {object} options - an object passed in to download() function
   * @param {Extension} extension - instance of an extension object
   */
  constructor(downloadInfo, options, extension) {
    this.id = downloadInfo.id;
    this.url = options.url;
    this.referrer = downloadInfo.referrer || "";
    this.filename = downloadInfo.filename || "";
    this.incognito = options.incognito;
    this.danger = "safe"; // todo; not implemented in desktop either
    this.mime = downloadInfo.mime || "";
    this.startTime = downloadInfo.startTime;
    this.state = STATE_MAP.get(downloadInfo.state);
    this.paused = downloadInfo.paused;
    this.canResume = downloadInfo.canResume;
    this.bytesReceived = downloadInfo.bytesReceived;
    this.totalBytes = downloadInfo.totalBytes;
    this.fileSize = downloadInfo.fileSize;
    this.exists = downloadInfo.exists;
    this.byExtensionId = extension?.id;
    this.byExtensionName = extension?.name;
  }

  /**
   * This function updates the download item it was called on.
   *
   * @param {object} data that arrived from the app (Java)
   * @returns {object | null} an object of <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads/onChanged#downloaddelta>downloadDelta type</a>
   */
  update(data) {
    const { downloadItemId } = data;
    const delta = {};

    data.state = STATE_MAP.get(data.state);
    data.error = INTERRUPT_REASON_MAP.get(data.error);
    delete data.downloadItemId;

    let changed = false;
    for (const prop in data) {
      const current = data[prop] ?? null;
      const previous = this[prop] ?? null;
      if (current !== previous) {
        delta[prop] = { current, previous };
        this[prop] = current;
        changed = true;
      }
    }

    // Don't send empty onChange events
    if (!changed) {
      return null;
    }

    delta.id = downloadItemId;

    return delta;
  }
}

this.downloads = class extends ExtensionAPIPersistent {
  PERSISTENT_EVENTS = {
    onChanged({ fire, context }, params) {
      const listener = (eventName, event) => {
        const { delta, downloadItem } = event;
        const { extension } = this;
        if (extension.privateBrowsingAllowed || !downloadItem.incognito) {
          fire.async(delta);
        }
      };
      DownloadTracker.on("download-changed", listener);

      return {
        unregister() {
          DownloadTracker.off("download-changed", listener);
        },
        convert(_fire, _context) {
          fire = _fire;
          context = _context;
        },
      };
    },
  };

  getAPI(context) {
    const { extension } = context;
    return {
      downloads: {
        download(options) {
          // the validation checks should be kept in sync with the toolkit implementation
          const { filename } = options;
          if (filename != null) {
            if (!filename.length) {
              return Promise.reject({ message: "filename must not be empty" });
            }

            if (PathUtils.isAbsolute(filename)) {
              return Promise.reject({
                message: "filename must not be an absolute path",
              });
            }

            const pathComponents = PathUtils.splitRelative(filename, {
              allowEmpty: true,
              allowCurrentDir: true,
              allowParentDir: true,
            });

            if (pathComponents.some(component => component == "..")) {
              return Promise.reject({
                message: "filename must not contain back-references (..)",
              });
            }

            if (
              pathComponents.some(component => {
                const sanitized = DownloadPaths.sanitize(component, {
                  compressWhitespaces: false,
                });
                return component != sanitized;
              })
            ) {
              return Promise.reject({
                message: "filename must not contain illegal characters",
              });
            }
          }

          if (options.incognito && !context.privateBrowsingAllowed) {
            return Promise.reject({
              message: "Private browsing access not allowed",
            });
          }

          if (options.cookieStoreId != null) {
            // https://bugzilla.mozilla.org/show_bug.cgi?id=1721460
            throw new ExtensionError("Not implemented");
          }

          if (options.headers) {
            for (const { name } of options.headers) {
              if (
                FORBIDDEN_HEADERS.includes(name.toUpperCase()) ||
                name.match(FORBIDDEN_PREFIXES)
              ) {
                return Promise.reject({
                  message: "Forbidden request header name",
                });
              }
            }
          }

          return EventDispatcher.instance
            .sendRequestForResult({
              type: REQUEST_DOWNLOAD_MESSAGE,
              options,
              extensionId: extension.id,
            })
            .then(value => {
              const downloadItem = new DownloadItem(value, options, extension);
              DownloadTracker.addDownloadItem(downloadItem);
              return downloadItem.id;
            });
        },

        removeFile(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        search(query) {
          throw new ExtensionError("Not implemented");
        },

        pause(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        resume(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        cancel(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        showDefaultFolder() {
          throw new ExtensionError("Not implemented");
        },

        erase(query) {
          throw new ExtensionError("Not implemented");
        },

        open(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        show(downloadId) {
          throw new ExtensionError("Not implemented");
        },

        getFileIcon(downloadId, options) {
          throw new ExtensionError("Not implemented");
        },

        onChanged: new EventManager({
          context,
          module: "downloads",
          event: "onChanged",
          extensionApi: this,
        }).api(),

        onCreated: ignoreEvent(context, "downloads.onCreated"),

        onErased: ignoreEvent(context, "downloads.onErased"),

        onDeterminingFilename: ignoreEvent(
          context,
          "downloads.onDeterminingFilename"
        ),
      },
    };
  }
};