File: favicon_database.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (345 lines) | stat: -rw-r--r-- 14,932 bytes parent folder | download | duplicates (3)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_FAVICON_CORE_FAVICON_DATABASE_H_
#define COMPONENTS_FAVICON_CORE_FAVICON_DATABASE_H_

#include <optional>
#include <vector>

#include "base/feature_list.h"
#include "base/gtest_prod_util.h"
#include "base/memory/ref_counted.h"
#include "components/favicon/core/favicon_types.h"
#include "sql/database.h"
#include "sql/init_status.h"
#include "sql/meta_table.h"
#include "sql/statement.h"

namespace base {
class FilePath;
class RefCountedMemory;
class Time;
}  // namespace base

namespace url {
class Origin;
}  // namespace url

namespace favicon {

// The minimum number of days after which last_requested field gets updated.
// All earlier updates are ignored.
static const int kFaviconUpdateLastRequestedAfterDays = 10;

// This database interface is owned by the history backend and runs on the
// history thread.
class FaviconDatabase {
 public:
  FaviconDatabase();
  ~FaviconDatabase();

  // Must be called after creation but before any other methods are called.
  // When not INIT_OK, no other functions should be called.
  sql::InitStatus Init(const base::FilePath& db_name);

  // Computes and records various metrics for the database. Should only be
  // called once and only upon successful Init.
  void ComputeDatabaseMetrics();

  // Transactions on the database.
  void BeginTransaction();
  void CommitTransaction();
  int transaction_nesting() const { return db_.transaction_nesting(); }
  void RollbackTransaction();

  // Vacuums the database. This will cause sqlite to defragment and collect
  // unused space in the file. It can be VERY SLOW.
  void Vacuum();

  // Release all non-essential memory associated with this database connection.
  void TrimMemory();

  // Get all on-demand favicon bitmaps that have been last requested prior to
  // `threshold`.
  std::map<favicon_base::FaviconID, IconMappingsForExpiry>
  GetOldOnDemandFavicons(base::Time threshold);

  // Favicon Bitmaps -----------------------------------------------------------

  // Returns true if there are favicon bitmaps for `icon_id`. If
  // `bitmap_id_sizes` is non NULL, sets it to a list of the favicon bitmap ids
  // and their associated pixel sizes for the favicon with `icon_id`.
  // The list contains results for the bitmaps which are cached in the
  // favicon_bitmaps table. The pixel sizes are a subset of the sizes in the
  // 'sizes' field of the favicons table for `icon_id`.
  bool GetFaviconBitmapIDSizes(
      favicon_base::FaviconID icon_id,
      std::vector<FaviconBitmapIDSize>* bitmap_id_sizes);

  // Returns true if there are any matched bitmaps for the given `icon_id`. All
  // matched results are returned if `favicon_bitmaps` is not NULL.
  bool GetFaviconBitmaps(favicon_base::FaviconID icon_id,
                         std::vector<FaviconBitmap>* favicon_bitmaps);

  // Gets the last updated time, bitmap data, and pixel size of the favicon
  // bitmap at `bitmap_id`. Returns true if successful.
  bool GetFaviconBitmap(FaviconBitmapID bitmap_id,
                        base::Time* last_updated,
                        base::Time* last_requested,
                        scoped_refptr<base::RefCountedMemory>* png_icon_data,
                        gfx::Size* pixel_size);

  // Adds a bitmap component of `type` at `pixel_size` for the favicon with
  // `icon_id`. Only favicons representing a .ico file should have multiple
  // favicon bitmaps per favicon.
  // `icon_data` is the png encoded data.
  // The `type` indicates how the lifetime of this icon should be managed.
  // The `time` is used for lifetime management of the bitmap (should be Now()).
  // `pixel_size` is the pixel dimensions of `icon_data`.
  // Returns the id of the added bitmap or 0 if unsuccessful.
  FaviconBitmapID AddFaviconBitmap(
      favicon_base::FaviconID icon_id,
      scoped_refptr<base::RefCountedMemory> icon_data,
      FaviconBitmapType type,
      base::Time time,
      const gfx::Size& pixel_size);

  // Sets the bitmap data and the last updated time for the favicon bitmap at
  // `bitmap_id`. Should not be called for bitmaps of type ON_DEMAND as they
  // should never get updated (the call silently changes the type to ON_VISIT).
  // Returns true if successful.
  bool SetFaviconBitmap(FaviconBitmapID bitmap_id,
                        scoped_refptr<base::RefCountedMemory> bitmap_data,
                        base::Time time);

  // Sets the last_updated time for the favicon bitmap at `bitmap_id`. Should
  // not be called for bitmaps of type ON_DEMAND as last_updated time is only
  // tracked for ON_VISIT bitmaps (the call silently changes the type to
  // ON_VISIT). Returns true if successful.
  bool SetFaviconBitmapLastUpdateTime(FaviconBitmapID bitmap_id,
                                      base::Time time);

  // Deletes the favicon bitmap with `bitmap_id`.
  // Returns true if successful.
  bool DeleteFaviconBitmap(FaviconBitmapID bitmap_id);

  // Favicons ------------------------------------------------------------------

  // Sets the the favicon as out of date. This will set `last_updated` for all
  // of the bitmaps for `icon_id` to be out of date.
  bool SetFaviconOutOfDate(favicon_base::FaviconID icon_id);

  // Mark all favicons as out of date that have been modified at or after
  // `begin` and before `end`. This will set `last_updated` for all matching
  // bitmaps to be out of date.
  bool SetFaviconsOutOfDateBetween(base::Time begin, base::Time end);

  // Retrieves the newest `last_updated` time across all bitmaps for `icon_id`.
  // Returns true if successful and if there is at least one bitmap.
  bool GetFaviconLastUpdatedTime(favicon_base::FaviconID icon_id,
                                 base::Time* last_updated);

  // Mark all bitmaps of type ON_DEMAND at `icon_url` as requested at `time`.
  // This postpones their automatic eviction from the database. Not all calls
  // end up in a write into the DB:
  // - it is no-op if the bitmaps are not of type ON_DEMAND;
  // - the updates of the "last requested time" have limited frequency for each
  //   particular bitmap (e.g. once per week). This limits the overhead of
  //   cache management for on-demand favicons.
  // Returns true if successful.
  bool TouchOnDemandFavicon(const GURL& icon_url, base::Time time);

  // Returns the id of the entry in the favicon database with the specified
  // `icon_url` and `icon_type` that has an existing mapping to `page_origin`
  // (and 0 if no entry exists). See crbug.com/1300214 for more context.
  favicon_base::FaviconID GetFaviconIDForFaviconURL(
      const GURL& icon_url,
      favicon_base::IconType icon_type,
      const url::Origin& page_origin);

  // Returns the id of the entry in the favicon database with the specified
  // `icon_url` and `icon_type` (and 0 if no entry exists). This function does
  // not respect cross-origin partitioning and returns an entry from the cache
  // without verifying it was stored for the origin requesting it. This can leak
  // navigation history, see crbug.com/1300214 for more context.
  favicon_base::FaviconID GetFaviconIDForFaviconURL(
      const GURL& icon_url,
      favicon_base::IconType icon_type);

  // Gets the icon_url, icon_type and sizes for the specified `icon_id`.
  bool GetFaviconHeader(favicon_base::FaviconID icon_id,
                        GURL* icon_url,
                        favicon_base::IconType* icon_type);

  // Adds favicon with `icon_url`, `icon_type` and `favicon_sizes` to the
  // favicon db, returning its id.
  favicon_base::FaviconID AddFavicon(const GURL& icon_url,
                                     favicon_base::IconType icon_type);

  // Adds a favicon with a single bitmap. This call is equivalent to calling
  // AddFavicon and AddFaviconBitmap of type `type`.
  favicon_base::FaviconID AddFavicon(
      const GURL& icon_url,
      favicon_base::IconType icon_type,
      scoped_refptr<base::RefCountedMemory> icon_data,
      FaviconBitmapType type,
      base::Time time,
      const gfx::Size& pixel_size);

  // Delete the favicon with the provided id. Returns false on failure
  bool DeleteFavicon(favicon_base::FaviconID id);

  // Icon Mapping --------------------------------------------------------------
  //
  // Returns true if there is a matched icon mapping for the given page and
  // icon type.
  // The matched icon mapping is returned in the icon_mapping parameter if it is
  // not NULL.

  // Returns true if there are icon mappings for the given page and icon types.
  // The matched icon mappings are returned in the `mapping_data` parameter if
  // it is not NULL.
  bool GetIconMappingsForPageURL(
      const GURL& page_url,
      const favicon_base::IconTypeSet& required_icon_types,
      std::vector<IconMapping>* mapping_data);

  // Returns true if there is any matched icon mapping for the given page.
  // All matched icon mappings are returned in descent order of IconType if
  // mapping_data is not NULL.
  bool GetIconMappingsForPageURL(const GURL& page_url,
                                 std::vector<IconMapping>* mapping_data);

  // Given `url`, returns the `page_url` page mapped to an icon with
  // `required_icon_types`, where `page_url` has host = url.host(). The search
  // prioritizes `PageUrlType::kRegular` over `PageUrlType::kRedirect` on the
  // assumption that `url` is not a cross-host redirect. This enables icons
  // to be retrieved when a full URL is not available. For example,
  // `url` = http://www.google.com would match
  // `page_url` = https://www.google.com/search.
  // The returned optional will be empty if no such `page_url` exists.
  std::optional<GURL> FindBestPageURLForHost(
      const GURL& url,
      const favicon_base::IconTypeSet& required_icon_types);

  // Adds a mapping between the given `page_url` and `icon_id`. A
  // `page_url_type` must also be provided. It is not possible to store multiple
  // entries for a (`page_url`, `icon_id`) pair with different `page_url_type`s.
  // Returns the new mapping id if the adding succeeds, otherwise 0 is returned.
  IconMappingID AddIconMapping(const GURL& page_url,
                               favicon_base::FaviconID icon_id,
                               PageUrlType page_url_type);

  // Deletes the icon mapping entries for the given page url.
  // Returns true if the deletion succeeded.
  bool DeleteIconMappings(const GURL& page_url);

  // Deletes the icon mapping entries for the given favicon ID.
  // Returns true if the deletion succeeded.
  bool DeleteIconMappingsForFaviconId(favicon_base::FaviconID id);

  // Deletes the icon mapping with `mapping_id`.
  // Returns true if the deletion succeeded.
  bool DeleteIconMapping(IconMappingID mapping_id);

  // Checks whether a favicon is used by any URLs in the database.
  bool HasMappingFor(favicon_base::FaviconID id);

  // Returns the ids of favicons which were last updated before `time`. This
  // returns at most `max_count` ids.
  std::vector<favicon_base::FaviconID> GetFaviconsLastUpdatedBefore(
      base::Time time,
      int max_count);

  // The class to enumerate icon mappings. Use InitIconMappingEnumerator to
  // initialize.
  class IconMappingEnumerator {
   public:
    IconMappingEnumerator();

    IconMappingEnumerator(const IconMappingEnumerator&) = delete;
    IconMappingEnumerator& operator=(const IconMappingEnumerator&) = delete;

    ~IconMappingEnumerator();

    // Get the next icon mapping, return false if no more are available.
    bool GetNextIconMapping(IconMapping* icon_mapping);

   private:
    friend class FaviconDatabase;

    // Used to query database and return the data for filling IconMapping in
    // each call of GetNextIconMapping().
    sql::Statement statement_;
  };

  // Return all icon mappings of the given `icon_type`.
  bool InitIconMappingEnumerator(favicon_base::IconType type,
                                 IconMappingEnumerator* enumerator);

  // Remove all data except that associated with the passed page urls.
  // Returns false in case of failure.  A nested transaction is used,
  // so failure causes any outer transaction to be rolled back.
  bool RetainDataForPageUrls(const std::vector<GURL>& urls_to_keep);

 private:
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseIconTypeTest,
                           ShouldBeBackwardCompatible);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, RetainDataForPageUrls);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest,
                           RetainDataForPageUrlsExpiresRetainedFavicons);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version3);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version4);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version5);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version6);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version7);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version8);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, Version9);
  FRIEND_TEST_ALL_PREFIXES(FaviconDatabaseTest, WildSchema);

  // For historical reasons, and for backward compatibility, the icon type
  // values stored in the DB are powers of two. Conversion functions
  // exposed publicly for testing.
  static int ToPersistedIconType(favicon_base::IconType icon_type);
  static favicon_base::IconType FromPersistedIconType(int icon_type);

  // `page_url_type` is stored as an int representation of the enum.
  static int ToPersistedPageUrlType(PageUrlType page_url_type);
  static PageUrlType FromPersistedPageUrlType(int page_url_type);

  // Fills `icon_mapping` with data from `statement` for `page_url`. The
  // format of the data in `statement` is an internal implementation detail.
  static void FillIconMapping(const GURL& page_url,
                              sql::Statement& statement,
                              IconMapping* icon_mapping);

  // Open database on a given filename. If the file does not exist,
  // it is created.
  // `db` is the database to open.
  // `db_name` is a path to the database file.
  sql::InitStatus OpenDatabase(sql::Database* db,
                               const base::FilePath& db_name);

  // Helper function to implement internals of Init().  This allows
  // Init() to retry in case of failure, since some failures run
  // recovery code.
  sql::InitStatus InitImpl(const base::FilePath& db_name);

  // Helper function to handle cleanup on upgrade failures.
  sql::InitStatus CantUpgradeToVersion(int cur_version);

  // Adds column for `page_url_type` to `icon_mapping` table.
  bool UpgradeToVersion9();

  // Returns true if the `favicons` database is missing a column.
  bool IsFaviconDBStructureIncorrect();

  sql::Database db_;
  sql::MetaTable meta_table_;
};

}  // namespace favicon

#endif  // COMPONENTS_FAVICON_CORE_FAVICON_DATABASE_H_