1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_GeneratePlaceholderCanvasData_h
8 #define mozilla_dom_GeneratePlaceholderCanvasData_h
10 #include "mozilla/StaticPrefs_privacy.h"
12 #include "nsIRandomGenerator.h"
13 #include "nsServiceManagerUtils.h"
15 #define RANDOM_BYTES_TO_SAMPLE 32
17 namespace mozilla::dom
{
20 * When privacy.resistFingerprinting.randomDataOnCanvasExtract is true, tries
21 * to generate random data for placeholder canvas by sampling
22 * RANDOM_BYTES_TO_SAMPLE bytes and then returning it. If this fails or if
23 * privacy.resistFingerprinting.randomDataOnCanvasExtract is false, returns
26 * @return uint8_t* output buffer
28 inline uint8_t* TryToGenerateRandomDataForPlaceholderCanvasData() {
29 if (!StaticPrefs::privacy_resistFingerprinting_randomDataOnCanvasExtract()) {
33 nsCOMPtr
<nsIRandomGenerator
> rg
=
34 do_GetService("@mozilla.org/security/random-generator;1", &rv
);
39 rv
= rg
->GenerateRandomBytes(RANDOM_BYTES_TO_SAMPLE
, &randomData
);
47 * If randomData not nullptr, repeats those bytes many times to fill buffer. If
48 * randomData is nullptr, returns all-white pixel data.
50 * @param[in] randomData Buffer of RANDOM_BYTES_TO_SAMPLE bytes of random
52 * @param[in] size Size of output buffer
53 * @param[out] buffer Output buffer
55 inline void FillPlaceholderCanvas(uint8_t* randomData
, uint32_t size
,
58 memset(buffer
, 0xFF, size
);
61 auto remaining_to_fill
= size
;
63 while (remaining_to_fill
> 0) {
64 auto bytes_to_write
= (remaining_to_fill
> RANDOM_BYTES_TO_SAMPLE
)
65 ? RANDOM_BYTES_TO_SAMPLE
67 memcpy(buffer
+ (index
* RANDOM_BYTES_TO_SAMPLE
), randomData
,
69 remaining_to_fill
-= bytes_to_write
;
76 * When privacy.resistFingerprinting.randomDataOnCanvasExtract is true, tries
77 * to generate random canvas data by sampling RANDOM_BYTES_TO_SAMPLE bytes and
78 * then repeating those bytes many times to fill the buffer. If this fails or
79 * if privacy.resistFingerprinting.randomDataOnCanvasExtract is false, returns
80 * all-white, opaque pixel data.
82 * It is recommended that callers call this function instead of individually
83 * calling TryToGenerateRandomDataForPlaceholderCanvasData and
84 * FillPlaceholderCanvas unless there are requirements, like NoGC, that prevent
85 * them from calling the RNG service inside this function.
87 * @param[in] size Size of output buffer
88 * @param[out] buffer Output buffer
90 inline void GeneratePlaceholderCanvasData(uint32_t size
, uint8_t* buffer
) {
91 uint8_t* randomData
= TryToGenerateRandomDataForPlaceholderCanvasData();
92 FillPlaceholderCanvas(randomData
, size
, buffer
);
95 } // namespace mozilla::dom
97 #endif // mozilla_dom_GeneratePlaceholderCanvasData_h