]> granicus.if.org Git - icinga2/blob - lib/base/networkstream.cpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / networkstream.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "base/networkstream.hpp"
4
5 using namespace icinga;
6
7 NetworkStream::NetworkStream(Socket::Ptr socket)
8         : m_Socket(std::move(socket)), m_Eof(false)
9 { }
10
11 void NetworkStream::Close()
12 {
13         Stream::Close();
14
15         m_Socket->Close();
16 }
17
18 /**
19  * Reads data from the stream.
20  *
21  * @param buffer The buffer where data should be stored. May be nullptr if you're
22  *               not actually interested in the data.
23  * @param count The number of bytes to read from the queue.
24  * @returns The number of bytes actually read.
25  */
26 size_t NetworkStream::Read(void *buffer, size_t count, bool allow_partial)
27 {
28         size_t rc;
29
30         ASSERT(allow_partial);
31
32         if (m_Eof)
33                 BOOST_THROW_EXCEPTION(std::invalid_argument("Tried to read from closed socket."));
34
35         try {
36                 rc = m_Socket->Read(buffer, count);
37         } catch (...) {
38                 m_Eof = true;
39
40                 throw;
41         }
42
43         if (rc == 0)
44                 m_Eof = true;
45
46         return rc;
47 }
48
49 /**
50  * Writes data to the stream.
51  *
52  * @param buffer The data that is to be written.
53  * @param count The number of bytes to write.
54  * @returns The number of bytes written
55  */
56 void NetworkStream::Write(const void *buffer, size_t count)
57 {
58         size_t rc;
59
60         if (m_Eof)
61                 BOOST_THROW_EXCEPTION(std::invalid_argument("Tried to write to closed socket."));
62
63         try {
64                 rc = m_Socket->Write(buffer, count);
65         } catch (...) {
66                 m_Eof = true;
67
68                 throw;
69         }
70
71         if (rc < count) {
72                 m_Eof = true;
73
74                 BOOST_THROW_EXCEPTION(std::runtime_error("Short write for socket."));
75         }
76 }
77
78 bool NetworkStream::IsEof() const
79 {
80         return m_Eof;
81 }