aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/string_utils/secret_string/secret_string.cpp
blob: 3b68d3cd2749638db2cff05c3004d2e76ce07339 (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
#include "secret_string.h"

#include <util/system/madvise.h>

namespace NSecretString {
    TSecretString::TSecretString(TStringBuf value) {
        Init(value);
    }

    TSecretString::~TSecretString() {
        try {
            Clear();
        } catch (...) {
        }
    }

    TSecretString& TSecretString::operator=(const TSecretString& o) {
        if (&o == this) {
            return *this;
        }

        Init(o.Value_);

        return *this;
    }

    /**
     * It is not honest "move". Actually it is copy-assignment with cleaning of other instance.
     * This way allowes to avoid side effects of string optimizations:
     *   Copy-On-Write or Short-String-Optimization
     */
    TSecretString& TSecretString::operator=(TSecretString&& o) {
        if (&o == this) {
            return *this;
        }

        Init(o.Value_);
        o.Clear();

        return *this;
    }

    TSecretString& TSecretString::operator=(const TStringBuf o) {
        Init(o);

        return *this;
    }

    void TSecretString::Init(TStringBuf value) {
        Clear();
        if (value.empty()) {
            return;
        }

        Value_ = value;
        MadviseExcludeFromCoreDump(Value_);
    }

    void TSecretString::Clear() {
        if (Value_.empty()) {
            return;
        }

        SecureZero((void*)Value_.data(), Value_.size());
        MadviseIncludeIntoCoreDump(Value_);
        Value_.clear();
    }
}