summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/StorageController.java
blob: a49cdf26a577c98a0f85bd9ec8b7ba4692c87167 (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
402
403
404
405
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * vim: ts=4 sw=4 expandtab:
 * 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/. */

package org.mozilla.geckoview;

import android.util.Log;
import androidx.annotation.AnyThread;
import androidx.annotation.LongDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import org.mozilla.gecko.EventDispatcher;
import org.mozilla.gecko.util.GeckoBundle;
import org.mozilla.geckoview.GeckoSession.PermissionDelegate.ContentPermission;

/**
 * Manage runtime storage data.
 *
 * <p>Retrieve an instance via {@link GeckoRuntime#getStorageController}.
 */
public final class StorageController {
  private static final String LOGTAG = "StorageController";

  // Keep in sync with GeckoViewStorageController.ClearFlags.
  /** Flags used for data clearing operations. */
  public static class ClearFlags {
    /** Cookies. */
    public static final long COOKIES = 1 << 0;

    /** Network cache. */
    public static final long NETWORK_CACHE = 1 << 1;

    /** Image cache. */
    public static final long IMAGE_CACHE = 1 << 2;

    /** DOM storages. */
    public static final long DOM_STORAGES = 1 << 4;

    /** Auth tokens and caches. */
    public static final long AUTH_SESSIONS = 1 << 5;

    /** Site permissions. */
    public static final long PERMISSIONS = 1 << 6;

    /** All caches. */
    public static final long ALL_CACHES = NETWORK_CACHE | IMAGE_CACHE;

    /** All site settings (permissions, content preferences, security settings, etc.). */
    public static final long SITE_SETTINGS = 1 << 7 | PERMISSIONS;

    /** All site-related data (cookies, storages, caches, permissions, etc.). */
    public static final long SITE_DATA =
        1 << 8 | COOKIES | DOM_STORAGES | ALL_CACHES | PERMISSIONS | SITE_SETTINGS;

    /** All data. */
    public static final long ALL = 1 << 9;
  }

  @Retention(RetentionPolicy.SOURCE)
  @LongDef(
      flag = true,
      value = {
        ClearFlags.COOKIES,
        ClearFlags.NETWORK_CACHE,
        ClearFlags.IMAGE_CACHE,
        ClearFlags.DOM_STORAGES,
        ClearFlags.AUTH_SESSIONS,
        ClearFlags.PERMISSIONS,
        ClearFlags.ALL_CACHES,
        ClearFlags.SITE_SETTINGS,
        ClearFlags.SITE_DATA,
        ClearFlags.ALL
      })
  public @interface StorageControllerClearFlags {}

  /**
   * Clear data for all hosts.
   *
   * <p>Note: Any open session may re-accumulate previously cleared data. To ensure that no
   * persistent data is left behind, you need to close all sessions prior to clearing data.
   *
   * @param flags Combination of {@link ClearFlags}.
   * @return A {@link GeckoResult} that will complete when clearing has finished.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> clearData(final @StorageControllerClearFlags long flags) {
    final GeckoBundle bundle = new GeckoBundle(1);
    bundle.putLong("flags", flags);

    return EventDispatcher.getInstance().queryVoid("GeckoView:ClearData", bundle);
  }

  /**
   * Clear data owned by the given host. Clearing data for a host will not clear data created by its
   * third-party origins.
   *
   * <p>Note: Any open session may re-accumulate previously cleared data. To ensure that no
   * persistent data is left behind, you need to close all sessions prior to clearing data.
   *
   * @param host The host to be used.
   * @param flags Combination of {@link ClearFlags}.
   * @return A {@link GeckoResult} that will complete when clearing has finished.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> clearDataFromHost(
      final @NonNull String host, final @StorageControllerClearFlags long flags) {
    final GeckoBundle bundle = new GeckoBundle(2);
    bundle.putString("host", host);
    bundle.putLong("flags", flags);

    return EventDispatcher.getInstance().queryVoid("GeckoView:ClearHostData", bundle);
  }

  /**
   * Clear data owned by the given base domain (eTLD+1). Clearing data for a base domain will also
   * clear any associated third-party storage. This includes clearing for third-parties embedded by
   * the domain and for the given domain embedded under other sites.
   *
   * <p>Note: Any open session may re-accumulate previously cleared data. To ensure that no
   * persistent data is left behind, you need to close all sessions prior to clearing data.
   *
   * @param baseDomain The base domain to be used.
   * @param flags Combination of {@link ClearFlags}.
   * @return A {@link GeckoResult} that will complete when clearing has finished.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> clearDataFromBaseDomain(
      final @NonNull String baseDomain, final @StorageControllerClearFlags long flags) {
    final GeckoBundle bundle = new GeckoBundle(2);
    bundle.putString("baseDomain", baseDomain);
    bundle.putLong("flags", flags);

    return EventDispatcher.getInstance().queryVoid("GeckoView:ClearBaseDomainData", bundle);
  }

  /**
   * Clear data for the given context ID. Use {@link GeckoSessionSettings.Builder#contextId}.to set
   * a context ID for a session.
   *
   * <p>Note: Any open session may re-accumulate previously cleared data. To ensure that no
   * persistent data is left behind, you need to close all sessions for the given context prior to
   * clearing data.
   *
   * @param contextId The context ID for the storage data to be deleted.
   */
  @AnyThread
  public void clearDataForSessionContext(final @NonNull String contextId) {
    final GeckoBundle bundle = new GeckoBundle(1);
    bundle.putString("contextId", createSafeSessionContextId(contextId));

    EventDispatcher.getInstance().dispatch("GeckoView:ClearSessionContextData", bundle);
  }

  /* package */ static @Nullable String createSafeSessionContextId(
      final @Nullable String contextId) {
    if (contextId == null) {
      return null;
    }
    if (contextId.isEmpty()) {
      // Let's avoid empty strings for Gecko.
      return "gvctxempty";
    }
    // We don't want to restrict the session context ID string options, so to
    // ensure that the string is safe for Gecko processing, we translate it to
    // its hex representation.
    return String.format("gvctx%x", new BigInteger(contextId.getBytes())).toLowerCase(Locale.ROOT);
  }

  /* package */ static @Nullable String retrieveUnsafeSessionContextId(
      final @Nullable String contextId) {
    if (contextId == null || contextId.isEmpty()) {
      return null;
    }
    if ("gvctxempty".equals(contextId)) {
      return "";
    }
    final byte[] bytes = new BigInteger(contextId.substring(5), 16).toByteArray();
    return new String(bytes, Charset.forName("UTF-8"));
  }

  /**
   * Get all currently stored permissions.
   *
   * @return A {@link GeckoResult} that will complete with a list of all currently stored {@link
   *     ContentPermission}s.
   */
  @AnyThread
  public @NonNull GeckoResult<List<ContentPermission>> getAllPermissions() {
    return EventDispatcher.getInstance()
        .queryBundle("GeckoView:GetAllPermissions")
        .map(
            bundle -> {
              final GeckoBundle[] permsArray = bundle.getBundleArray("permissions");
              return ContentPermission.fromBundleArray(permsArray);
            });
  }

  /**
   * Get all currently stored permissions for a given URI and default (unset) context ID, in normal
   * mode This API will be deprecated in the future
   * https://bugzilla.mozilla.org/show_bug.cgi?id=1797379
   *
   * @param uri A String representing the URI to get permissions for.
   * @return A {@link GeckoResult} that will complete with a list of all currently stored {@link
   *     ContentPermission}s for the URI.
   */
  @AnyThread
  public @NonNull GeckoResult<List<ContentPermission>> getPermissions(final @NonNull String uri) {
    return getPermissions(uri, null, false);
  }

  /**
   * Get all currently stored permissions for a given URI and default (unset) context ID.
   *
   * @param uri A String representing the URI to get permissions for.
   * @param privateMode indicate where the {@link ContentPermission}s should be in private or normal
   *     mode.
   * @return A {@link GeckoResult} that will complete with a list of all currently stored {@link
   *     ContentPermission}s for the URI.
   */
  @AnyThread
  public @NonNull GeckoResult<List<ContentPermission>> getPermissions(
      final @NonNull String uri, final boolean privateMode) {
    return getPermissions(uri, null, privateMode);
  }

  /**
   * Get all currently stored permissions for a given URI and context ID.
   *
   * @param uri A String representing the URI to get permissions for.
   * @param contextId A String specifying the context ID.
   * @param privateMode indicate where the {@link ContentPermission}s should be in private or normal
   *     mode
   * @return A {@link GeckoResult} that will complete with a list of all currently stored {@link
   *     ContentPermission}s for the URI.
   */
  @AnyThread
  public @NonNull GeckoResult<List<ContentPermission>> getPermissions(
      final @NonNull String uri, final @Nullable String contextId, final boolean privateMode) {
    final GeckoBundle msg = new GeckoBundle(2);
    final int privateBrowsingId = (privateMode) ? 1 : 0;
    msg.putString("uri", uri);
    msg.putString("contextId", createSafeSessionContextId(contextId));
    msg.putInt("privateBrowsingId", privateBrowsingId);
    return EventDispatcher.getInstance()
        .queryBundle("GeckoView:GetPermissionsByURI", msg)
        .map(
            bundle -> {
              final GeckoBundle[] permsArray = bundle.getBundleArray("permissions");
              return ContentPermission.fromBundleArray(permsArray);
            });
  }

  /**
   * Set a new value for an existing permission.
   *
   * <p>Note: in private browsing, this value will only be cleared at the end of the session to add
   * permanent permissions in private browsing, you can use {@link
   * #setPrivateBrowsingPermanentPermission}.
   *
   * @param perm A {@link ContentPermission} that you wish to update the value of.
   * @param value The new value for the permission.
   */
  @AnyThread
  public void setPermission(
      final @NonNull ContentPermission perm, final @ContentPermission.Value int value) {
    setPermissionInternal(perm, value, /* allowPermanentPrivateBrowsing */ false);
  }

  /**
   * Set a permanent value for a permission in a private browsing session.
   *
   * <p>Normally permissions in private browsing are cleared at the end of the session. This method
   * allows you to set a permanent permission bypassing this behavior.
   *
   * <p>Note: permanent permissions in private browsing are web discoverable and might make the user
   * more easily trackable.
   *
   * @see #setPermission
   * @param perm A {@link ContentPermission} that you wish to update the value of.
   * @param value The new value for the permission.
   */
  @AnyThread
  public void setPrivateBrowsingPermanentPermission(
      final @NonNull ContentPermission perm, final @ContentPermission.Value int value) {
    setPermissionInternal(perm, value, /* allowPermanentPrivateBrowsing */ true);
  }

  private void setPermissionInternal(
      final @NonNull ContentPermission perm,
      final @ContentPermission.Value int value,
      final boolean allowPermanentPrivateBrowsing) {
    if (perm.permission == GeckoSession.PermissionDelegate.PERMISSION_TRACKING
        && value == ContentPermission.VALUE_PROMPT) {
      Log.w(LOGTAG, "Cannot set a tracking permission to VALUE_PROMPT, aborting.");
      return;
    }
    final GeckoBundle msg = perm.toGeckoBundle();
    msg.putInt("newValue", value);
    msg.putBoolean("allowPermanentPrivateBrowsing", allowPermanentPrivateBrowsing);
    EventDispatcher.getInstance().dispatch("GeckoView:SetPermission", msg);
  }

  /**
   * Set a permanent {@link ContentBlocking.CBCookieBannerMode} for the given uri and browsing mode.
   *
   * @param uri An uri for which you want change the {@link ContentBlocking.CBCookieBannerMode}
   *     value.
   * @param mode A new {@link ContentBlocking.CBCookieBannerMode} for the given uri.
   * @param isPrivateBrowsing Indicates in which browsing mode the given {@link
   *     ContentBlocking.CBCookieBannerMode} should be applied.
   * @return A {@link GeckoResult} that will complete when the mode has been set.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> setCookieBannerModeForDomain(
      final @NonNull String uri,
      final @ContentBlocking.CBCookieBannerMode int mode,
      final boolean isPrivateBrowsing) {
    final GeckoBundle data = new GeckoBundle(3);
    data.putString("uri", uri);
    data.putInt("mode", mode);
    data.putBoolean("allowPermanentPrivateBrowsing", false);
    data.putBoolean("isPrivateBrowsing", isPrivateBrowsing);
    return EventDispatcher.getInstance().queryVoid("GeckoView:SetCookieBannerModeForDomain", data);
  }

  /**
   * Set a permanent {@link ContentBlocking.CBCookieBannerMode} for the given uri in private mode.
   *
   * @param uri for which you want to change the {@link ContentBlocking.CBCookieBannerMode} value.
   * @param mode A new {@link ContentBlocking.CBCookieBannerMode} for the given uri.
   * @return A {@link GeckoResult} that will complete when the mode has been set.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> setCookieBannerModeAndPersistInPrivateBrowsingForDomain(
      final @NonNull String uri, final @ContentBlocking.CBCookieBannerMode int mode) {
    final GeckoBundle data = new GeckoBundle(3);
    data.putString("uri", uri);
    data.putInt("mode", mode);
    data.putBoolean("allowPermanentPrivateBrowsing", true);
    return EventDispatcher.getInstance().queryVoid("GeckoView:SetCookieBannerModeForDomain", data);
  }

  /**
   * Removes a {@link ContentBlocking.CBCookieBannerMode} for the given uri and and browsing mode.
   *
   * @param uri An uri for which you want change the {@link ContentBlocking.CBCookieBannerMode}
   *     value.
   * @param isPrivateBrowsing Indicates in which mode the given mode should be applied.
   * @return A {@link GeckoResult} that will complete when the mode has been removed.
   */
  @AnyThread
  public @NonNull GeckoResult<Void> removeCookieBannerModeForDomain(
      final @NonNull String uri, final boolean isPrivateBrowsing) {

    final GeckoBundle data = new GeckoBundle(3);
    data.putString("uri", uri);
    data.putBoolean("isPrivateBrowsing", isPrivateBrowsing);
    return EventDispatcher.getInstance()
        .queryVoid("GeckoView:RemoveCookieBannerModeForDomain", data);
  }

  /**
   * Gets the actual {@link ContentBlocking.CBCookieBannerMode} for the given uri and browsing mode.
   *
   * @param uri An uri for which you want get the {@link ContentBlocking.CBCookieBannerMode}.
   * @param isPrivateBrowsing Indicates in which browsing mode the given uri should be.
   * @return A {@link GeckoResult} that resolves to a {@link ContentBlocking.CBCookieBannerMode} for
   *     the given uri and browsing mode.
   */
  @AnyThread
  public @NonNull @ContentBlocking.CBCookieBannerMode GeckoResult<Integer>
      getCookieBannerModeForDomain(final @NonNull String uri, final boolean isPrivateBrowsing) {

    final GeckoBundle data = new GeckoBundle(2);
    data.putString("uri", uri);
    data.putBoolean("isPrivateBrowsing", isPrivateBrowsing);
    return EventDispatcher.getInstance()
        .queryBundle("GeckoView:GetCookieBannerModeForDomain", data)
        .map(StorageController::cookieBannerModeFromBundle, StorageController::fromQueryException);
  }

  private static @ContentBlocking.CBCookieBannerMode int cookieBannerModeFromBundle(
      final GeckoBundle bundle) throws Exception {
    if (bundle == null) {
      throw new Exception("Unable to parse cookie banner mode");
    }
    return bundle.getInt("mode");
  }

  private static Throwable fromQueryException(final Throwable exception) {
    final EventDispatcher.QueryException queryException =
        (EventDispatcher.QueryException) exception;
    final Object response = queryException.data;
    return new Exception(response.toString());
  }
}