File: SWScriptStorage.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (148 lines) | stat: -rw-r--r-- 6,116 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (C) 2021-2023 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "SWScriptStorage.h"

#include "Logging.h"
#include "ScriptBuffer.h"
#include "ServiceWorkerRegistrationKey.h"
#include <pal/crypto/CryptoDigest.h>
#include <wtf/MainThread.h>
#include <wtf/PageBlock.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/Base64.h>

namespace WebCore {

WTF_MAKE_TZONE_ALLOCATED_IMPL(SWScriptStorage);

static bool shouldUseFileMapping(uint64_t fileSize)
{
    return fileSize >= pageSize();
}

SWScriptStorage::SWScriptStorage(const String& directory)
    : m_directory(directory)
    , m_salt(valueOrDefault(FileSystem::readOrMakeSalt(saltPath())))
{
    ASSERT(!isMainThread());
}

String SWScriptStorage::sha2Hash(const String& input) const
{
    auto crypto = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
    crypto->addBytes(m_salt);
    auto inputUTF8 = input.utf8();
    crypto->addBytes(byteCast<uint8_t>(inputUTF8.span()));
    return base64URLEncodeToString(crypto->computeHash());
}

String SWScriptStorage::sha2Hash(const URL& input) const
{
    return sha2Hash(input.string());
}

String SWScriptStorage::saltPath() const
{
    return FileSystem::pathByAppendingComponent(m_directory, "salt"_s);
}

String SWScriptStorage::registrationDirectory(const ServiceWorkerRegistrationKey& registrationKey) const
{
    return FileSystem::pathByAppendingComponents(m_directory, { sha2Hash(registrationKey.topOrigin().toString()), sha2Hash(registrationKey.scope()) });
}

String SWScriptStorage::scriptPath(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL) const
{
    return FileSystem::pathByAppendingComponent(registrationDirectory(registrationKey), sha2Hash(scriptURL));
}

ScriptBuffer SWScriptStorage::store(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL, const ScriptBuffer& script)
{
    ASSERT(!isMainThread());

    auto scriptPath = this->scriptPath(registrationKey, scriptURL);
    FileSystem::makeAllDirectories(FileSystem::parentPath(scriptPath));

    size_t size = script.buffer() ? script.buffer()->size() : 0;

    auto iterateOverBufferAndWriteData = [&](NOESCAPE const Function<bool(std::span<const uint8_t>)>& writeData) {
        script.buffer()->forEachSegment([&](std::span<const uint8_t> span) {
            writeData(span);
        });
    };

    // Make sure we delete the file before writing as there may be code using a mmap'd version of this file.
    FileSystem::deleteFile(scriptPath);

    if (!shouldUseFileMapping(size)) {
        auto handle = FileSystem::openFile(scriptPath, FileSystem::FileOpenMode::Truncate);
        if (!FileSystem::isHandleValid(handle)) {
            RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::store: Failure to store %s, FileSystem::openFile() failed", scriptPath.utf8().data());
            return { };
        }
        if (size) {
            iterateOverBufferAndWriteData([&](std::span<const uint8_t> span) {
                FileSystem::writeToFile(handle, span);
                return true;
            });
        }
        FileSystem::closeFile(handle);
        return script;
    }

    auto mappedFile = FileSystem::mapToFile(scriptPath, size, WTFMove(iterateOverBufferAndWriteData));
    if (!mappedFile) {
        RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::store: Failure to store %s, FileSystem::mapToFile() failed", scriptPath.utf8().data());
        return { };
    }
    return ScriptBuffer { SharedBuffer::create(WTFMove(mappedFile)) };
}

ScriptBuffer SWScriptStorage::retrieve(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL)
{
    ASSERT(!isMainThread());

    auto scriptPath = this->scriptPath(registrationKey, scriptURL);
    auto fileSize = FileSystem::fileSize(scriptPath);
    if (!fileSize) {
        RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::retrieve: Failure to retrieve %s, FileSystem::fileSize() failed", scriptPath.utf8().data());
        return { };
    }

    // FIXME: Do we need to disable file mapping in more cases to avoid having too many file descriptors open?
    RefPtr<FragmentedSharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(scriptPath, FileSystem::MappedFileMode::Private, shouldUseFileMapping(*fileSize) ? SharedBuffer::MayUseFileMapping::Yes : SharedBuffer::MayUseFileMapping::No);
    return buffer;
}

void SWScriptStorage::clear(const ServiceWorkerRegistrationKey& registrationKey)
{
    auto registrationDirectory = this->registrationDirectory(registrationKey);
    bool result = FileSystem::deleteNonEmptyDirectory(registrationDirectory);
    RELEASE_LOG_ERROR_IF(!result, ServiceWorker, "SWScriptStorage::clear: Failure to clear scripts for registration %s", registrationKey.toDatabaseKey().utf8().data());
}

} // namespace WebCore