summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/parent/ext-proxy.js
blob: 049fac81799422aa1e8dc2698f2ad5c97c0b42ac (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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* 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, {
  ProxyChannelFilter: "resource://gre/modules/ProxyChannelFilter.sys.mjs",
});
var { ExtensionPreferencesManager } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionPreferencesManager.sys.mjs"
);

var { ExtensionError } = ExtensionUtils;
var { getSettingsAPI } = ExtensionPreferencesManager;

const proxySvc = Ci.nsIProtocolProxyService;

const PROXY_TYPES_MAP = new Map([
  ["none", proxySvc.PROXYCONFIG_DIRECT],
  ["autoDetect", proxySvc.PROXYCONFIG_WPAD],
  ["system", proxySvc.PROXYCONFIG_SYSTEM],
  ["manual", proxySvc.PROXYCONFIG_MANUAL],
  ["autoConfig", proxySvc.PROXYCONFIG_PAC],
]);

const DEFAULT_PORTS = new Map([
  ["http", 80],
  ["ssl", 443],
  ["socks", 1080],
]);

ExtensionPreferencesManager.addSetting("proxy.settings", {
  permission: "proxy",
  prefNames: [
    "network.proxy.type",
    "network.proxy.http",
    "network.proxy.http_port",
    "network.proxy.share_proxy_settings",
    "network.proxy.ssl",
    "network.proxy.ssl_port",
    "network.proxy.socks",
    "network.proxy.socks_port",
    "network.proxy.socks_version",
    "network.proxy.socks_remote_dns",
    "network.proxy.no_proxies_on",
    "network.proxy.autoconfig_url",
    "signon.autologin.proxy",
    "network.http.proxy.respect-be-conservative",
  ],

  setCallback(value) {
    let prefs = {
      "network.proxy.type": PROXY_TYPES_MAP.get(value.proxyType),
      "signon.autologin.proxy": value.autoLogin,
      "network.proxy.socks_remote_dns": value.proxyDNS,
      "network.proxy.autoconfig_url": value.autoConfigUrl,
      "network.proxy.share_proxy_settings": value.httpProxyAll,
      "network.proxy.socks_version": value.socksVersion,
      "network.proxy.no_proxies_on": value.passthrough,
      "network.http.proxy.respect-be-conservative": value.respectBeConservative,
    };

    for (let prop of ["http", "ssl", "socks"]) {
      if (value[prop]) {
        let url = new URL(`http://${value[prop]}`);
        prefs[`network.proxy.${prop}`] = url.hostname;
        // Only fall back to defaults if no port provided.
        let [, rawPort] = value[prop].split(":");
        let port = parseInt(rawPort, 10) || DEFAULT_PORTS.get(prop);
        prefs[`network.proxy.${prop}_port`] = port;
      }
    }

    return prefs;
  },
});

function registerProxyFilterEvent(
  context,
  extension,
  fire,
  filterProps,
  extraInfoSpec = []
) {
  let listener = data => {
    return fire.sync(data);
  };

  let filter = { ...filterProps };
  if (filter.urls) {
    let perms = new MatchPatternSet([
      ...extension.allowedOrigins.patterns,
      ...extension.optionalOrigins.patterns,
    ]);
    filter.urls = new MatchPatternSet(filter.urls);

    if (!perms.overlapsAll(filter.urls)) {
      Cu.reportError(
        "The proxy.onRequest filter doesn't overlap with host permissions."
      );
    }
  }

  let proxyFilter = new ProxyChannelFilter(
    context,
    extension,
    listener,
    filter,
    extraInfoSpec
  );
  return {
    unregister: () => {
      proxyFilter.destroy();
    },
    convert(_fire, _context) {
      fire = _fire;
      proxyFilter.context = _context;
    },
  };
}

this.proxy = class extends ExtensionAPIPersistent {
  PERSISTENT_EVENTS = {
    onRequest({ fire, context }, params) {
      return registerProxyFilterEvent(context, this.extension, fire, ...params);
    },
  };

  getAPI(context) {
    let { extension } = context;
    let self = this;

    return {
      proxy: {
        onRequest: new EventManager({
          context,
          module: "proxy",
          event: "onRequest",
          extensionApi: self,
        }).api(),

        // Leaving as non-persistent.  By itself it's not useful since proxy-error
        // is emitted from the proxy filter.
        onError: new EventManager({
          context,
          name: "proxy.onError",
          register: fire => {
            let listener = (name, error) => {
              fire.async(error);
            };
            extension.on("proxy-error", listener);
            return () => {
              extension.off("proxy-error", listener);
            };
          },
        }).api(),

        settings: Object.assign(
          getSettingsAPI({
            context,
            name: "proxy.settings",
            callback() {
              let prefValue = Services.prefs.getIntPref("network.proxy.type");
              let proxyConfig = {
                proxyType: Array.from(PROXY_TYPES_MAP.entries()).find(
                  entry => entry[1] === prefValue
                )[0],
                autoConfigUrl: Services.prefs.getCharPref(
                  "network.proxy.autoconfig_url"
                ),
                autoLogin: Services.prefs.getBoolPref("signon.autologin.proxy"),
                proxyDNS: Services.prefs.getBoolPref(
                  "network.proxy.socks_remote_dns"
                ),
                httpProxyAll: Services.prefs.getBoolPref(
                  "network.proxy.share_proxy_settings"
                ),
                socksVersion: Services.prefs.getIntPref(
                  "network.proxy.socks_version"
                ),
                passthrough: Services.prefs.getCharPref(
                  "network.proxy.no_proxies_on"
                ),
              };

              if (extension.isPrivileged) {
                proxyConfig.respectBeConservative = Services.prefs.getBoolPref(
                  "network.http.proxy.respect-be-conservative"
                );
              }

              for (let prop of ["http", "ssl", "socks"]) {
                let host = Services.prefs.getCharPref(`network.proxy.${prop}`);
                let port = Services.prefs.getIntPref(
                  `network.proxy.${prop}_port`
                );
                proxyConfig[prop] = port ? `${host}:${port}` : host;
              }

              return proxyConfig;
            },
            // proxy.settings is unsupported on android.
            validate() {
              if (AppConstants.platform == "android") {
                throw new ExtensionError(
                  `proxy.settings is not supported on android.`
                );
              }
            },
          }),
          {
            set: details => {
              if (AppConstants.platform === "android") {
                throw new ExtensionError(
                  "proxy.settings is not supported on android."
                );
              }

              if (!extension.privateBrowsingAllowed) {
                throw new ExtensionError(
                  "proxy.settings requires private browsing permission."
                );
              }

              if (!Services.policies.isAllowed("changeProxySettings")) {
                throw new ExtensionError(
                  "Proxy settings are being managed by the Policies manager."
                );
              }

              let value = details.value;

              // proxyType is optional and it should default to "system" when missing.
              if (value.proxyType == null) {
                value.proxyType = "system";
              }

              if (!PROXY_TYPES_MAP.has(value.proxyType)) {
                throw new ExtensionError(
                  `${value.proxyType} is not a valid value for proxyType.`
                );
              }

              if (value.httpProxyAll) {
                // Match what about:preferences does with proxy settings
                // since the proxy service does not check the value
                // of share_proxy_settings.
                value.ssl = value.http;
              }

              for (let prop of ["http", "ssl", "socks"]) {
                let host = value[prop];
                if (host) {
                  try {
                    // Fixup in case a full url is passed.
                    if (host.includes("://")) {
                      value[prop] = new URL(host).host;
                    } else {
                      // Validate the host value.
                      new URL(`http://${host}`);
                    }
                  } catch (e) {
                    throw new ExtensionError(
                      `${value[prop]} is not a valid value for ${prop}.`
                    );
                  }
                }
              }

              if (value.proxyType === "autoConfig" || value.autoConfigUrl) {
                try {
                  new URL(value.autoConfigUrl);
                } catch (e) {
                  throw new ExtensionError(
                    `${value.autoConfigUrl} is not a valid value for autoConfigUrl.`
                  );
                }
              }

              if (value.socksVersion !== undefined) {
                if (
                  !Number.isInteger(value.socksVersion) ||
                  value.socksVersion < 4 ||
                  value.socksVersion > 5
                ) {
                  throw new ExtensionError(
                    `${value.socksVersion} is not a valid value for socksVersion.`
                  );
                }
              }

              if (
                value.respectBeConservative !== undefined &&
                !extension.isPrivileged &&
                Services.prefs.getBoolPref(
                  "network.http.proxy.respect-be-conservative"
                ) != value.respectBeConservative
              ) {
                throw new ExtensionError(
                  `respectBeConservative can be set by privileged extensions only.`
                );
              }

              return ExtensionPreferencesManager.setSetting(
                extension.id,
                "proxy.settings",
                value
              );
            },
          }
        ),
      },
    };
  }
};