1 //* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=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/. */
6 
7 #ifndef VariableLengthPrefixSet_h
8 #define VariableLengthPrefixSet_h
9 
10 #include "nsISupports.h"
11 #include "nsIMemoryReporter.h"
12 #include "Entries.h"
13 #include "nsTArray.h"
14 #include "mozilla/MemoryReporting.h"
15 #include "mozilla/Mutex.h"
16 
17 class nsUrlClassifierPrefixSet;
18 
19 namespace mozilla {
20 namespace safebrowsing {
21 
22 class VariableLengthPrefixSet final : public nsIMemoryReporter {
23  public:
24   VariableLengthPrefixSet();
25 
26   nsresult Init(const nsACString& aName);
27   nsresult SetPrefixes(mozilla::safebrowsing::PrefixStringMap& aPrefixMap);
28   nsresult SetPrefixes(AddPrefixArray& aAddPrefixes,
29                        AddCompleteArray& aAddCompletes);
30   nsresult GetPrefixes(mozilla::safebrowsing::PrefixStringMap& aPrefixMap);
31   nsresult GetFixedLengthPrefixes(FallibleTArray<uint32_t>* aPrefixes,
32                                   FallibleTArray<nsCString>* aCompletes);
33   nsresult Matches(uint32_t aPrefix, const nsACString& aFullHash,
34                    uint32_t* aLength) const;
35   nsresult IsEmpty(bool* aEmpty) const;
36 
37   nsresult WritePrefixes(nsCOMPtr<nsIOutputStream>& out) const;
38   nsresult LoadPrefixes(nsCOMPtr<nsIInputStream>& in);
39   uint32_t CalculatePreallocateSize() const;
40 
41   size_t SizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
42 
43   NS_DECL_THREADSAFE_ISUPPORTS
44   NS_DECL_NSIMEMORYREPORTER
45 
46  private:
47   virtual ~VariableLengthPrefixSet();
48 
49   static const uint32_t PREFIXSET_VERSION_MAGIC = 1;
50 
51   bool BinarySearch(const nsACString& aFullHash, const nsACString& aPrefixes,
52                     uint32_t aPrefixSize) const;
53 
54   // Lock to prevent races between the url-classifier thread (which does most
55   // of the operations) and the main thread (which does memory reporting).
56   // It should be held for all operations between Init() and destruction that
57   // touch this class's data members.
58   mutable mozilla::Mutex mLock;
59 
60   const RefPtr<nsUrlClassifierPrefixSet> mFixedPrefixSet;
61   mozilla::safebrowsing::PrefixStringMap mVLPrefixSet;
62 
63   nsCString mName;
64   nsCString mMemoryReportPath;
65 };
66 
67 }  // namespace safebrowsing
68 }  // namespace mozilla
69 
70 #endif
71