int WdtSocket::readWithTimeout()

in util/WdtSocket.cpp [310:371]


int WdtSocket::readWithTimeout(char *buf, int nbyte, int timeoutMs,
                               bool tryFull) {
  WDT_CHECK_GT(nbyte, 0);
  if (readErrorCode_ != OK && readErrorCode_ != WDT_TIMEOUT) {
    WLOG(ERROR) << "Socket read failed before, not trying to read again "
                << port_;
    return -1;
  }
  readErrorCode_ = OK;
  int numRead = 0;

  // first try to find encryption settings
  readEncryptionSettingsOnce(timeoutMs);
  if (supportUnencryptedPeer_ && readErrorCode_ == UNEXPECTED_CMD_ERROR) {
    WLOG(WARNING)
        << "Turning off encryption since the other side does not support "
           "encryption "
        << port_;
    readErrorCode_ = OK;
    buf[0] = buf_[0];
    numRead = 1;
    // also turn off encryption
    encryptionParams_.erase();
  } else if (readErrorCode_ != OK) {
    return -1;
  }

  const bool encrypt = encryptionParams_.isSet();
  if (!encrypt) {
    // handle the non-encryption case
    int ret = readInternal(buf + numRead, nbyte - numRead, timeoutMs, tryFull);
    if (ret >= 0) {
      return numRead + ret;
    }
    // read failure
    return (numRead > 0 ? numRead : -1);
  }

  // handle encryption case
  WDT_CHECK_EQ(0, numRead);
  if (readTagInterval_ <= 0) {
    return readAndDecrypt(buf, nbyte, timeoutMs, tryFull);
  }
  // tag verification enabled
  // have to break the read in chunks of readTagInterval_
  while (numRead < nbyte) {
    const int remaining = nbyte - numRead;
    const int toRead = std::min(remaining, readTagInterval_);
    const int ret =
        readAndDecryptWithTag(buf + numRead, toRead, timeoutMs, tryFull);
    if (ret <= 0) {
      // read error
      return (numRead > 0 ? numRead : ret);
    }
    numRead += ret;
    if (ret < toRead) {
      // couldn't read full data
      return numRead;
    }
  }
  return numRead;
}