aboutsummaryrefslogtreecommitdiff
path: root/src/util/tokenpipe.cpp
blob: 49456814e2ec78924f510b37ad9152d31c7a825f (plain)
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
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/tokenpipe.h>

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#ifndef WIN32

#include <errno.h>
#include <fcntl.h>
#include <optional>
#include <unistd.h>

TokenPipeEnd TokenPipe::TakeReadEnd()
{
    TokenPipeEnd res(m_fds[0]);
    m_fds[0] = -1;
    return res;
}

TokenPipeEnd TokenPipe::TakeWriteEnd()
{
    TokenPipeEnd res(m_fds[1]);
    m_fds[1] = -1;
    return res;
}

TokenPipeEnd::TokenPipeEnd(int fd) : m_fd(fd)
{
}

TokenPipeEnd::~TokenPipeEnd()
{
    Close();
}

int TokenPipeEnd::TokenWrite(uint8_t token)
{
    while (true) {
        ssize_t result = write(m_fd, &token, 1);
        if (result < 0) {
            // Failure. It's possible that the write was interrupted by a signal,
            // in that case retry.
            if (errno != EINTR) {
                return TS_ERR;
            }
        } else if (result == 0) {
            return TS_EOS;
        } else { // ==1
            return 0;
        }
    }
}

int TokenPipeEnd::TokenRead()
{
    uint8_t token;
    while (true) {
        ssize_t result = read(m_fd, &token, 1);
        if (result < 0) {
            // Failure. Check if the read was interrupted by a signal,
            // in that case retry.
            if (errno != EINTR) {
                return TS_ERR;
            }
        } else if (result == 0) {
            return TS_EOS;
        } else { // ==1
            return token;
        }
    }
    return token;
}

void TokenPipeEnd::Close()
{
    if (m_fd != -1) close(m_fd);
    m_fd = -1;
}

std::optional<TokenPipe> TokenPipe::Make()
{
    int fds[2] = {-1, -1};
#if HAVE_O_CLOEXEC && HAVE_DECL_PIPE2
    if (pipe2(fds, O_CLOEXEC) != 0) {
        return std::nullopt;
    }
#else
    if (pipe(fds) != 0) {
        return std::nullopt;
    }
#endif
    return TokenPipe(fds);
}

TokenPipe::~TokenPipe()
{
    Close();
}

void TokenPipe::Close()
{
    if (m_fds[0] != -1) close(m_fds[0]);
    if (m_fds[1] != -1) close(m_fds[1]);
    m_fds[0] = m_fds[1] = -1;
}

#endif // WIN32