FileSystemHashSource.cpp (2298B)
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/. */ 6 7 #include "FileSystemHashSource.h" 8 9 #include "FileSystemParentTypes.h" 10 #include "mozilla/dom/FileSystemTypes.h" 11 #include "mozilla/dom/data_encoding_ffi_generated.h" 12 #include "mozilla/dom/quota/QuotaCommon.h" 13 #include "nsComponentManagerUtils.h" 14 #include "nsICryptoHash.h" 15 #include "nsNetCID.h" 16 #include "nsString.h" 17 #include "nsStringFwd.h" 18 19 namespace mozilla::dom::fs::data { 20 21 Result<EntryId, QMResult> FileSystemHashSource::GenerateHash( 22 const EntryId& aParent, const Name& aName) { 23 auto makeHasher = [](nsresult* aRv) { 24 return do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, aRv); 25 }; 26 QM_TRY_INSPECT(const auto& hasher, 27 QM_TO_RESULT_TRANSFORM(MOZ_TO_RESULT_GET_TYPED( 28 nsCOMPtr<nsICryptoHash>, makeHasher))); 29 30 QM_TRY(QM_TO_RESULT(hasher->Init(nsICryptoHash::SHA256))); 31 32 QM_TRY(QM_TO_RESULT( 33 hasher->Update(reinterpret_cast<const uint8_t*>(aName.BeginReading()), 34 sizeof(char16_t) * aName.Length()))); 35 36 QM_TRY(QM_TO_RESULT( 37 hasher->Update(reinterpret_cast<const uint8_t*>(aParent.BeginReading()), 38 aParent.Length()))); 39 40 EntryId entryId; 41 QM_TRY(QM_TO_RESULT(hasher->Finish(/* aASCII */ false, entryId))); 42 MOZ_ASSERT(!entryId.IsEmpty()); 43 44 return entryId; 45 } 46 47 Result<Name, QMResult> FileSystemHashSource::EncodeHash(const FileId& aFileId) { 48 MOZ_ASSERT(32u == aFileId.Value().Length()); 49 nsCString encoded; 50 base32encode(&aFileId.Value(), &encoded); 51 52 // We are stripping last four padding characters because 53 // it may not be allowed in some file systems. 54 MOZ_ASSERT(56u == encoded.Length() && '=' == encoded[52u] && 55 '=' == encoded[53u] && '=' == encoded[54u] && '=' == encoded[55u]); 56 encoded.SetLength(52u); 57 58 Name result; 59 QM_TRY(OkIf(result.SetCapacity(encoded.Length(), mozilla::fallible)), 60 Err(QMResult(NS_ERROR_OUT_OF_MEMORY))); 61 62 result.AppendASCII(encoded); 63 64 return result; 65 } 66 67 } // namespace mozilla::dom::fs::data