Exemple #1
0
void connectProc(aioInfo *info)
{
  SSLOp *Op = (SSLOp*)info->arg;
  SSLSocket *S = Op->info.socket;
  if (info->status == aosSuccess) {
    if (Op->state == sslStReadNewFrame) {
      BIO_write(S->bioIn, S->sslReadBuffer, info->bytesTransferred);
      Op->state = sslStConnecting;
    }

    int connectResult = SSL_connect(S->ssl);
    int errCode = SSL_get_error(S->ssl, connectResult);
    if (connectResult == 1) {
      // Successfully connected
      finishSSLOp(Op, aosSuccess);
    } else if (errCode == SSL_ERROR_WANT_READ) {
      // Need data exchange
      size_t connectSize = copyFromOut(S, Op);
      Op->state = sslStReadNewFrame;
      asyncWrite(S->object, Op->sslBuffer, connectSize, afNone, 3000000, 0, 0);
      asyncRead(S->object, S->sslReadBuffer, S->sslReadBufferSize, afNone, 3000000, connectProc, Op);
    } else {
      finishSSLOp(Op, aosUnknownError);          
    }
  } else {
    finishSSLOp(Op, info->status);
  }
}
Exemple #2
0
void sslRead(SSLSocket *socket,
             void *buffer,
             size_t size,
             AsyncFlags flags,
             uint64_t usTimeout,
             sslCb callback,
             void *arg)
{
  size_t readSize = BIO_ctrl_pending(socket->bioIn);

  SSLOp *newOp = allocSSLOp(socket, callback, arg, buffer, size, afNone);  
  newOp->type = sslOpRead;
  newOp->state = sslStReadNewFrame;

  if (readSize >= size) {
    BIO_read(socket->bioOut, buffer, size);
    finishSSLOp(newOp, aosSuccess);
  } else if (!socket->current) {
    socket->current = newOp;
    asyncRead(socket->object, socket->sslReadBuffer, socket->sslReadBufferSize, afNone, usTimeout, readProc, newOp);
  } else {
    newOp->usTimeout = usTimeout;
    socket->current->next = newOp;
  }
}
Exemple #3
0
void readProc(aioInfo *info)
{
  SSLOp *Op = (SSLOp*)info->arg;
  SSLSocket *S = Op->info.socket;
  if (info->status == aosSuccess) {
    if (Op->state == sslStReadNewFrame) {
      BIO_write(S->bioIn, S->sslReadBuffer, info->bytesTransferred);
      Op->state = sslStReading;
    }
    
    uint8_t *ptr = ((uint8_t*)Op->info.buffer) + Op->info.bytesTransferred;
    size_t size = Op->info.transactionSize-Op->info.bytesTransferred;
    
    int readResult = 0;
    int R;
    while ( (R = SSL_read(S->ssl, ptr, size)) > 0) {
      readResult += R;
      ptr += R;
      size -= R;
    }
    
    Op->info.bytesTransferred += readResult;
    if (Op->info.bytesTransferred == Op->info.transactionSize || (Op->info.bytesTransferred && !(Op->info.flags & afWaitAll))) {
      finishSSLOp(Op, aosSuccess);
    } else {
      Op->state = sslStReadNewFrame;
      asyncRead(S->object, S->sslReadBuffer, S->sslReadBufferSize, afNone, 3000000, readProc, Op);
    }    
  } else {
    finishSSLOp(Op, info->status);
  }
}
Exemple #4
0
void AsyncFile::readFinished(qint64 bytes)
{
    reading = false;
    m_readBuffer.append(QByteArray(overlapped.buffer, bytes));
//    memset(overlapped.buffer, 0, BUFFER_SIZE);

    emit readyRead();
//    QMetaObject::invokeMethod(this, "asyncRead", Qt::QueuedConnection);
    asyncRead(pos());
}
Exemple #5
0
void ChatClient::handleConnect(const boost::system::error_code& error,
                               Sctp::ip::sctp::resolver_iterator iterator)
{
    if (error) {
        LOG(info) << "Connect error";
        close();
        connectAsyncNext(iterator);
        return;
    }

    asyncRead();
    asyncReadFromStdin();
}
void BasicConnection::receive( const std::size_t size, ReceiveCallback callback ){
   // Read the message asynchronously.
   const BufferMap::key_type bufferId = ++m_bufferCounter;
   asyncRead(
        m_bufferMap[ bufferId ].resize( size ),
        std::bind(
            &BasicConnection::_receiveComplete,
            shared_from_this(),
            bufferId,
            callback,
            std::placeholders::_1,
            std::placeholders::_2 )
    );
}
Exemple #7
0
void ChatClient::handleRead(const boost::system::error_code& error,
                            size_t length)
{
    if (error) {
        LOG(info) << "Read error";
        close();
        return;
    }

    m_messageBuffer.sgetn(m_buffer, length);
    writeOutputPrompt();
    std::cout << m_buffer << std::flush;
    writeInputPrompt();

    asyncRead();
}
Exemple #8
0
qint64 AsyncFile::readData(char *data, qint64 maxlen)
{
    qint64 size = qMin((qint64)m_readBuffer.size(), maxlen);
    qDebug() << "readData" << maxlen << size;
    if (size == 0)
        return 0;
    qDebug() << pos() + maxlen << this->size();
//    Q_ASSERT(pos() + maxlen <= this->size());

    memcpy(data, m_readBuffer.data(), size);
    m_readBuffer.remove(0, size);
    Q_ASSERT(m_readBuffer.isEmpty());

    asyncRead(pos() + size);

    return size;
}
Exemple #9
0
void
EthernetChannel::handleRead(const boost::system::error_code& error,
                            const FaceCreatedCallback& onFaceCreated,
                            const FaceCreationFailedCallback& onReceiveFailed)
{
  if (error) {
    if (error != boost::asio::error::operation_aborted) {
      NFD_LOG_CHAN_DEBUG("Receive failed: " << error.message());
      if (onReceiveFailed)
        onReceiveFailed(500, "Receive failed: " + error.message());
    }
    return;
  }

  const uint8_t* pkt;
  size_t len;
  std::string err;
  std::tie(pkt, len, err) = m_pcap.readNextPacket();

  if (pkt == nullptr) {
    NFD_LOG_CHAN_WARN("Read error: " << err);
  }
  else {
    const ether_header* eh;
    std::tie(eh, err) = ethernet::checkFrameHeader(pkt, len, m_localEndpoint->getEthernetAddress(),
                                                   m_localEndpoint->getEthernetAddress());
    if (eh == nullptr) {
      NFD_LOG_CHAN_DEBUG(err);
    }
    else {
      ethernet::Address sender(eh->ether_shost);
      pkt += ethernet::HDR_LEN;
      len -= ethernet::HDR_LEN;
      processIncomingPacket(pkt, len, sender, onFaceCreated, onReceiveFailed);
    }
  }

#ifdef _DEBUG
  size_t nDropped = m_pcap.getNDropped();
  if (nDropped - m_nDropped > 0)
    NFD_LOG_CHAN_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
  m_nDropped = nDropped;
#endif

  asyncRead(onFaceCreated, onReceiveFailed);
}
Exemple #10
0
static void finishSSLOp(SSLOp *Op, AsyncOpStatus status)
{
  SSLOp *current = Op->next;
  if (Op->type != sslOpWrite)
    Op->info.socket->current = current;
 
  Op->info.status = status;
  if (Op->info.callback)
    Op->info.callback(&Op->info);
  releaseObject(Op->info.socket->base, Op, sslPoolId);
  if (current && Op->type != sslOpWrite) {
    SSLSocket *S = current->info.socket;
    switch (current->type) {
      case sslOpConnect :
        asyncConnect(S->object, &current->address, current->usTimeout, connectProc, current);
        break;
      case sslOpRead :
        asyncRead(S->object, S->sslReadBuffer, S->sslReadBufferSize, afNone, current->usTimeout, readProc, current);
        break;
    }
  }
}
Exemple #11
0
void
EthernetChannel::listen(const FaceCreatedCallback& onFaceCreated,
                        const FaceCreationFailedCallback& onFaceCreationFailed)
{
  if (isListening()) {
    NFD_LOG_CHAN_WARN("Already listening");
    return;
  }
  m_isListening = true;

  try {
    m_pcap.activate(DLT_EN10MB);
    m_socket.assign(m_pcap.getFd());
  }
  catch (const PcapHelper::Error& e) {
    NDN_THROW_NESTED(Error(e.what()));
  }
  updateFilter();

  asyncRead(onFaceCreated, onFaceCreationFailed);
  NFD_LOG_CHAN_DEBUG("Started listening");
}
Exemple #12
0
bool AsyncFile::open(QIODevice::OpenMode mode)
{
#ifdef Q_OS_WIN
    m_FileHandle = CreateFile(reinterpret_cast<wchar_t *>(QString(m_filePath).data()), // file to open
                              GENERIC_READ,           // open for reading
                              FILE_SHARE_READ,        // share for reading
                              NULL,                   // default security
                              OPEN_EXISTING,          // existing file only
                              FILE_FLAG_OVERLAPPED,   // overlapped operation
                              NULL);                  // no attr. template

    if (m_FileHandle == INVALID_HANDLE_VALUE) {
        setError(QFileDevice::OpenError, errorMessage(GetLastError()));
        return false;
    }

    if (!asyncRead(pos())) {
        setError(QFileDevice::OpenError, errorMessage(GetLastError()));
        return false;
    }
#endif

    return QIODevice::open(mode | QIODevice::Unbuffered);
}
void KConnectionSelectable::read(KHttpRequest *rq,resultEvent result,bufferEvent buffer,int list)
{
	
	rq->c->selector->addList(rq,list);
	asyncRead(rq,result,buffer);
}
Exemple #14
0
   // PD_TRACE_DECLARE_FUNCTION ( SDB__NETEVNHND__RDCALLBK, "_netEventHandler::_readCallback" )
   void _netEventHandler::_readCallback( const boost::system::error_code &
                                         error )
   {
      PD_TRACE_ENTRY ( SDB__NETEVNHND__RDCALLBK ) ;

      if ( error )
      {
         if ( error.value() == boost::system::errc::operation_canceled ||
              error.value() == boost::system::errc::no_such_file_or_directory )
         {
            PD_LOG ( PDINFO, "connection aborted, node:%d, %d, %d",
                     _id.columns.groupID, _id.columns.nodeID,
                     _id.columns.serviceID ) ;
         }
         else
         {
            PD_LOG ( PDERROR, "Error received, node:%d, %d, %d, err=%d",
                     _id.columns.groupID, _id.columns.nodeID,
                     _id.columns.serviceID, error.value() ) ;
         }

         goto error_close ;
      }

      if ( NET_EVENT_HANDLER_STATE_HEADER == _state )
      {
         if ( ( UINT32 )MSG_SYSTEM_INFO_LEN == (UINT32)_header.messageLength )
         {
            if ( SDB_OK != _allocateBuf( sizeof(MsgSysInfoRequest) ))
            {
               goto error_close ;
            }
            _hasRecvMsg = TRUE ;
            ossMemcpy( _buf, &_header, sizeof( MsgSysInfoRequest ) ) ;
            _frame->handleMsg( shared_from_this() ) ;
            _state = NET_EVENT_HANDLER_STATE_HEADER ;
            asyncRead() ;
            goto done ;
         }
         else if ( sizeof(_MsgHeader) > (UINT32)_header.messageLength ||
                   SDB_MAX_MSG_LENGTH < (UINT32)_header.messageLength )
         {
            PD_LOG( PDERROR, "Error header[len: %d, opCode: (%d)%d, TID:%d] "
                    "received, node:%d, %d, %d", _header.messageLength,
                    IS_REPLY_TYPE(_header.opCode) ? 1 : 0,
                    GET_REQUEST_TYPE(_header.opCode), _header.TID,
                    _id.columns.groupID,
                    _id.columns.nodeID, _id.columns.serviceID ) ;
            goto error_close ;
         }
         else
         {
            if ( FALSE == _hasRecvMsg )
            {
               _hasRecvMsg = TRUE ;
               _state = NET_EVENT_HANDLER_STATE_HEADER_LAST ;
               asyncRead() ;
               _state = NET_EVENT_HANDLER_STATE_HEADER ;
               goto done ;
            }

            PD_LOG( PDDEBUG, "msg header: [len:%d], [opCode: [%d]%d], "
                             "[TID:%d], [groupID:%d], [nodeID:%d], "
                             "[ADDR:%s], [PORT:%d]",
                    _header.messageLength, IS_REPLY_TYPE(_header.opCode)?1:0,
                    GET_REQUEST_TYPE(_header.opCode),
                    _header.TID, _header.routeID.columns.groupID,
                    _header.routeID.columns.nodeID,
                    remoteAddr().c_str(), remotePort() ) ;
            if ( MSG_INVALID_ROUTEID == _id.value )
            {
               if ( MSG_INVALID_ROUTEID != _header.routeID.value )
               {
                  _id = _header.routeID ;
                  _frame->_addRoute( shared_from_this() ) ;
               }
            }
         }
         if ( (UINT32)sizeof(_MsgHeader) == (UINT32)_header.messageLength )
         {
            if ( SDB_OK != _allocateBuf( sizeof(_MsgHeader) ))
            {
               goto error_close ;
            }
            ossMemcpy( _buf, &_header, sizeof( _MsgHeader ) ) ;
            _frame->handleMsg( shared_from_this() ) ;
            _state = NET_EVENT_HANDLER_STATE_HEADER ;
            asyncRead() ;
            goto done ;
         }

#if defined (_LINUX)
         try
         {
            boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_QUICKACK>
                                                    quickack( TRUE ) ;
            _sock.set_option( quickack ) ;
         }
         catch ( boost::system::system_error &e )
         {
            PD_LOG ( PDERROR, "Failed to quick ack: %s", e.what() ) ;
         }
#endif // _LINUX

         _state = NET_EVENT_HANDLER_STATE_BODY ;
         asyncRead() ;
      }
      else
      {
         _frame->handleMsg( shared_from_this() ) ;
         _state = NET_EVENT_HANDLER_STATE_HEADER ;
         asyncRead() ;
      }

   done:
      PD_TRACE_EXIT ( SDB__NETEVNHND__RDCALLBK ) ;
      return ;
   error_close:
      if ( _isConnected )
      {
         close() ;
      }
      _frame->handleClose( shared_from_this(), _id ) ;
      _frame->_erase( handle() ) ;
      goto done ;
   }