aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/tvmauth/client/misc/disk_cache.cpp
blob: 3c01be4a837e7a7a52a184d605a1a3c2b866b4c6 (plain) (blame)
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include "disk_cache.h"

#include <library/cpp/tvmauth/client/logger.h>

#include <contrib/libs/openssl/include/openssl/evp.h>
#include <contrib/libs/openssl/include/openssl/hmac.h>
#include <contrib/libs/openssl/include/openssl/sha.h>

#include <util/folder/path.h>
#include <util/stream/file.h>
#include <util/stream/str.h>
#include <util/system/fs.h>
#include <util/system/sysstat.h>
#include <util/system/tempfile.h>

#include <exception>

namespace NTvmAuth {
    static const size_t HASH_SIZE = 32;
    static const size_t TIMESTAMP_SIZE = sizeof(time_t);

    TDiskReader::TDiskReader(const TString& filename, ILogger* logger)
        : Filename_(filename)
        , Logger_(logger)
    {
    }

    bool TDiskReader::Read() {
        TStringStream s;

        try {
            if (!NFs::Exists(Filename_)) {
                if (Logger_) {
                    s << "File '" << Filename_ << "' does not exist";
                    Logger_->Debug(s.Str());
                }
                return false;
            }

            TFile file(Filename_, OpenExisting | RdOnly | Seq);
            file.Flock(LOCK_SH | LOCK_NB);

            TFileInput input(file);
            return ParseData(input.ReadAll());
        } catch (const std::exception& e) {
            if (Logger_) {
                s << "Failed to read '" << Filename_ << "': " << e.what();
                Logger_->Error(s.Str());
            }
        }

        return false;
    }

    bool TDiskReader::ParseData(TStringBuf buf) {
        TStringStream s;

        if (buf.size() <= HASH_SIZE + TIMESTAMP_SIZE) {
            if (Logger_) {
                s << "File '" << Filename_ << "' is too small";
                Logger_->Warning(s.Str());
            }
            return false;
        }

        TStringBuf hash = buf.SubStr(0, HASH_SIZE);
        if (hash != GetHash(buf.Skip(HASH_SIZE))) {
            if (Logger_) {
                s << "Content of '" << Filename_ << "' was incorrectly changed";
                Logger_->Warning(s.Str());
            }
            return false;
        }

        Time_ = TInstant::Seconds(GetTimestamp(buf.substr(0, TIMESTAMP_SIZE)));
        Data_ = buf.Skip(TIMESTAMP_SIZE);

        if (Logger_) {
            s << "File '" << Filename_ << "' was successfully read";
            Logger_->Info(s.Str());
        }
        return true;
    }

    TString TDiskReader::GetHash(TStringBuf data) {
        TString value(EVP_MAX_MD_SIZE, 0);
        unsigned macLen = 0;
        if (!::HMAC(EVP_sha256(),
                    "",
                    0,
                    (unsigned char*)data.data(),
                    data.size(),
                    (unsigned char*)value.data(),
                    &macLen)) {
            return {};
        }

        if (macLen != EVP_MAX_MD_SIZE) {
            value.resize(macLen);
        }

        return value;
    }

    time_t TDiskReader::GetTimestamp(TStringBuf data) {
        time_t time = 0;
        for (int idx = TIMESTAMP_SIZE - 1; idx >= 0; --idx) {
            time <<= 8;
            time |= static_cast<unsigned char>(data.at(idx));
        }
        return time;
    }

    TDiskWriter::TDiskWriter(const TString& filename, ILogger* logger)
        : Filename_(filename)
        , Logger_(logger)
    {
    }

    bool TDiskWriter::Write(TStringBuf data, TInstant now) {
        TStringStream s;

        try {
            {
                if (NFs::Exists(Filename_)) {
                    Chmod(Filename_.c_str(),
                          S_IRUSR | S_IWUSR); // 600
                }

                TFile file(Filename_, CreateAlways | WrOnly | Seq | AWUser | ARUser);
                file.Flock(LOCK_EX | LOCK_NB);

                TFileOutput output(file);
                output << PrepareData(now, data);
            }

            if (Logger_) {
                s << "File '" << Filename_ << "' was successfully written";
                Logger_->Info(s.Str());
            }
            return true;
        } catch (const std::exception& e) {
            if (Logger_) {
                s << "Failed to write '" << Filename_ << "': " << e.what();
                Logger_->Error(s.Str());
            }
        }

        return false;
    }

    TString TDiskWriter::PrepareData(TInstant time, TStringBuf data) {
        TString toHash = WriteTimestamp(time.TimeT()) + data;
        return TDiskReader::GetHash(toHash) + toHash;
    }

    TString TDiskWriter::WriteTimestamp(time_t time) {
        TString res(TIMESTAMP_SIZE, 0);
        for (size_t idx = 0; idx < TIMESTAMP_SIZE; ++idx) {
            res[idx] = time & 0xFF;
            time >>= 8;
        }
        return res;
    }
}