[honey] Fix portability to systems without pread()
[xapian.git] / xapian-core / net / remoteconnection.h
blobc0423a617ac0c68c3e0a1ee8cc49b883da946a52
1 /** @file remoteconnection.h
2 * @brief RemoteConnection class used by the remote backend.
3 */
4 /* Copyright (C) 2006,2007,2008,2010,2011,2014,2015 Olly Betts
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #ifndef XAPIAN_INCLUDED_REMOTECONNECTION_H
22 #define XAPIAN_INCLUDED_REMOTECONNECTION_H
24 #include <string>
26 #include "remoteprotocol.h"
27 #include "safeerrno.h"
28 #include "safenetdb.h" // For EAI_* constants.
29 #include "safeunistd.h"
31 #ifdef __WIN32__
32 # include "safewinsock2.h"
34 # include <xapian/error.h>
36 /** Class to initialise winsock and keep it initialised while we use it.
38 * We need to get WinSock initialised before we use it, and make it clean up
39 * after we've finished using it. This class performs this initialisation when
40 * constructed and cleans up when destructed. Multiple instances of the class
41 * may be instantiated - windows keeps a count of the number of times that
42 * WSAStartup has been successfully called and only performs the actual cleanup
43 * when WSACleanup has been called the same number of times.
45 * Simply ensure that an instance of this class is initialised whenever we're
46 * doing socket handling. This class can be used as a mixin class (just
47 * inherit from it) or instantiated as a class member or local variable).
49 struct WinsockInitializer {
50 WinsockInitializer() {
51 WSADATA wsadata;
52 int wsaerror = WSAStartup(MAKEWORD(2, 2), &wsadata);
53 // FIXME - should we check the returned information in wsadata to check
54 // that we have a version of winsock which is recent enough for us?
56 if (wsaerror != 0) {
57 throw Xapian::NetworkError("Failed to initialize winsock", wsaerror);
61 ~WinsockInitializer() {
62 WSACleanup();
66 /** Get the errno value of the last error to occur due to a socket operation.
68 * This is specific to the calling thread.
70 * This is needed because some platforms (Windows) separate errors due to
71 * socket operations from other errors. On platforms which don't do this,
72 * the return value will be the value of errno.
74 inline int socket_errno() {
75 int wsa_err = WSAGetLastError();
76 switch (wsa_err) {
77 # ifdef EADDRINUSE
78 case WSAEADDRINUSE: return EADDRINUSE;
79 # endif
80 # ifdef ETIMEDOUT
81 case WSAETIMEDOUT: return ETIMEDOUT;
82 # endif
83 # ifdef EINPROGRESS
84 case WSAEINPROGRESS: return EINPROGRESS;
85 # endif
86 default: return wsa_err;
90 /* Newer compilers define these, in which case we map to those already defined
91 * values in socket_errno() above.
93 # ifndef EADDRINUSE
94 # define EADDRINUSE WSAEADDRINUSE
95 # endif
96 # ifndef ETIMEDOUT
97 # define ETIMEDOUT WSAETIMEDOUT
98 # endif
99 # ifndef EINPROGRESS
100 # define EINPROGRESS WSAEINPROGRESS
101 # endif
103 // We must call closesocket() (instead of just close()) under __WIN32__ or
104 // else the socket remains in the CLOSE_WAIT state.
105 # define CLOSESOCKET(S) closesocket(S)
106 #else
107 // Use a macro so we don't need to pull safeerrno.h in here.
108 # define socket_errno() errno
110 # define CLOSESOCKET(S) close(S)
111 #endif
113 inline int eai_to_xapian(int e) {
114 // Under WIN32, the EAI_* constants are defined to be WSA_* constants with
115 // roughly equivalent meanings, so we can just let them be handled as any
116 // other WSA_* error codes would be.
117 #ifndef __WIN32__
118 // Ensure they all have the same sign - this switch will fail to compile if
119 // we bitwise-or some 1 and some 2 bits to get 3.
120 #define C(X) ((X) < 0 ? 2 : 1)
121 // Switch on a value there is a case for, to avoid clang warning:
122 // "no case matching constant switch condition '0'"
123 switch (3) {
124 case
125 C(EAI_AGAIN)|
126 C(EAI_BADFLAGS)|
127 C(EAI_FAIL)|
128 C(EAI_FAMILY)|
129 C(EAI_MEMORY)|
130 C(EAI_NONAME)|
131 C(EAI_SERVICE)|
132 C(EAI_SOCKTYPE)|
133 C(EAI_SYSTEM)|
134 #ifdef EAI_ADDRFAMILY
135 // In RFC 2553 but not RFC 3493 or POSIX:
136 C(EAI_ADDRFAMILY)|
137 #endif
138 #ifdef EAI_NODATA
139 // In RFC 2553 but not RFC 3493 or POSIX:
140 C(EAI_NODATA)|
141 #endif
142 #ifdef EAI_OVERFLOW
143 // In RFC 3493 and POSIX but not RFC 2553:
144 C(EAI_OVERFLOW)|
145 #endif
146 0: break;
147 case 3: break;
149 #undef C
151 // EAI_SYSTEM means "look at errno".
152 if (e == EAI_SYSTEM)
153 return errno;
154 // POSIX only says that EAI_* constants are "non-zero". On Linux they are
155 // negative, but allow for them being positive too.
156 if (EAI_FAIL > 0)
157 return -e;
158 #endif
159 return e;
162 /** A RemoteConnection object provides a bidirectional connection to another
163 * RemoteConnection object on a remote machine.
165 * The connection is implemented using a pair of file descriptors. Messages
166 * with a single byte type code and arbitrary data as the contents can be
167 * sent and received.
169 class RemoteConnection {
170 /// Don't allow assignment.
171 void operator=(const RemoteConnection &);
173 /// Don't allow copying.
174 RemoteConnection(const RemoteConnection &);
176 /** The file descriptor used for reading.
178 * If this is -1, the connection is unidirectional and write-only.
179 * If both fdin and fdout are -1, then the connection has been closed.
181 int fdin;
183 /** The file descriptor used for writing.
185 * If this is -1, the connection is unidirectional and read-only.
186 * If both fdin and fdout are -1, then the connection has been closed.
187 * It is valid for fdout to be the same as fdin.
189 int fdout;
191 /// Buffer to hold unprocessed input.
192 std::string buffer;
194 /// Remaining bytes of message data still to come over fdin for a chunked read.
195 off_t chunked_data_left;
197 /** Read until there are at least min_len bytes in buffer.
199 * If for some reason this isn't possible, returns false upon EOF and
200 * otherwise throws NetworkError.
202 * @param min_len Minimum number of bytes required in buffer.
203 * @param end_time If this time is reached, then a timeout
204 * exception will be thrown. If (end_time == 0.0),
205 * then keep trying indefinitely.
207 * @return false on EOF, otherwise true.
209 bool read_at_least(size_t min_len, double end_time);
211 #ifdef __WIN32__
212 /** On Windows we use overlapped IO. We share an overlapped structure
213 * for both reading and writing, as we know that we always wait for
214 * one to finish before starting another (ie, we don't *really* use
215 * overlapped IO - no IO is overlapped - its used only to manage timeouts)
217 WSAOVERLAPPED overlapped;
219 /** Calculate how many milliseconds a read should wait.
221 * This will raise a timeout exception if end_time has already passed.
223 DWORD calc_read_wait_msecs(double end_time);
224 #endif
226 protected:
227 /** The context to report with errors.
229 * Subclasses are allowed to manage this.
231 std::string context;
233 public:
234 /// Constructor.
235 RemoteConnection(int fdin_, int fdout_,
236 const std::string & context_ = std::string());
238 #ifdef __WIN32__
239 /// Destructor
240 ~RemoteConnection();
241 #endif
243 /** See if there is data available to read.
245 * @return true if there is data waiting to be read.
247 bool ready_to_read() const;
249 /** Check what the next message type is.
251 * This must not be called after a call to get_message_chunked() until
252 * get_message_chunk() has returned 0 to indicate the whole message
253 * has been received.
255 * Other than that restriction, this may be called at any time to
256 * determine what the next message waiting to be processed is: it will not
257 * affect subsequent calls which read messages.
259 * @param end_time If this time is reached, then a timeout
260 * exception will be thrown. If
261 * (end_time == 0.0) then the operation will
262 * never timeout.
264 * @return Message type code or -1 for EOF.
266 int sniff_next_message_type(double end_time);
268 /** Read one message from fdin.
270 * @param[out] result Message data.
271 * @param end_time If this time is reached, then a timeout
272 * exception will be thrown. If
273 * (end_time == 0.0) then the operation will
274 * never timeout.
276 * @return Message type code or -1 for EOF.
278 int get_message(std::string &result, double end_time);
280 /** Prepare to read one message from fdin in chunks.
282 * Sometimes a message can be sufficiently large that you don't want to
283 * read it all into memory before processing it. Also, it may be more
284 * efficient to process it as you go.
286 * This method doesn't actually return any message data - call
287 * get_message_chunk() to do that.
289 * @param end_time If this time is reached, then a timeout
290 * exception will be thrown. If
291 * (end_time == 0.0) then the operation will
292 * never timeout.
294 * @return Message type code or -1 for EOF.
296 int get_message_chunked(double end_time);
298 /** Read a chunk of a message from fdin.
300 * You must call get_message_chunked() before calling this method.
302 * @param[in,out] result Message data. This is appended to, so if you
303 * read more than needed the previous time, leave
304 * the excess in result.
305 * @param at_least Return at least this many bytes in result,
306 * unless there isn't enough data left in the
307 * message (in which case all remaining data is
308 * read and 0 is returned).
309 * @param end_time If this time is reached, then a timeout
310 * exception will be thrown. If
311 * (end_time == 0.0) then the operation will
312 * never timeout.
314 * @return 1 if at least at_least bytes are now in result;
315 * -1 on EOF on the connection; 0 for having read
316 * < at_least bytes, but finished the message.
318 int get_message_chunk(std::string &result, size_t at_least,
319 double end_time);
321 /** Save the contents of a message as a file.
323 * @param file Path to file to save the message data into. If
324 * the file exists it will be overwritten.
325 * @param end_time If this time is reached, then a timeout
326 * exception will be thrown. If
327 * (end_time == 0.0) then the operation will
328 * never timeout.
330 * @return Message type code or -1 for EOF.
332 int receive_file(const std::string &file, double end_time);
334 /** Send a message.
336 * @param type Message type code.
337 * @param s Message data.
338 * @param end_time If this time is reached, then a timeout
339 * exception will be thrown. If
340 * (end_time == 0.0) then the operation will
341 * never timeout.
343 void send_message(char type, const std::string & s, double end_time);
345 /** Send the contents of a file as a message.
347 * @param type Message type code.
348 * @param fd File containing the message data.
349 * @param end_time If this time is reached, then a timeout
350 * exception will be thrown. If
351 * (end_time == 0.0) then the operation will
352 * never timeout.
354 void send_file(char type, int fd, double end_time);
356 /** Shutdown the connection.
358 * @param wait If true, wait for the remote end to close the
359 * connection before returning.
361 void do_close(bool wait);
364 #endif // XAPIAN_INCLUDED_REMOTECONNECTION_H