LCOV - code coverage report
Current view: top level - net - remoteconnection.h (source / functions) Hit Total Coverage
Test: Test Coverage for xapian-core fcfb185a9dd5 Lines: 3 8 37.5 %
Date: 2019-04-18 16:33:14 Functions: 3 4 75.0 %
Branches: 0 2 0.0 %

           Branch data     Line data    Source code
       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
       5                 :            :  *
       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.
      10                 :            :  *
      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.
      15                 :            :  *
      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
      19                 :            :  */
      20                 :            : 
      21                 :            : #ifndef XAPIAN_INCLUDED_REMOTECONNECTION_H
      22                 :            : #define XAPIAN_INCLUDED_REMOTECONNECTION_H
      23                 :            : 
      24                 :            : #include <cerrno>
      25                 :            : #include <string>
      26                 :            : 
      27                 :            : #include "remoteprotocol.h"
      28                 :            : #include "safenetdb.h" // For EAI_* constants.
      29                 :            : #include "safeunistd.h"
      30                 :            : 
      31                 :            : #ifdef __WIN32__
      32                 :            : # include "safewinsock2.h"
      33                 :            : 
      34                 :            : # include <xapian/error.h>
      35                 :            : 
      36                 :            : /** Class to initialise winsock and keep it initialised while we use it.
      37                 :            :  *
      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.
      44                 :            :  *
      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).
      48                 :            :  */
      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?
      55                 :            : 
      56                 :            :         if (wsaerror != 0) {
      57                 :            :             throw Xapian::NetworkError("Failed to initialize winsock", wsaerror);
      58                 :            :         }
      59                 :            :     }
      60                 :            : 
      61                 :            :     ~WinsockInitializer() {
      62                 :            :         WSACleanup();
      63                 :            :     }
      64                 :            : };
      65                 :            : 
      66                 :            : /** Get the errno value of the last error to occur due to a socket operation.
      67                 :            :  *
      68                 :            :  *  This is specific to the calling thread.
      69                 :            :  *
      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.
      73                 :            :  */
      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;
      87                 :            :     }
      88                 :            : }
      89                 :            : 
      90                 :            : /* Newer compilers define these, in which case we map to those already defined
      91                 :            :  * values in socket_errno() above.
      92                 :            :  */
      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
     102                 :            : 
     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                 :        800 : inline int socket_errno() { return errno; }
     108                 :            : 
     109                 :            : # define CLOSESOCKET(S) close(S)
     110                 :            : #endif
     111                 :            : 
     112                 :          0 : inline int eai_to_xapian(int e) {
     113                 :            :     // Under WIN32, the EAI_* constants are defined to be WSA_* constants with
     114                 :            :     // roughly equivalent meanings, so we can just let them be handled as any
     115                 :            :     // other WSA_* error codes would be.
     116                 :            : #ifndef __WIN32__
     117                 :            :     // Ensure they all have the same sign - this switch will fail to compile if
     118                 :            :     // we bitwise-or some 1 and some 2 bits to get 3.
     119                 :            : #define C(X) ((X) < 0 ? 2 : 1)
     120                 :            :     // Switch on a value there is a case for, to avoid clang warning:
     121                 :            :     // "no case matching constant switch condition '0'"
     122                 :            :     switch (3) {
     123                 :            :         case
     124                 :            :             C(EAI_AGAIN)|
     125                 :            :             C(EAI_BADFLAGS)|
     126                 :            :             C(EAI_FAIL)|
     127                 :            :             C(EAI_FAMILY)|
     128                 :            :             C(EAI_MEMORY)|
     129                 :            :             C(EAI_NONAME)|
     130                 :            :             C(EAI_SERVICE)|
     131                 :            :             C(EAI_SOCKTYPE)|
     132                 :            :             C(EAI_SYSTEM)|
     133                 :            : #ifdef EAI_ADDRFAMILY
     134                 :            :             // In RFC 2553 but not RFC 3493 or POSIX:
     135                 :            :             C(EAI_ADDRFAMILY)|
     136                 :            : #endif
     137                 :            : #ifdef EAI_NODATA
     138                 :            :             // In RFC 2553 but not RFC 3493 or POSIX:
     139                 :            :             C(EAI_NODATA)|
     140                 :            : #endif
     141                 :            : #ifdef EAI_OVERFLOW
     142                 :            :             // In RFC 3493 and POSIX but not RFC 2553:
     143                 :            :             C(EAI_OVERFLOW)|
     144                 :            : #endif
     145                 :            :             0: break;
     146                 :          0 :         case 3: break;
     147                 :            :     }
     148                 :            : #undef C
     149                 :            : 
     150                 :            :     // EAI_SYSTEM means "look at errno".
     151         [ #  # ]:          0 :     if (e == EAI_SYSTEM)
     152                 :          0 :         return errno;
     153                 :            :     // POSIX only says that EAI_* constants are "non-zero".  On Linux they are
     154                 :            :     // negative, but allow for them being positive too.
     155                 :            :     if (EAI_FAIL > 0)
     156                 :            :         return -e;
     157                 :            : #endif
     158                 :          0 :     return e;
     159                 :            : }
     160                 :            : 
     161                 :            : /** A RemoteConnection object provides a bidirectional connection to another
     162                 :            :  *  RemoteConnection object on a remote machine.
     163                 :            :  *
     164                 :            :  *  The connection is implemented using a pair of file descriptors.  Messages
     165                 :            :  *  with a single byte type code and arbitrary data as the contents can be
     166                 :            :  *  sent and received.
     167                 :            :  */
     168                 :       3040 : class RemoteConnection {
     169                 :            :     /// Don't allow assignment.
     170                 :            :     void operator=(const RemoteConnection &);
     171                 :            : 
     172                 :            :     /// Don't allow copying.
     173                 :            :     RemoteConnection(const RemoteConnection &);
     174                 :            : 
     175                 :            :     /** The file descriptor used for reading.
     176                 :            :      *
     177                 :            :      *  If this is -1, the connection is unidirectional and write-only.
     178                 :            :      *  If both fdin and fdout are -1, then the connection has been closed.
     179                 :            :      */
     180                 :            :     int fdin;
     181                 :            : 
     182                 :            :     /** The file descriptor used for writing.
     183                 :            :      *
     184                 :            :      *  If this is -1, the connection is unidirectional and read-only.
     185                 :            :      *  If both fdin and fdout are -1, then the connection has been closed.
     186                 :            :      *  It is valid for fdout to be the same as fdin.
     187                 :            :      */
     188                 :            :     int fdout;
     189                 :            : 
     190                 :            :     /// Buffer to hold unprocessed input.
     191                 :            :     std::string buffer;
     192                 :            : 
     193                 :            :     /// Remaining bytes of message data still to come over fdin for a chunked read.
     194                 :            :     off_t chunked_data_left;
     195                 :            : 
     196                 :            :     /** Read until there are at least min_len bytes in buffer.
     197                 :            :      *
     198                 :            :      *  If for some reason this isn't possible, returns false upon EOF and
     199                 :            :      *  otherwise throws NetworkError.
     200                 :            :      *
     201                 :            :      *  @param min_len  Minimum number of bytes required in buffer.
     202                 :            :      *  @param end_time If this time is reached, then a timeout
     203                 :            :      *                  exception will be thrown.  If (end_time == 0.0),
     204                 :            :      *                  then keep trying indefinitely.
     205                 :            :      *
     206                 :            :      *  @return false on EOF, otherwise true.
     207                 :            :      */
     208                 :            :     bool read_at_least(size_t min_len, double end_time);
     209                 :            : 
     210                 :            : #ifdef __WIN32__
     211                 :            :     /** On Windows we use overlapped IO.  We share an overlapped structure
     212                 :            :      *  for both reading and writing, as we know that we always wait for
     213                 :            :      *  one to finish before starting another (ie, we don't *really* use
     214                 :            :      *  overlapped IO - no IO is overlapped - its used only to manage timeouts)
     215                 :            :      */
     216                 :            :     WSAOVERLAPPED overlapped;
     217                 :            : 
     218                 :            :     /** Calculate how many milliseconds a read should wait.
     219                 :            :      *
     220                 :            :      *  This will raise a timeout exception if end_time has already passed.
     221                 :            :      */
     222                 :            :     DWORD calc_read_wait_msecs(double end_time);
     223                 :            : #endif
     224                 :            : 
     225                 :            :   protected:
     226                 :            :     /** The context to report with errors.
     227                 :            :      *
     228                 :            :      *  Subclasses are allowed to manage this.
     229                 :            :      */
     230                 :            :     std::string context;
     231                 :            : 
     232                 :            :   public:
     233                 :            :     /// Constructor.
     234                 :            :     RemoteConnection(int fdin_, int fdout_,
     235                 :            :                      const std::string & context_ = std::string());
     236                 :            : 
     237                 :            : #ifdef __WIN32__
     238                 :            :     /// Destructor
     239                 :            :     ~RemoteConnection();
     240                 :            : #endif
     241                 :            : 
     242                 :            :     /** Return the underlying fd this remote connection reads from. */
     243                 :        168 :     int get_read_fd() const { return fdin; }
     244                 :            : 
     245                 :            :     /** Check what the next message type is.
     246                 :            :      *
     247                 :            :      *  This must not be called after a call to get_message_chunked() until
     248                 :            :      *  get_message_chunk() has returned 0 to indicate the whole message
     249                 :            :      *  has been received.
     250                 :            :      *
     251                 :            :      *  Other than that restriction, this may be called at any time to
     252                 :            :      *  determine what the next message waiting to be processed is: it will not
     253                 :            :      *  affect subsequent calls which read messages.
     254                 :            :      *
     255                 :            :      *  @param end_time         If this time is reached, then a timeout
     256                 :            :      *                          exception will be thrown.  If
     257                 :            :      *                          (end_time == 0.0) then the operation will
     258                 :            :      *                          never timeout.
     259                 :            :      *
     260                 :            :      *  @return                 Message type code or -1 for EOF.
     261                 :            :      */
     262                 :            :     int sniff_next_message_type(double end_time);
     263                 :            : 
     264                 :            :     /** Read one message from fdin.
     265                 :            :      *
     266                 :            :      *  @param[out] result      Message data.
     267                 :            :      *  @param end_time         If this time is reached, then a timeout
     268                 :            :      *                          exception will be thrown.  If
     269                 :            :      *                          (end_time == 0.0) then the operation will
     270                 :            :      *                          never timeout.
     271                 :            :      *
     272                 :            :      *  @return                 Message type code or -1 for EOF.
     273                 :            :      */
     274                 :            :     int get_message(std::string &result, double end_time);
     275                 :            : 
     276                 :            :     /** Prepare to read one message from fdin in chunks.
     277                 :            :      *
     278                 :            :      *  Sometimes a message can be sufficiently large that you don't want to
     279                 :            :      *  read it all into memory before processing it.  Also, it may be more
     280                 :            :      *  efficient to process it as you go.
     281                 :            :      *
     282                 :            :      *  This method doesn't actually return any message data - call
     283                 :            :      *  get_message_chunk() to do that.
     284                 :            :      *
     285                 :            :      *  @param end_time         If this time is reached, then a timeout
     286                 :            :      *                          exception will be thrown.  If
     287                 :            :      *                          (end_time == 0.0) then the operation will
     288                 :            :      *                          never timeout.
     289                 :            :      *
     290                 :            :      *  @return                 Message type code or -1 for EOF.
     291                 :            :      */
     292                 :            :     int get_message_chunked(double end_time);
     293                 :            : 
     294                 :            :     /** Read a chunk of a message from fdin.
     295                 :            :      *
     296                 :            :      *  You must call get_message_chunked() before calling this method.
     297                 :            :      *
     298                 :            :      *  @param[in,out] result   Message data.  This is appended to, so if you
     299                 :            :      *                          read more than needed the previous time, leave
     300                 :            :      *                          the excess in result.
     301                 :            :      *  @param at_least         Return at least this many bytes in result,
     302                 :            :      *                          unless there isn't enough data left in the
     303                 :            :      *                          message (in which case all remaining data is
     304                 :            :      *                          read and 0 is returned).
     305                 :            :      *  @param end_time         If this time is reached, then a timeout
     306                 :            :      *                          exception will be thrown.  If
     307                 :            :      *                          (end_time == 0.0) then the operation will
     308                 :            :      *                          never timeout.
     309                 :            :      *
     310                 :            :      *  @return                 1 if at least at_least bytes are now in result;
     311                 :            :      *                          -1 on EOF on the connection; 0 for having read
     312                 :            :      *                          < at_least bytes, but finished the message.
     313                 :            :      */
     314                 :            :     int get_message_chunk(std::string &result, size_t at_least,
     315                 :            :                           double end_time);
     316                 :            : 
     317                 :            :     /** Save the contents of a message as a file.
     318                 :            :      *
     319                 :            :      *  @param file             Path to file to save the message data into.  If
     320                 :            :      *                          the file exists it will be overwritten.
     321                 :            :      *  @param end_time         If this time is reached, then a timeout
     322                 :            :      *                          exception will be thrown.  If
     323                 :            :      *                          (end_time == 0.0) then the operation will
     324                 :            :      *                          never timeout.
     325                 :            :      *
     326                 :            :      *  @return                 Message type code or -1 for EOF.
     327                 :            :      */
     328                 :            :     int receive_file(const std::string &file, double end_time);
     329                 :            : 
     330                 :            :     /** Send a message.
     331                 :            :      *
     332                 :            :      *  @param type             Message type code.
     333                 :            :      *  @param s                Message data.
     334                 :            :      *  @param end_time         If this time is reached, then a timeout
     335                 :            :      *                          exception will be thrown.  If
     336                 :            :      *                          (end_time == 0.0) then the operation will
     337                 :            :      *                          never timeout.
     338                 :            :      */
     339                 :            :     void send_message(char type, const std::string & s, double end_time);
     340                 :            : 
     341                 :            :     /** Send the contents of a file as a message.
     342                 :            :      *
     343                 :            :      *  @param type             Message type code.
     344                 :            :      *  @param fd               File containing the message data.
     345                 :            :      *  @param end_time         If this time is reached, then a timeout
     346                 :            :      *                          exception will be thrown.  If
     347                 :            :      *                          (end_time == 0.0) then the operation will
     348                 :            :      *                          never timeout.
     349                 :            :      */
     350                 :            :     void send_file(char type, int fd, double end_time);
     351                 :            : 
     352                 :            :     /** Shutdown the connection.
     353                 :            :      *
     354                 :            :      *  @param wait     If true, wait for the remote end to close the
     355                 :            :      *                  connection before returning.
     356                 :            :      */
     357                 :            :     void do_close(bool wait);
     358                 :            : };
     359                 :            : 
     360                 :            : #endif // XAPIAN_INCLUDED_REMOTECONNECTION_H

Generated by: LCOV version 1.11