Files
palemoon27/xpcom/io/Base64.cpp
T
roytam1 c5205b44c8 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1240330 - mozAlarm debug messages are turned on r=khuey (aa938a4371)
- fix (cdc44e8bc8)
- Bug 1239788 - Don't include non-main-thread assertions in the constructor enabled check for [Exposed=System] WebIDL interfaces; r=bzbarsky (5d05b4066a)
- Bug 1247346. Slot indices on IDL interface members that get a slot should be per-interface, not a single per-member number. r=peterv (640231c37e)
- Bug 1157469 - null check wrapper in case WrapNode fails, r=bholley (9fd9b038db)
- Bug 1242211 - Mark MozMapRooter as final; r=baku (f3b5cc7728)
- Bug 1243438. Don't try to include the filename '<unknown>' when including headers for unions that have a built-in typedef they're referenced by. r=peterv (781d1ec0af)
- Bug 1241021 part 1: Refactor GenerateCSS2PropertiesWebIDL.py to invoke a helper function for each line. r=bz (258b031fd8)
- Bug 1241021 part 2: Make GenerateCSS2PropertiesWebIDL.py produce capitalized as well as uncapitalized WebkitFoo/webkitFoo DOM style accessors. r=bz (0bf2ec95ae)
- Bug 1241021 part 3: Refactor CSS mochitest test_initial_storage.html to perform its DOM accessor consistency-checks via a helper-function. r=bz (3a0c1a1678)
- Bug 1241021 part 4: Extend mochitest test_initial_storage.html to test that uppercase Webkit DOM accessors for css properties are functional. r=bz (5a6a23c7ab)
- Bug 1240592 - Remove unnecessary -Wno-uninitialized from dom/bindings. r=khuey (c854f7b397)
- Bug 1200341 - Implement HKDF for WebCrypto r=rbarnes,smaug (2c830d65a1)
- Bug 1200341 - Use BufferSource instead of CryptoOperationData in the SubtleCrypto WebIDL spec r=smaug (8cece95b5c)
- Bug 1191936 - Implement RSA-PSS key generation r=rbarnes (ec9654595c)
- Bug 1191936 - Implement RSA-PSS signing and verification r=rbarnes,smaug (7653bdfced)
- Bug 1204763 follow-up: Fix the comments, DONTBUILD (8b26e6f3a9)
- Reformat clang-plugin.cpp using clang-format, no bug (9346eda9f4)
- Bug 1214037 - Don't consider the result of an assignment expression MOZ_MUST_USE, r=ehsan (70c7830c3a)
- Bug 1242789 - Allow lambdas to capture raw pointers to refcounted objects by reference, r=ehsan (e7158a7746)
- Bug 1238042 - Add about:checkerboard. r=ehsan,botond (f234ce7fa0)
- Bug 1237177. Make the this-rebinding callable proxy sandboxes use return the prototype of its target, not its own null prototype. r=efaust (694a8081dc)
- Bug 1248521 - Pack PrefHashEntry better. r=froydnj. (55e9d609fe)
- Bug 1240453 - enable shared memory in xpconnect. r=bz (58db0b406e)
- Bug 1202014 - Don't use-after-move in ActorsChild.cpp, r=khuey (382e7183c0)
- Bug 1136762 - TSan: data race xpcom/io/nsPipe3.cpp:1061 CloseWithStatus. r=nfroyd. (68fd82971d)
- Bug 1237668 - Remove nsSimpleUnicharStreamFactory r=froydnj (8bb6ec081c)
- Bug 1189998, Part 4 - Add authentication secret to Push data test. r=dragana (122a0bd5f9)
- Bug 1205137 - Add a PushSubscription serializer. r=mt,smaug (aa9e847c42)
- Bug 1232910 - Use channel.asyncOpen2 within dom/push/PushServiceHttp2.jsm. r=sicking r=dragana (a2f483a983)
- Bug 1246632 - Fix ackMsgRecv in PushServiceHttp2.js. r=kitcambridge (c1559e0539)
- Bug 1240615 - Make PushService protocol init method return a Promise. r=kitcambridge (4d52dc6a41)
- Bug 1246784 - Expose Console to the WorkerDebuggerGlobalScope, r=khuey (a992fdc555)
- misspatch (33708903c4)
- Bug 1207494 - Part 5: Remove use of expression closure from dom/contacts/. r=reuben (256b3831a4)
- Bug 1207494 - Part 4: Remove use of expression closure from dom/canvas/. r=gw280 (1666e49673)
- Bug 1207494 - Part 3: Remove use of expression closure from dom/browser-element/. r=smaug (a891769373)
- Bug 1207494 - Part 2: Remove use of expression closure from dom/base/test/. r=peterv (01762e3181)
- Bug 1207494 - Part 1: Remove use of expression closure from dom/apps/. r=ferjm (2474c8619b)
- Bug 1247108 - Pass securityFlag when creating a new channel within webapps (r=fabrice) (8305294f26)
- Bug 1219004 - Improve error management in getFullAppByManifestURL r=ferjm (c3ad64df7a)
- revert contains/includes (29c60a77e5)
- Bug 1147562 - Update remaining callsites of newChannel before landing the shim in dom/ (r=sicking) (0cd64e20e1)
- Bug 1243924 - Convert remaining callsites within dom/ to use channel.open2() (r=sicking) (43b01f88ba)
- Bug 1162658 - Update FormData to match latest spec, r=smaug (a42ca52ad5)
- Bug 1208895 - Fix a typo in nsGenericHTMLElement::GetItemId(); r=baku (2d6f2d79f4)
- Bug 1223523. The named getter on document should not return images with an empty name. r=peterv (da3d1f52f5)
- Bug 1183491. Null-check the document we get from our contentWindow in the contentDocument getter, because apparently it can end up null. r=bkelly (3002a4375c)
- Bug 1203430 - Intermittent crash in PNeckoChild::SendHTMLDNSPrefetch. r=jdm (3b82b57cbf)
- Bug 893332, part 1 - Rename misnamed SetValidityState/GetValidityState arguments. r=baku (d403b12c9a)
- Bug 893332, part 2 - Update validity state before asserting range underflow state. r=baku (a4cbce224c)
- Bug 893332, part 3 - Don't assert range underflow state under the parser. r=baku (763e99ed8e)
- Bug 893332, part 4 - Crashtests. r=baku (7cdcdc02c4)
- Bug 1240336 Setting same value to either <input> or <textarea> shouldn't cause committing existing composition r=ehsan (5cc2c35dbb)
- Bug 1228708. Fix UndoManager to correctly suppress exceptions it wants to suppress on ErrorResults. r=smaug (905207a3b4)
- Bug 1230295 - Add telemetry to report when Ogg chaining is used. r=rillian,r=vladan (e47c49f508)
2023-12-29 16:00:23 +08:00

424 lines
11 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
#include "Base64.h"
#include "nsIInputStream.h"
#include "nsString.h"
#include "plbase64.h"
namespace {
// BEGIN base64 encode code copied and modified from NSPR
const unsigned char* base =
(unsigned char*)"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
template<typename T>
static void
Encode3to4(const unsigned char* aSrc, T* aDest)
{
uint32_t b32 = (uint32_t)0;
int i, j = 18;
for (i = 0; i < 3; ++i) {
b32 <<= 8;
b32 |= (uint32_t)aSrc[i];
}
for (i = 0; i < 4; ++i) {
aDest[i] = base[(uint32_t)((b32 >> j) & 0x3F)];
j -= 6;
}
}
template<typename T>
static void
Encode2to4(const unsigned char* aSrc, T* aDest)
{
aDest[0] = base[(uint32_t)((aSrc[0] >> 2) & 0x3F)];
aDest[1] = base[(uint32_t)(((aSrc[0] & 0x03) << 4) | ((aSrc[1] >> 4) & 0x0F))];
aDest[2] = base[(uint32_t)((aSrc[1] & 0x0F) << 2)];
aDest[3] = (unsigned char)'=';
}
template<typename T>
static void
Encode1to4(const unsigned char* aSrc, T* aDest)
{
aDest[0] = base[(uint32_t)((aSrc[0] >> 2) & 0x3F)];
aDest[1] = base[(uint32_t)((aSrc[0] & 0x03) << 4)];
aDest[2] = (unsigned char)'=';
aDest[3] = (unsigned char)'=';
}
template<typename T>
static void
Encode(const unsigned char* aSrc, uint32_t aSrcLen, T* aDest)
{
while (aSrcLen >= 3) {
Encode3to4(aSrc, aDest);
aSrc += 3;
aDest += 4;
aSrcLen -= 3;
}
switch (aSrcLen) {
case 2:
Encode2to4(aSrc, aDest);
break;
case 1:
Encode1to4(aSrc, aDest);
break;
case 0:
break;
default:
NS_NOTREACHED("coding error");
}
}
// END base64 encode code copied and modified from NSPR.
template<typename T>
struct EncodeInputStream_State
{
unsigned char c[3];
uint8_t charsOnStack;
typename T::char_type* buffer;
};
template<typename T>
NS_METHOD
EncodeInputStream_Encoder(nsIInputStream* aStream,
void* aClosure,
const char* aFromSegment,
uint32_t aToOffset,
uint32_t aCount,
uint32_t* aWriteCount)
{
MOZ_ASSERT(aCount > 0, "Er, what?");
EncodeInputStream_State<T>* state =
static_cast<EncodeInputStream_State<T>*>(aClosure);
// We consume the whole data always.
*aWriteCount = aCount;
// If we have any data left from last time, encode it now.
uint32_t countRemaining = aCount;
const unsigned char* src = (const unsigned char*)aFromSegment;
if (state->charsOnStack) {
MOZ_ASSERT(state->charsOnStack == 1 || state->charsOnStack == 2);
// Not enough data to compose a triple.
if (state->charsOnStack == 1 && countRemaining == 1) {
state->charsOnStack = 2;
state->c[1] = src[0];
return NS_OK;
}
uint32_t consumed = 0;
unsigned char firstSet[4];
if (state->charsOnStack == 1) {
firstSet[0] = state->c[0];
firstSet[1] = src[0];
firstSet[2] = src[1];
firstSet[3] = '\0';
consumed = 2;
} else /* state->charsOnStack == 2 */ {
firstSet[0] = state->c[0];
firstSet[1] = state->c[1];
firstSet[2] = src[0];
firstSet[3] = '\0';
consumed = 1;
}
Encode(firstSet, 3, state->buffer);
state->buffer += 4;
countRemaining -= consumed;
src += consumed;
state->charsOnStack = 0;
// Nothing is left.
if (!countRemaining) {
return NS_OK;
}
}
// Encode as many full triplets as possible.
uint32_t encodeLength = countRemaining - countRemaining % 3;
MOZ_ASSERT(encodeLength % 3 == 0,
"Should have an exact number of triplets!");
Encode(src, encodeLength, state->buffer);
state->buffer += (encodeLength / 3) * 4;
src += encodeLength;
countRemaining -= encodeLength;
if (countRemaining) {
// We should never have a full triplet left at this point.
MOZ_ASSERT(countRemaining < 3, "We should have encoded more!");
state->c[0] = src[0];
state->c[1] = (countRemaining == 2) ? src[1] : '\0';
state->charsOnStack = countRemaining;
}
return NS_OK;
}
template<typename T>
nsresult
EncodeInputStream(nsIInputStream* aInputStream,
T& aDest,
uint32_t aCount,
uint32_t aOffset)
{
nsresult rv;
uint64_t count64 = aCount;
if (!aCount) {
rv = aInputStream->Available(&count64);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// if count64 is over 4GB, it will be failed at the below condition,
// then will return NS_ERROR_OUT_OF_MEMORY
aCount = (uint32_t)count64;
}
uint64_t countlong =
(count64 + 2) / 3 * 4; // +2 due to integer math.
if (countlong + aOffset > UINT32_MAX) {
return NS_ERROR_OUT_OF_MEMORY;
}
uint32_t count = uint32_t(countlong);
if (!aDest.SetLength(count + aOffset, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
EncodeInputStream_State<T> state;
state.charsOnStack = 0;
state.c[2] = '\0';
state.buffer = aOffset + aDest.BeginWriting();
while (1) {
uint32_t read = 0;
rv = aInputStream->ReadSegments(&EncodeInputStream_Encoder<T>,
(void*)&state,
aCount,
&read);
if (NS_FAILED(rv)) {
if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
NS_RUNTIMEABORT("Not implemented for async streams!");
}
if (rv == NS_ERROR_NOT_IMPLEMENTED) {
NS_RUNTIMEABORT("Requires a stream that implements ReadSegments!");
}
return rv;
}
if (!read) {
break;
}
}
// Finish encoding if anything is left
if (state.charsOnStack) {
Encode(state.c, state.charsOnStack, state.buffer);
}
if (aDest.Length()) {
// May belong to an nsCString with an unallocated buffer, so only null
// terminate if there is a need to.
*aDest.EndWriting() = '\0';
}
return NS_OK;
}
static const char kBase64URLAlphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
} // namespace
namespace mozilla {
nsresult
Base64EncodeInputStream(nsIInputStream* aInputStream,
nsACString& aDest,
uint32_t aCount,
uint32_t aOffset)
{
return EncodeInputStream<nsACString>(aInputStream, aDest, aCount, aOffset);
}
nsresult
Base64EncodeInputStream(nsIInputStream* aInputStream,
nsAString& aDest,
uint32_t aCount,
uint32_t aOffset)
{
return EncodeInputStream<nsAString>(aInputStream, aDest, aCount, aOffset);
}
nsresult
Base64Encode(const nsACString& aBinaryData, nsACString& aString)
{
// Check for overflow.
if (aBinaryData.Length() > (UINT32_MAX / 4) * 3) {
return NS_ERROR_FAILURE;
}
// Don't ask PR_Base64Encode to encode empty strings
if (aBinaryData.IsEmpty()) {
aString.Truncate();
return NS_OK;
}
uint32_t stringLen = ((aBinaryData.Length() + 2) / 3) * 4;
char* buffer;
// Add one byte for null termination.
if (aString.SetCapacity(stringLen + 1, fallible) &&
(buffer = aString.BeginWriting()) &&
PL_Base64Encode(aBinaryData.BeginReading(), aBinaryData.Length(), buffer)) {
// PL_Base64Encode doesn't null terminate the buffer for us when we pass
// the buffer in. Do that manually.
buffer[stringLen] = '\0';
aString.SetLength(stringLen);
return NS_OK;
}
aString.Truncate();
return NS_ERROR_INVALID_ARG;
}
nsresult
Base64Encode(const nsAString& aString, nsAString& aBinaryData)
{
NS_LossyConvertUTF16toASCII string(aString);
nsAutoCString binaryData;
nsresult rv = Base64Encode(string, binaryData);
if (NS_SUCCEEDED(rv)) {
CopyASCIItoUTF16(binaryData, aBinaryData);
} else {
aBinaryData.Truncate();
}
return rv;
}
nsresult
Base64Decode(const nsACString& aString, nsACString& aBinaryData)
{
// Check for overflow.
if (aString.Length() > UINT32_MAX / 3) {
return NS_ERROR_FAILURE;
}
// Don't ask PR_Base64Decode to decode the empty string
if (aString.IsEmpty()) {
aBinaryData.Truncate();
return NS_OK;
}
uint32_t binaryDataLen = ((aString.Length() * 3) / 4);
char* buffer;
// Add one byte for null termination.
if (aBinaryData.SetCapacity(binaryDataLen + 1, fallible) &&
(buffer = aBinaryData.BeginWriting()) &&
PL_Base64Decode(aString.BeginReading(), aString.Length(), buffer)) {
// PL_Base64Decode doesn't null terminate the buffer for us when we pass
// the buffer in. Do that manually, taking into account the number of '='
// characters we were passed.
if (!aString.IsEmpty() && aString[aString.Length() - 1] == '=') {
if (aString.Length() > 1 && aString[aString.Length() - 2] == '=') {
binaryDataLen -= 2;
} else {
binaryDataLen -= 1;
}
}
buffer[binaryDataLen] = '\0';
aBinaryData.SetLength(binaryDataLen);
return NS_OK;
}
aBinaryData.Truncate();
return NS_ERROR_INVALID_ARG;
}
nsresult
Base64Decode(const nsAString& aBinaryData, nsAString& aString)
{
NS_LossyConvertUTF16toASCII binaryData(aBinaryData);
nsAutoCString string;
nsresult rv = Base64Decode(binaryData, string);
if (NS_SUCCEEDED(rv)) {
CopyASCIItoUTF16(string, aString);
} else {
aString.Truncate();
}
return rv;
}
nsresult
Base64URLEncode(uint32_t aLength, const uint8_t* aData, nsACString& aString)
{
// Don't encode empty strings.
if (aLength == 0) {
aString.Truncate();
return NS_OK;
}
// Check for overflow.
if ((static_cast<uint64_t>(aLength) * 6 + 7) / 8 > UINT32_MAX) {
return NS_ERROR_FAILURE;
}
if (!aString.SetLength((aLength * 8 + 5) / 6, fallible)) {
aString.Truncate();
return NS_ERROR_FAILURE;
}
char* rawBuffer = aString.BeginWriting();
uint32_t index = 0;
for (; index + 3 <= aLength; index += 3) {
*rawBuffer++ = kBase64URLAlphabet[aData[index] >> 2];
*rawBuffer++ = kBase64URLAlphabet[((aData[index] & 0x3) << 4) |
(aData[index + 1] >> 4)];
*rawBuffer++ = kBase64URLAlphabet[((aData[index + 1] & 0xf) << 2) |
(aData[index + 2] >> 6)];
*rawBuffer++ = kBase64URLAlphabet[aData[index + 2] & 0x3f];
}
uint32_t remaining = aLength - index;
if (remaining == 1) {
*rawBuffer++ = kBase64URLAlphabet[aData[index] >> 2];
*rawBuffer++ = kBase64URLAlphabet[((aData[index] & 0x3) << 4)];
} else if (remaining == 2) {
*rawBuffer++ = kBase64URLAlphabet[aData[index] >> 2];
*rawBuffer++ = kBase64URLAlphabet[((aData[index] & 0x3) << 4) |
(aData[index + 1] >> 4)];
*rawBuffer++ = kBase64URLAlphabet[((aData[index + 1] & 0xf) << 2)];
}
return NS_OK;
}
} // namespace mozilla