Esempio n. 1
0
void TFileTransport::seekToChunk(int32_t chunk) {
  if (fd_ <= 0) {
    throw TTransportException("File not open");
  }

  int32_t numChunks = getNumChunks();

  // file is empty, seeking to chunk is pointless
  if (numChunks == 0) {
    return;
  }

  // negative indicates reverse seek (from the end)
  if (chunk < 0) {
    chunk += numChunks;
  }

  // too large a value for reverse seek, just seek to beginning
  if (chunk < 0) {
    T_DEBUG("%s", "Incorrect value for reverse seek. Seeking to beginning...");
    chunk = 0;
  }

  // cannot seek past EOF
  bool seekToEnd = false;
  off_t minEndOffset = 0;
  if (chunk >= numChunks) {
    T_DEBUG("%s", "Trying to seek past EOF. Seeking to EOF instead...");
    seekToEnd = true;
    chunk = numChunks - 1;
    // this is the min offset to process events till
    minEndOffset = lseek(fd_, 0, SEEK_END);
  }

  off_t newOffset = off_t(chunk) * chunkSize_;
  offset_ = lseek(fd_, newOffset, SEEK_SET);
  readState_.resetAllValues();
  currentEvent_ = NULL;
  if (offset_ == -1) {
    GlobalOutput("TFileTransport: lseek error in seekToChunk");
    throw TTransportException("TFileTransport: lseek error in seekToChunk");
  }

  // seek to EOF if user wanted to go to last chunk
  if (seekToEnd) {
    uint32_t oldReadTimeout = getReadTimeout();
    setReadTimeout(NO_TAIL_READ_TIMEOUT);
    // keep on reading unti the last event at point of seekChunk call
    boost::scoped_ptr<eventInfo> event;
    while ((offset_ + readState_.bufferPtr_) < minEndOffset) {
      event.reset(readEvent());
      if (event.get() == NULL) {
        break;
      }
    }
    setReadTimeout(oldReadTimeout);
  }

}
Esempio n. 2
0
    void Connection::onWrite( )
    {
        TRACE_ENTERLEAVE( );

        if ( !m_initialized )
        {
            //
            //  set timeouts if needed
            //
            if ( m_thread.server( ).getConnectionReadTimeout( ) > 0 )
            {
                setReadTimeout( m_thread.server( ).getConnectionReadTimeout( ) );
            }

            if ( m_thread.server( ).getConnectionWriteTimeout( ) > 0 )
            {
                setWriteTimeout( m_thread.server( ).getConnectionWriteTimeout( ) );
            }
        }

        if ( m_close )
        {
            disable( );
            onClose( );
        }
    }
Esempio n. 3
0
// --------------------------------------------------
void UClientSocket::close()
{
	sockLock.on();
	if (sockNum)
	{
		// signal shutdown
		shutdown(sockNum,SHUT_WR);

		// skip remaining data and wait for 0 from recv
		setReadTimeout(2000);
		unsigned int stime = sys->getTime();
		try
		{
			char c[1024];
			while (read(&c, sizeof(c)) > 0)
				if (sys->getTime() - stime > 5)
					break;
		}catch(StreamException &e) 
		{
			LOG_ERROR("Socket close: %s",e.msg);
		}
		// close handle
		::close(sockNum);

		sockNum = 0;
	}
	sockLock.off();
}
Esempio n. 4
0
void TcpConnection::startAsyncReadBody(Buffer& buffer, int timeout)
{
  LOG_DEBUG(socket().native() << ": startAsyncReadBody");
  setReadTimeout(timeout);

  boost::shared_ptr<TcpConnection> sft 
    = boost::dynamic_pointer_cast<TcpConnection>(shared_from_this());
  socket_.async_read_some(asio::buffer(buffer),
			  boost::bind(&Connection::handleReadBody,
				      sft,
				      asio::placeholders::error,
				      asio::placeholders::bytes_transferred));
}
Esempio n. 5
0
bool mdtTcpSocket::open(mdtPortConfig &cfg)
{
  // Close previous opened connection
  close();
  // Open new connection
  lockMutex();
  qDebug() << "Open ....";

  // Set R/W timeouts
  setReadTimeout(cfg.readTimeout());
  setWriteTimeout(cfg.writeTimeout());

  return mdtAbstractPort::open(cfg);
}
Esempio n. 6
0
void SslConnection::startAsyncReadRequest(Buffer& buffer, int timeout)
{
  if (state_ & Reading) {
    stop();
    return;
  }

  setReadTimeout(timeout);

  boost::shared_ptr<SslConnection> sft 
    = boost::dynamic_pointer_cast<SslConnection>(shared_from_this());
  socket_.async_read_some(asio::buffer(buffer),
			  strand_.wrap
			  (boost::bind(&SslConnection::handleReadRequestSsl,
				       sft,
				       asio::placeholders::error,
				       asio::placeholders::bytes_transferred)));
}
Esempio n. 7
0
// --------------------------------------------------
void WSAClientSocket::close()
{
	if (sockNum)
	{
		shutdown(sockNum,SD_SEND);

		setReadTimeout(2000);
		try
		{
			//char c;
			//while (readUpto(&c,1)!=0);
			//readUpto(&c,1);
		}catch(StreamException &) {}

		if (closesocket(sockNum))
			LOG_ERROR("closesocket() error");


		sockNum=0;
	}
}
Esempio n. 8
0
void SslConnection::startAsyncReadBody(ReplyPtr reply,
				       Buffer& buffer, int timeout)
{
  if (state_ & Reading) {
    LOG_DEBUG(socket().native() << ": state_ = " << state_);
    stop();
    return;
  }

  setReadTimeout(timeout);

  boost::shared_ptr<SslConnection> sft
    = boost::dynamic_pointer_cast<SslConnection>(shared_from_this());
  socket_.async_read_some(asio::buffer(buffer),
			  strand_.wrap
			  (boost::bind(&SslConnection::handleReadBodySsl,
				       sft,
				       reply,
				       asio::placeholders::error,
				       asio::placeholders::bytes_transferred)));
}
Esempio n. 9
0
bool Socket_TCP::connectTo(const char * hostname, uint16_t port, uint32_t timeout)
{
    char servport[32];
    int rc;
    struct in6_addr serveraddr;
    struct addrinfo hints, *res=NULL;

    memset(&hints, 0x00, sizeof(hints));

#ifdef _WIN32
    hints.ai_flags    = 0;
#else
    hints.ai_flags    = AI_NUMERICSERV;
#endif
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    rc = inet_pton(AF_INET, hostname, &serveraddr);
    if (rc == 1)
    {
        hints.ai_family = AF_INET;
        hints.ai_flags |= AI_NUMERICHOST;
    }
    else
    {
        rc = inet_pton(AF_INET6, hostname, &serveraddr);
        if (rc == 1)
        {
            hints.ai_family = AF_INET6;
            hints.ai_flags |= AI_NUMERICHOST;
        }
    }

    snprintf(servport,32,"%u",port);

    rc = getaddrinfo(hostname, servport, &hints, &res);
    if (rc != 0)
    {
        // Host not found.
        lastError = "Error resolving hostname";
        return false;
    }

    bool connected = false;

    for (struct addrinfo *resiter=res; resiter && !connected; resiter = resiter->ai_next)
    {
        if (getSocket() >=0 ) closeSocket();
        setSocket(socket(res->ai_family, res->ai_socktype, res->ai_protocol));
        if (!isValidSocket())
        {
            lastError = "socket() failed";
            break;
        }

        // Set the read timeout here. (to zero)
        setReadTimeout(0);

        if (internalConnect(getSocket(),resiter->ai_addr, resiter->ai_addrlen,timeout))
        {
            // now it's connected...
            if (PostConnectSubInitialization())
            {
                connected = true;
            }
            else
            {
            	// should disconnect here.
            	shutdownSocket();
                // drop the socket descriptor. we don't need it anymore.
                closeSocket();
            }
            break;
        }
        else
        {
            // drop the current socket... (and free the resource :))
            shutdownSocket();
            closeSocket();
        }
    }

    freeaddrinfo(res);

    if (!connected)
    {
        lastError = "connect() failed";
        return false;
    }

    return true;
}
Esempio n. 10
0
bool mdtSerialPortPosix::open(mdtSerialPortConfig &cfg)
{
  QString strNum;

  // Close previous opened device
  this->close();
  // Try to open port
  //  O_RDWR : Read/write access
  //  O_NOCTTY: not a terminal
  //  O_NDELAY: ignore DCD signal
  lockMutex();
  // In read only mode, we handle no lock
  if(cfg.readOnly()){
    pvFd = ::open(pvName.toStdString().c_str(), O_RDONLY | O_NOCTTY | O_NONBLOCK);
  }else{
    pvFd = pvPortLock->openLocked(pvName, O_RDWR | O_NOCTTY | O_NONBLOCK);
  }
  if(pvFd < 0){
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "Unable to open port: " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Get current config and save it to pvOriginalTermios
  if(tcgetattr(pvFd, &pvOriginalTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "tcgetattr() failed, " + pvName + " is not a serial port, or is not available", mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Get current system config on "work copy"
  if(tcgetattr(pvFd, &pvTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "tcgetattr() failed, " + pvName + " is not a serial port, or is not available", mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set baud rate
  if(!setBaudRate(cfg.baudRate())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.baudRate());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported baud rate '" + strNum + "' for port " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set local mode and enable the receiver
  pvTermios.c_cflag |= (CLOCAL | CREAD);
  // Set data bits
  if(!setDataBits(cfg.dataBitsCount())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.dataBitsCount());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported data bits count '" + strNum + "' for port " + pvName, mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set stop bits
  if(!setStopBits(cfg.stopBitsCount())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.stopBitsCount());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported stop bits count '" + strNum + "' for port " + pvName, mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set parity
  setParity(cfg.parity());
  // Set flow control
  setFlowCtlRtsCts(cfg.flowCtlRtsCtsEnabled());
  setFlowCtlXonXoff(cfg.flowCtlXonXoffEnabled(), cfg.xonChar(), cfg.xoffChar());
  // Set raw data mode
  pvTermios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  pvTermios.c_oflag &= ~OPOST;
  // Apply the setup
  if(tcsetattr(pvFd, TCSANOW, &pvTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "unable to apply configuration for port " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Check if configuration could really be set
  if(!checkConfig(cfg)){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    unlockMutex();
    return false;
  }

  // Set the read/write timeouts
  setReadTimeout(cfg.readTimeout());
  setWriteTimeout(cfg.writeTimeout());

  return mdtAbstractPort::open(cfg);
}