Bitcoin ABC 0.30.5
P2P Digital Currency
tokenpipe.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4#include <util/tokenpipe.h>
5
6#include <config/bitcoin-config.h>
7
8#ifndef WIN32
9
10#include <cerrno>
11#include <fcntl.h>
12#include <unistd.h>
13
15 TokenPipeEnd res(m_fds[0]);
16 m_fds[0] = -1;
17 return res;
18}
19
21 TokenPipeEnd res(m_fds[1]);
22 m_fds[1] = -1;
23 return res;
24}
25
26TokenPipeEnd::TokenPipeEnd(int fd) : m_fd(fd) {}
27
29 Close();
30}
31
32int TokenPipeEnd::TokenWrite(uint8_t token) {
33 while (true) {
34 ssize_t result = write(m_fd, &token, 1);
35 if (result < 0) {
36 // Failure. It's possible that the write was interrupted by a
37 // signal, in that case retry.
38 if (errno != EINTR) {
39 return TS_ERR;
40 }
41 } else if (result == 0) {
42 return TS_EOS;
43 } else { // ==1
44 return 0;
45 }
46 }
47}
48
50 uint8_t token;
51 while (true) {
52 ssize_t result = read(m_fd, &token, 1);
53 if (result < 0) {
54 // Failure. Check if the read was interrupted by a signal,
55 // in that case retry.
56 if (errno != EINTR) {
57 return TS_ERR;
58 }
59 } else if (result == 0) {
60 return TS_EOS;
61 } else { // ==1
62 return token;
63 }
64 }
65 return token;
66}
67
69 if (m_fd != -1) {
70 close(m_fd);
71 }
72 m_fd = -1;
73}
74
75std::optional<TokenPipe> TokenPipe::Make() {
76 int fds[2] = {-1, -1};
77#if HAVE_O_CLOEXEC && HAVE_DECL_PIPE2
78 if (pipe2(fds, O_CLOEXEC) != 0) {
79 return std::nullopt;
80 }
81#else
82 if (pipe(fds) != 0) {
83 return std::nullopt;
84 }
85#endif
86 return TokenPipe(fds);
87}
88
90 Close();
91}
92
94 if (m_fds[0] != -1) {
95 close(m_fds[0]);
96 }
97 if (m_fds[1] != -1) {
98 close(m_fds[1]);
99 }
100 m_fds[0] = m_fds[1] = -1;
101}
102
103#endif // WIN32
One end of a token pipe.
Definition: tokenpipe.h:14
TokenPipeEnd(int fd=-1)
Definition: tokenpipe.cpp:26
@ TS_ERR
I/O error.
Definition: tokenpipe.h:25
@ TS_EOS
Unexpected end of stream.
Definition: tokenpipe.h:27
int TokenWrite(uint8_t token)
Write token to endpoint.
Definition: tokenpipe.cpp:32
void Close()
Explicit close function.
Definition: tokenpipe.cpp:68
int TokenRead()
Read token from endpoint.
Definition: tokenpipe.cpp:49
void Close()
Close and end of the pipe that hasn't been moved out.
Definition: tokenpipe.cpp:93
TokenPipeEnd TakeReadEnd()
Take the read end of this pipe.
Definition: tokenpipe.cpp:14
TokenPipeEnd TakeWriteEnd()
Take the write end of this pipe.
Definition: tokenpipe.cpp:20
int m_fds[2]
Definition: tokenpipe.h:77
static std::optional< TokenPipe > Make()
Create a new pipe.
Definition: tokenpipe.cpp:75
TokenPipe(int fds[2])
Definition: tokenpipe.h:79