1 /** @file remoteconnection.h
2 * @brief RemoteConnection class used by the remote backend.
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
26 #include "remoteprotocol.h"
27 #include "safeerrno.h"
28 #include "safenetdb.h" // For EAI_* constants.
29 #include "safeunistd.h"
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() {
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?
57 throw Xapian::NetworkError("Failed to initialize winsock", wsaerror
);
61 ~WinsockInitializer() {
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();
78 case WSAEADDRINUSE
: return EADDRINUSE
;
81 case WSAETIMEDOUT
: return ETIMEDOUT
;
84 case WSAEINPROGRESS
: return EINPROGRESS
;
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.
94 # define EADDRINUSE WSAEADDRINUSE
97 # define ETIMEDOUT WSAETIMEDOUT
100 # define EINPROGRESS WSAEINPROGRESS
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)
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)
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.
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'"
134 #ifdef EAI_ADDRFAMILY
135 // In RFC 2553 but not RFC 3493 or POSIX:
139 // In RFC 2553 but not RFC 3493 or POSIX:
143 // In RFC 3493 and POSIX but not RFC 2553:
151 // EAI_SYSTEM means "look at errno".
154 // POSIX only says that EAI_* constants are "non-zero". On Linux they are
155 // negative, but allow for them being positive too.
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
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.
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.
191 /// Buffer to hold unprocessed input.
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
);
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
);
227 /** The context to report with errors.
229 * Subclasses are allowed to manage this.
235 RemoteConnection(int fdin_
, int fdout_
,
236 const std::string
& context_
= std::string());
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
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
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
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
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
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
,
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
330 * @return Message type code or -1 for EOF.
332 int receive_file(const std::string
&file
, double end_time
);
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
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
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