Exemple #1
0
int SocketImpl::receiveBytes(void* buffer, int length, int flags)
{
#if defined(POCO_BROKEN_TIMEOUTS)
	if (_recvTimeout.totalMicroseconds() != 0)
	{
		if (!poll(_recvTimeout, SELECT_READ))
			throw TimeoutException();
	}
#endif
	
	int rc;
	do
	{
		if (_sockfd == POCO_INVALID_SOCKET) throw InvalidSocketException();
		rc = ::recv(_sockfd, reinterpret_cast<char*>(buffer), length, flags);
	}
	while (_blocking && rc < 0 && lastError() == POCO_EINTR);
	if (rc < 0) 
	{
		int err = lastError();
		if (err == POCO_EAGAIN && !_blocking)
			;
		else if (err == POCO_EAGAIN || err == POCO_ETIMEDOUT)
			throw TimeoutException(err);
		else
			error(err);
	}
	return rc;
}
Node * Exchanger::exchange(Node *n)
{
    timespec current, bound;
    ExchangeState state;

    clock_gettime(CLOCK_REALTIME, &bound);
    bound.tv_nsec += NANO_DUR;

    while(true)
    {
        clock_gettime(CLOCK_REALTIME, &current);
        if (current > bound) throw TimeoutException();
        Node *otheritem = slot.get(&state);
        switch(state)
        {
        case EMPTY:
            if(slot.compareAndSet(otheritem, n, EMPTY, WAITING))
            {
                while(current < bound)
                {
                    clock_gettime(CLOCK_REALTIME, &current);
                    otheritem = slot.get(&state);
                    if(state == BUSY)
                    {
                        slot.set(NULL, EMPTY);
                        return otheritem;
                    }
                }
                if(slot.compareAndSet(n, NULL, WAITING, EMPTY))
                {
                    throw TimeoutException();
                }
                else
                {
                    otheritem = slot.get(&state);
                    slot.set(NULL, EMPTY);
                    return otheritem;
                }
            }
            break;
        case WAITING:
            if(slot.compareAndSet(otheritem, n, WAITING, BUSY))
            {
                return otheritem;
            }
            break;
        case BUSY:
            break;
        }
    }

    return NULL;
}
	void * Device::Reap(int timeout)
	{
		timeval started = {};
		if (gettimeofday(&started, NULL) == -1)
			throw usb::Exception("gettimeofday");

		pollfd fd = {};
		fd.fd		= _fd.Get();
		fd.events	= POLLOUT;
		int r = poll(&fd, 1, timeout);

		timeval now = {};
		if (gettimeofday(&now, NULL) == -1)
			throw usb::Exception("gettimeofday");

		if (r < 0)
			throw Exception("poll");

		if (r == 0 && timeout > 0)
		{
			int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000;
			fprintf(stderr, "%d ms since the last poll call\n", ms);
		}

		usbdevfs_urb *urb;
		r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb);
		if (r == 0)
			return urb;
		else if (errno == EAGAIN)
			throw TimeoutException("timeout reaping usb urb");
		else
			throw Exception("ioctl");
	}
	void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, bool interruptCurrentTransaction, int timeout)
	{
		usbdevfs_ctrltransfer ctrl = { };
		ctrl.bRequestType = type;
		ctrl.bRequest = req;
		ctrl.wValue = value;
		ctrl.wIndex = index;
		ctrl.wLength = data.size();
		ctrl.data = const_cast<u8 *>(data.data());
		ctrl.timeout = timeout;

		int fd = _fd.Get();

		_controls.push(
		[fd, ctrl, interruptCurrentTransaction]()
		{
			int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
			if (r >= 0)
			{
				if (interruptCurrentTransaction)
					throw std::runtime_error("transaction aborted");
				else
					return;
			}
			else if (errno == EAGAIN)
				throw TimeoutException("timeout sending control transfer");
			else
				throw Exception("ioctl");
		});
	}
/**
 *  Select
 */
void SelectorImplNSPR::select(vpr::Uint16& numWithEvents,
                              const vpr::Interval& timeout)
{
   PRInt32 result;

   // Call poll - If timeout == 0, then make sure we pass 0
   result = PR_Poll(&(mPollDescs[0]), mPollDescs.size(),
                    NSPR_getInterval(timeout));

   if ( -1 == result )
   {
      //NSPR_PrintError("SelectorImplNSPR::select: Error selecting. ");
      std::stringstream msg_stream;
      msg_stream << "[vpr::SelectorImplNSPR::select()] Error selecting.";
      vpr::Error::outputCurrentError(std::cerr, msg_stream.str());

      numWithEvents = 0;

      msg_stream << ": " << vpr::Error::getCurrentErrorMsg();
      throw IOException(msg_stream.str(), VPR_LOCATION);
   }
   else if ( 0 == result )    // Timeout
   {
      numWithEvents = 0;
      throw TimeoutException("Timeout occured while selecting.", VPR_LOCATION);
   }
   //else                    // Got some

   numWithEvents = result;
}
Exemple #6
0
DataPackage RpcSocket::sendSynch(const DataPackage& output) throw(Exception)
{
	ScopedLock lock(this->sendLock);

	this->isWaitingData=true;
	this->idOfWaitData=output.getId();

	// TODO: deal with block(or timeout)
	this->send(output);

	unsigned int timeout = this->timeout + 100;
	if(this->timeout == 0)
		timeout = INFINITE;
	if(!this->sendLock.wait(timeout))
		throwpe(TimeoutException(timeout));

	DataPackage& result = this->recvPacket;
	if(result.getId() != output.getId()) {
		// if another thread send a request, idOfWaitData may changed
		// TODO: should we support multi-thread to send? if so, we should
		// add a map instead of idOfWaitData, like map<id, object(lock, value)>
		// when a response reached:
		//   map(id).value=response;
		//   map(id).lock.notify();
		String msg = "Unexpected response received, there may be another "\
			"thread sending a request? if so please use async-send instead!";
		throwpe(RpcException(msg));
	}

	this->isWaitingData=false;
	return std::move(result);
}
Exemple #7
0
/** Enqueue message to send and wait for answer. It is guaranteed that an
 * answer cannot be missed. However, if the component sends another message
 * (which is not the answer to the query) this will also trigger the wait
 * condition to be woken up. The component ID to wait for is taken from the
 * message.
 * This message also calls unref() on the message. If you want to use it
 * after enqueuing make sure you ref() before calling this method.
 * @param message message to send
 * @param timeout_sec timeout for the waiting operation in seconds, 0 to wait
 * forever (warning, this may result in a deadlock!)
 */
void
FawkesNetworkClient::enqueue_and_wait(FawkesNetworkMessage *message,
				      unsigned int timeout_sec)
{
  if (__send_slave && __recv_slave) {
    __recv_mutex->lock();
    if ( __recv_received.find(message->cid()) != __recv_received.end()) {
      __recv_mutex->unlock();
      unsigned int cid = message->cid();
      throw Exception("There is already a thread waiting for messages of "
		      "component id %u", cid);
    }
    __send_slave->enqueue(message);
    unsigned int cid = message->cid();
    __recv_received[cid] = false;
    while (!__recv_received[cid] && ! connection_died_recently) {
      if (!__recv_waitcond->reltimed_wait(timeout_sec, 0)) {
	__recv_received.erase(cid);
	__recv_mutex->unlock();
	throw TimeoutException("Timeout reached while waiting for incoming message "
			       "(outgoing was %u:%u)", message->cid(), message->msgid());
      }
    }
    __recv_received.erase(cid);
    __recv_mutex->unlock();
  } else {
    unsigned int cid = message->cid();
    unsigned int msgid = message->msgid();
    throw Exception("Cannot enqueue given message %u:%u, sender or "
		    "receiver missing", cid, msgid);
  }
}
Exemple #8
0
	/**
	 * ソケットからのデータの取得(タイムアウトあり)
	 * @param buffer 読み込んだデータへのポインタ
	 * @param readSize 読み込み可能な最大サイズ
	 * @return 実際に読み込まれたデータサイズ。0が返った場合、相手先ソ
	 * ケットがクローズされた。
	 * @exception TimeoutException 待機時間内にソケットに読み取り可能
	 * なデータが入ってこなかった場合
	 */
	size_t readWithTimeout(void* buffer, const size_t readSize)
		throw(TimeoutException, ConnectionClosedException)
	{
		if (!this->isReadable(this->socket, this->defaultTimeout))
			throw TimeoutException();

		return read(buffer, readSize);
	}  
Exemple #9
0
	/**
	 * ソケットへのデータ書き込み(タイムアウトあり)
	 * @param buffer 書き込むデータへのポインタ
	 * @param writeSize 書き込むデータのサイズ
	 * @return 実際に書き込まれたデータのサイズ。0が返った場合、相手先
	 * ソケットがクローズされた
	 * @exception TimeoutException 待機時間中にソケットが書き込み可能
	 * にならなかった場合
	 */
	size_t writeWithTimeout(const void* buffer, const size_t writeSize) 
		throw(TimeoutException, ConnectionClosedException)
	{
		if (!this->isWritable(this->socket, this->defaultTimeout))
			throw TimeoutException();
   
		return write(buffer, writeSize);
	}
vpr::Uint32 SocketDatagramImplBSD::recvfrom(void* msg,
                                            const vpr::Uint32 length,
                                            vpr::InetAddr& from,
                                            const vpr::Interval& timeout)
{
   vpr::Uint32 bytes_read(0);

#if defined(VPR_OS_IRIX) || defined(VPR_OS_HPUX)
   int fromlen;
#else
   socklen_t fromlen;
#endif

   // If not readable within timeout interval throw exception.
   if ( ! mHandle->isReadable(timeout) )
   {
      std::ostringstream msg_stream;
      msg_stream << "Timeout occured while trying to read from "
                 << mHandle->getName();
      throw TimeoutException(msg_stream.str(), VPR_LOCATION);
   }

   ssize_t bytes;

   mBlockingFixed = true;

   fromlen = from.size();
   bytes   = ::recvfrom(mHandle->mFdesc, msg, length, 0,
                        reinterpret_cast<sockaddr*>(&from.mAddr), &fromlen);

   if ( bytes == -1 )
   {
      if ( errno == EAGAIN && ! isBlocking() )
      {
         throw WouldBlockException("Would block while reading.", VPR_LOCATION);
      }
      else
      {
         std::ostringstream ss;
         ss << "[vpr::SocketDatagramImplBSD::recvfrom()] ERROR: Could not "
            << "read from socket (" << mRemoteAddr << "): "
            << strerror(errno);
         throw SocketException(ss.str(), VPR_LOCATION);
      }
   }
   else if ( bytes == 0 )
   {
      throw SocketException("Socket not connected.");
   }
   else
   {
      bytes_read = bytes;
   }

   return bytes_read;
}
void SelectorImplSIM::select(vpr::Uint16& numWithEvents,
                                          const vpr::Interval timeout)
{
   std::vector<SimPollDesc>::iterator i;
   bool has_event;

   numWithEvents = 0;

   for ( i = mPollDescs.begin(); i != mPollDescs.end(); ++i )
   {
      // We have to do this every time to insure that a previous event is not
      // "reselected".
      (*i).out_flags = 0;

      has_event = false;

      if ( (*i).in_flags & vpr::SelectorBase::Read ||
           (*i).in_flags & vpr::SelectorBase::Accept)
      {
         if ( (*i).fd->isReadReady().success() )
         {
            has_event = true;
            (*i).out_flags |= vpr::SelectorBase::Read;
         }
      }

      if ( (*i).in_flags & vpr::SelectorBase::Write )
      {
         if ( (*i).fd->isWriteReady().success() )
         {
            has_event = true;
            (*i).out_flags |= vpr::SelectorBase::Write;
         }
      }

      if ( (*i).in_flags & vpr::SelectorBase::Except )
      {
         if ( (*i).fd->inExceptState().success() )
         {
            has_event = true;
            (*i).out_flags |= vpr::SelectorBase::Except;
         }
      }

      if ( has_event )
      {
         numWithEvents++;
      }
   }

   if ( numWithEvents == 0 )
   {
      numWithEvents = 0;
      throw TimeoutException("Timeout occured while selecting.", VPR_LOCATION);
   }
}
Exemple #12
0
// ---------------------------------
void WSys::waitThread(ThreadInfo *info, int timeout)
{
#pragma warning(disable : 4312)
	switch(WaitForSingleObject((void *)info->handle, timeout))
#pragma warning(default : 4312)
	{
      case WAIT_TIMEOUT:
          throw TimeoutException();
          break;
	}
}
Exemple #13
0
void Node::verify_arp_cache(string address)
{
	time_t timestamp = time(0);
	//Endereco nao esta na ARP Cache. Comecando o processo do ARP
	if(arp_cache.size() < 1 || arp_cache.find(address) == arp_cache.end()) arp_request(this->arp_packet,address);
	//Aguardando 15 segundos para o retorno de resposta, caso contrario, Timeout
	while(arp_cache.find(address) == arp_cache.end()){ 
		try { if(time(0)-timestamp > 15) throw TimeoutException(); }
		catch(exception& e){ cout << e.what() << endl; break; }
	}
}
// Read the specified number of bytes from the file handle into the given
// bufer.
vpr::Uint32 FileHandleImplUNIX::read_i(void* buffer, const vpr::Uint32 length,
                                       const vpr::Interval& timeout)
{
   vpr::Uint32 bytes_read(0);

   // If not readable within timeout interval throw exception.
   if ( ! isReadable(timeout) )
   {
      std::ostringstream msg_stream;
      msg_stream << "Timeout occured while trying to read from " << mName;
      throw TimeoutException(msg_stream.str(), VPR_LOCATION);
   }

   const ssize_t bytes = ::read(mFdesc, buffer, length);

   // Error: Something went wrong while attempting to read from the file.
   if ( bytes < 0 )
   {
      if ( errno == EAGAIN && ! mBlocking )
      {
         throw WouldBlockException("Would block while reading.", VPR_LOCATION);
      }
      else  // "real" error, so throw IO Exception
      {
         std::ostringstream msg_stream;
         msg_stream << "Error reading from " << mName << ":"
                    << strerror(errno);
         throw IOException(msg_stream.str(), VPR_LOCATION);
      }
   }
   // If 0 bytes were read and an error was returned, we throw.
   // Note: If bytes == 0 and no error (and socket) then that means the other
   //       side shut down cleanly.
   else if ( 0 == bytes && 0 != errno )
   {
      vprDEBUG(vprDBG_ERROR, vprDBG_WARNING_LVL)
         << "[vpr::FileHandleImplUNIX::read_i()] Nothing read from "
         << mName << ": " << strerror(errno) << std::endl << vprDEBUG_FLUSH;

      // XXX: Failure status may not be exactly what we want to return.
      std::ostringstream msg_stream;
      msg_stream << "Nothing read from " << mName << ": " << strerror(errno);
      throw IOException(msg_stream.str(), VPR_LOCATION);
   }
   else
   {
      bytes_read = bytes;
   }

   return bytes_read;
}
Exemple #15
0
int SocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
#if defined(POCO_BROKEN_TIMEOUTS)
	if (_recvTimeout.totalMicroseconds() != 0)
	{
		if (!poll(_recvTimeout, SELECT_READ))
			throw TimeoutException();
	}
#endif
	
	char abuffer[SocketAddress::MAX_ADDRESS_LENGTH];
	struct sockaddr* pSA = reinterpret_cast<struct sockaddr*>(abuffer);
	poco_socklen_t saLen = sizeof(abuffer);
	int rc;
	do
	{
		if (_sockfd == POCO_INVALID_SOCKET) throw InvalidSocketException();
		rc = ::recvfrom(_sockfd, reinterpret_cast<char*>(buffer), length, flags, pSA, &saLen);
	}
	while (_blocking && rc < 0 && lastError() == POCO_EINTR);
	if (rc >= 0)
	{
		address = SocketAddress(pSA, saLen);
	}
	else
	{
		int err = lastError();
		if (err == POCO_EAGAIN && !_blocking)
			;
		else if (err == POCO_EAGAIN || err == POCO_ETIMEDOUT)
			throw TimeoutException(err);
		else
			error(err);
	}
	return rc;
}
Exemple #16
0
// --------------------------------------------------
void UClientSocket::checkTimeout(bool r, bool w)
{
    int err = errno;
    if ((err == EAGAIN) || (err == EINPROGRESS))
    {
		//LOG("checktimeout %d %d",(int)r,(int)w);

		timeval timeout;
		fd_set read_fds;
		fd_set write_fds;

		timeout.tv_sec = 0;
		timeout.tv_usec = 0;

        FD_ZERO (&write_fds);
		if (w)
		{
			timeout.tv_sec = (int)this->writeTimeout/1000;
			FD_SET (sockNum, &write_fds);
		}

        FD_ZERO (&read_fds);
		if (r)
		{
			timeout.tv_sec = (int)this->readTimeout/1000;
	        FD_SET (sockNum, &read_fds);
		}

		timeval *tp;
		if (timeout.tv_sec)
			tp = &timeout;
		else
			tp = NULL;


		int r=select (sockNum+1, &read_fds, &write_fds, NULL, tp);

        if (r == 0)
			throw TimeoutException();
		else if (r == SOCKET_ERROR)
			throw SockException("select failed.");

	}else{
		char str[256];
		sprintf(str,"Closed: %s",strerror(err));
		throw SockException(str);
	}
}
Exemple #17
0
// --------------------------------------------------
void WSAClientSocket::checkTimeout(bool r, bool w)
{
    int err = WSAGetLastError();
    if (err == WSAEWOULDBLOCK)
    {

		timeval timeout;
		fd_set read_fds;
		fd_set write_fds;

		timeout.tv_sec = 0;
		timeout.tv_usec = 0;

        FD_ZERO (&write_fds);
		if (w)
		{
			timeout.tv_sec = (int)this->writeTimeout/1000;
			FD_SET (sockNum, &write_fds);
		}

        FD_ZERO (&read_fds);
		if (r)
		{
			timeout.tv_sec = (int)this->readTimeout/1000;
	        FD_SET (sockNum, &read_fds);
		}

		timeval *tp;
		if (timeout.tv_sec)
			tp = &timeout;
		else
			tp = NULL;


		int r=select (NULL, &read_fds, &write_fds, NULL, tp);

        if (r == 0)
			throw TimeoutException();
		else if (r == SOCKET_ERROR)
			throw SockException("select failed.");

	}else{
		char str[32];
		sprintf(str,"%d",err);
		throw SockException(str);
	}
}
Exemple #18
0
int SocketChannel::readData(char* pBuffer, int length)
{
    int received = 0;

    try
    {
        if (!socketImpl()->poll(config().getTimeout() * Timespan::MILLISECONDS, SocketImpl::SELECT_READ))
            throw TimeoutException("read timed out", socketImpl()->address().toString());
        received = socketImpl()->receiveBytes(pBuffer, (int) length);
    }
    catch (Poco::Exception&)
    {
        throw;
    }

    return received;
}
Exemple #19
0
void
writeExact(int fd, const void *data, unsigned int size, unsigned long long *timeout) {
	ssize_t ret;
	unsigned int written = 0;
	while (written < size) {
		if (timeout != NULL && !waitUntilWritable(fd, timeout)) {
			throw TimeoutException("Cannot write enough data within the specified timeout");
		}
		ret = syscalls::write(fd, (const char *) data + written, size - written);
		if (ret == -1) {
			int e = errno;
			throw SystemException("write() failed", e);
		} else {
			written += ret;
		}
	}
}
Exemple #20
0
int ICMPSocketImpl::receiveFrom(void*, int, SocketAddress& address, int flags)
{
	int maxPacketSize = _icmpPacket.maxPacketSize();
	unsigned char* buffer = new unsigned char[maxPacketSize];

	try
	{
		Poco::Timestamp ts;
		do
		{
			if (ts.isElapsed(_timeout)) 
			{
				// This guards against a possible DoS attack, where sending
				// fake ping responses will cause an endless loop.
				throw TimeoutException();
			}
			SocketImpl::receiveFrom(buffer, maxPacketSize, address, flags);
		}
		while (!_icmpPacket.validReplyID(buffer, maxPacketSize));
	}
	catch (TimeoutException&)
	{
		delete [] buffer;			
		throw;
	}
	catch (Exception&)
	{
		std::string err = _icmpPacket.errorDescription(buffer, maxPacketSize);
		delete [] buffer;
		if (!err.empty()) 
			throw ICMPException(err);
		else 
			throw;
	}

	struct timeval then = _icmpPacket.time(buffer, maxPacketSize);
	struct timeval now  = _icmpPacket.time();

	int elapsed	= (((now.tv_sec * 1000000) + now.tv_usec) - ((then.tv_sec * 1000000) + then.tv_usec))/1000;

	delete[] buffer;
	return elapsed;
}
vpr::Uint32 SerialPortImplWin32::read_i(void* buffer, const vpr::Uint32 length,
                                        const vpr::Interval& timeout)
{
   unsigned long bytes;

   // Shouldn't be setting this every read, but don't have any other way of
   // specifying the timeout.
   if ( vpr::Interval::NoTimeout != timeout )
   {
      COMMTIMEOUTS t;
      GetCommTimeouts(mHandle, &t);
      t.ReadTotalTimeoutConstant = (int)timeout.msec();
      SetCommTimeouts(mHandle, &t);
   }

   if ( ! ReadFile(mHandle, buffer, length, &bytes, NULL) )
   {
      std::stringstream msg_stream;
      msg_stream << "Failed to read from serial port " << mName << ": "
                 << getErrorMessageWithCode(GetLastError());
      throw IOException(msg_stream.str(), VPR_LOCATION);
   }

   //Now set the timeout back
   if ( vpr::Interval::NoTimeout != timeout )
   {
      COMMTIMEOUTS t;
      GetCommTimeouts(mHandle, &t);
      t.ReadTotalTimeoutConstant = (int)mCurrentTimeout*100;
      SetCommTimeouts(mHandle, &t);
   }

   // XXX: Does reading 0 bytes really indicate a timeout?
   if ( bytes == 0 )
   {
      std::stringstream msg_stream;
      msg_stream << "Timeout while attempting to read from serial port "
                 << mName;
      throw TimeoutException(msg_stream.str(), VPR_LOCATION);
   }

   return bytes;
}
Exemple #22
0
int SocketImpl::sendBytes(const void* buffer, int length, int flags)
{
#if defined(POCO_BROKEN_TIMEOUTS)
	if (_sndTimeout.totalMicroseconds() != 0)
	{
		if (!poll(_sndTimeout, SELECT_WRITE))
			throw TimeoutException();
	}
#endif

	int rc;
	do
	{
		if (_sockfd == POCO_INVALID_SOCKET) throw InvalidSocketException();
		rc = ::send(_sockfd, reinterpret_cast<const char*>(buffer), length, flags);
	}
	while (_blocking && rc < 0 && lastError() == POCO_EINTR);
	if (rc < 0) error();
	return rc;
}
Exemple #23
0
// --------------------------------------------------
void UClientSocket::checkTimeout2(bool r, bool w)
{
    {
		//LOG("checktimeout %d %d",(int)r,(int)w);

		timeval timeout;
		fd_set read_fds;
		fd_set write_fds;

		timeout.tv_sec = 0;
		timeout.tv_usec = 0;

        FD_ZERO (&write_fds);
		if (w)
		{
			timeout.tv_sec = (int)this->writeTimeout/1000;
			FD_SET (sockNum, &write_fds);
		}

        FD_ZERO (&read_fds);
		if (r)
		{
			timeout.tv_sec = (int)this->readTimeout/1000;
	        FD_SET (sockNum, &read_fds);
		}

		timeval *tp;
		if (timeout.tv_sec)
			tp = &timeout;
		else
			tp = NULL;


		int r=select (sockNum+1, &read_fds, &write_fds, NULL, tp);

        if (r == 0)
			throw TimeoutException();
		else if (r == SOCKET_ERROR)
			throw SockException("select failed.");
	}
}
// Write the buffer to the file handle.
vpr::Uint32 FileHandleImplUNIX::write_i(const void* buffer,
                                        const vpr::Uint32 length,
                                        const vpr::Interval& timeout)
{
   vpr::Uint32 bytes_written(0);

   // If not writable within timeout interval throw exception.
   if ( ! isWriteable(timeout) )
   {
      std::ostringstream msg_stream;
      msg_stream << "Timeout occured while trying to write to: " << mName;
      throw TimeoutException(msg_stream.str(), VPR_LOCATION);
   }

   const ssize_t bytes = ::write(mFdesc, buffer, length);

   if ( bytes <= 0 )
   {
      if ( errno == EAGAIN && ! mBlocking )
      {
         throw WouldBlockException("Would block writing.", VPR_LOCATION);
      }
      else
      {
         vprDEBUG(vprDBG_ERROR, vprDBG_CRITICAL_LVL)
            << "[vpr::FileHandleImplUNIX::write_i()] Error writing to "
            << mName << ": " << strerror(errno) << std::endl
            << vprDEBUG_FLUSH;

         std::ostringstream msg_stream;
         msg_stream << "Error writing to " << mName << strerror(errno);
         throw IOException(msg_stream.str(), VPR_LOCATION);
      }
   }
   else
   {
      bytes_written = bytes;
   }

   return bytes_written;
}
Exemple #25
0
unsigned int
readExact(int fd, void *buf, unsigned int size, unsigned long long *timeout) {
	ssize_t ret;
	unsigned int alreadyRead = 0;
	
	while (alreadyRead < size) {
		if (timeout != NULL && !waitUntilReadable(fd, timeout)) {
			throw TimeoutException("Cannot read enough data within the specified timeout");
		}
		ret = syscalls::read(fd, (char *) buf + alreadyRead, size - alreadyRead);
		if (ret == -1) {
			int e = errno;
			throw SystemException("read() failed", e);
		} else if (ret == 0) {
			return alreadyRead;
		} else {
			alreadyRead += ret;
		}
	}
	return alreadyRead;
}
Exemple #26
0
/** Wait for messages for component ID.
 * This will wait for messages of the given component ID to arrive. The calling
 * thread is blocked until messages are available.
 * @param component_id component ID to monitor
 * @param timeout_sec timeout for the waiting operation in seconds, 0 to wait
 * forever (warning, this may result in a deadlock!)
 */
void
FawkesNetworkClient::wait(unsigned int component_id, unsigned int timeout_sec)
{
  __recv_mutex->lock();
  if ( __recv_received.find(component_id) != __recv_received.end()) {
    __recv_mutex->unlock();
    throw Exception("There is already a thread waiting for messages of "
		    "component id %u", component_id);
  }
  __recv_received[component_id] = false;
  while (! __recv_received[component_id] && ! connection_died_recently) {
    if (!__recv_waitcond->reltimed_wait(timeout_sec, 0)) {
      __recv_received.erase(component_id);
      __recv_mutex->unlock();
      throw TimeoutException("Timeout reached while waiting for incoming message "
			     "(component %u)", component_id);
    }
  }
  __recv_received.erase(component_id);
  __recv_mutex->unlock();
}
Exemple #27
0
ByteArray TCPSocket::read(size_t maxSize)
{
    ByteArray ba(maxSize);

    // Return empty array if size is 0
    if (maxSize == 0)
    {
        return ba;
    }

    // Read from socket
    ssize_t size = ::read(d->fd, ba.data(), ba.size());

    // Check for errors
    if (size < 0)
    {
        switch (errno)
        {
        case EAGAIN:
        case ETIMEDOUT:
            throw TimeoutException("TCPSocket::read", strerror(errno));
        case EPIPE:
            throw DisconnectedException("TCPSocket::read", strerror(errno));
        default:
            throw IOException("TCPSocket::read", strerror(errno));
        }
    }

    // If size is 0, means the socket is disconnected
    if (size == 0)
    {
        throw DisconnectedException("TCPSocket::read", "Disconnected");
    }

    // Return a byte-array of the actual read size
    return ByteArray(ba.constData(), size);
}
Exemple #28
0
// --------------------------------------------------
void	CSocket::_checkTimeout(bool bRead)
{
    int err = WSAGetLastError();
    if (err == WSAEWOULDBLOCK) {
		timeval timeout = { 0 };
		fd_set read_fds;
		FD_ZERO (&read_fds);
		fd_set write_fds;
        FD_ZERO(&write_fds);
		
		if (bRead) {
			timeout.tv_sec = (int)m_uReadTimeout/1000;
	        FD_SET(m_sock, &read_fds);
		} else {
			timeout.tv_sec = (int)m_uWriteTimeout/1000;
			FD_SET(m_sock, &write_fds);
		}

		timeval *tp;
		if (timeout.tv_sec)
			tp = &timeout;
		else
			tp = NULL;

		int r = select(NULL, &read_fds, &write_fds, NULL, tp);
        if (r == 0)
			throw TimeoutException();
		else if (r == SOCKET_ERROR)
			throw SockException("select failed.");

	} else {
		char str[32];
		sprintf(str, "%d", err);
		throw SockException(str);
	}
}
Exemple #29
0
void TCPSocket::flush()
{
    size_t sent = 0;
    while (sent < d->sendbuf.size())
    {
        ssize_t size = ::write(d->fd, d->sendbuf.data(), d->sendbuf.size());

        if (size < 0)
        {
            switch (errno)
            {
            case EAGAIN:
            case ETIMEDOUT:
                throw TimeoutException("TCPSocket::flush", strerror(errno));
            case EPIPE:
                throw DisconnectedException("TCPSocket::flush", strerror(errno));
            default:
                throw IOException("TCPSocket::flush", strerror(errno));
            }
        }
        sent += size;
    }
    d->sendbuf.clear();
}
Exemple #30
0
void SocketImpl::error(int code, const std::string& arg)
{
	switch (code)
	{
	case POCO_ENOERR: return;
	case POCO_ESYSNOTREADY:
		throw NetException("Net subsystem not ready", code);
	case POCO_ENOTINIT:
		throw NetException("Net subsystem not initialized", code);
	case POCO_EINTR:
		throw IOException("Interrupted", code);
	case POCO_EACCES:
		throw IOException("Permission denied", code);
	case POCO_EFAULT:
		throw IOException("Bad address", code);
	case POCO_EINVAL:
		throw InvalidArgumentException(code);
	case POCO_EMFILE:
		throw IOException("Too many open files", code);
	case POCO_EWOULDBLOCK:
		throw IOException("Operation would block", code);
	case POCO_EINPROGRESS:
		throw IOException("Operation now in progress", code);
	case POCO_EALREADY:
		throw IOException("Operation already in progress", code);
	case POCO_ENOTSOCK:
		throw IOException("Socket operation attempted on non-socket", code);
	case POCO_EDESTADDRREQ:
		throw NetException("Destination address required", code);
	case POCO_EMSGSIZE:
		throw NetException("Message too long", code);
	case POCO_EPROTOTYPE:
		throw NetException("Wrong protocol type", code);
	case POCO_ENOPROTOOPT:
		throw NetException("Protocol not available", code);
	case POCO_EPROTONOSUPPORT:
		throw NetException("Protocol not supported", code);
	case POCO_ESOCKTNOSUPPORT:
		throw NetException("Socket type not supported", code);
	case POCO_ENOTSUP:
		throw NetException("Operation not supported", code);
	case POCO_EPFNOSUPPORT:
		throw NetException("Protocol family not supported", code);
	case POCO_EAFNOSUPPORT:
		throw NetException("Address family not supported", code);
	case POCO_EADDRINUSE:
		throw NetException("Address already in use", arg, code);
	case POCO_EADDRNOTAVAIL:
		throw NetException("Cannot assign requested address", arg, code);
	case POCO_ENETDOWN:
		throw NetException("Network is down", code);
	case POCO_ENETUNREACH:
		throw NetException("Network is unreachable", code);
	case POCO_ENETRESET:
		throw NetException("Network dropped connection on reset", code);
	case POCO_ECONNABORTED:
		throw ConnectionAbortedException(code);
	case POCO_ECONNRESET:
		throw ConnectionResetException(code);
	case POCO_ENOBUFS:
		throw IOException("No buffer space available", code);
	case POCO_EISCONN:
		throw NetException("Socket is already connected", code);
	case POCO_ENOTCONN:
		throw NetException("Socket is not connected", code);
	case POCO_ESHUTDOWN:
		throw NetException("Cannot send after socket shutdown", code);
	case POCO_ETIMEDOUT:
		throw TimeoutException(code);
	case POCO_ECONNREFUSED:
		throw ConnectionRefusedException(arg, code);
	case POCO_EHOSTDOWN:
		throw NetException("Host is down", arg, code);
	case POCO_EHOSTUNREACH:
		throw NetException("No route to host", arg, code);
#if defined(POCO_OS_FAMILY_UNIX)
	case EPIPE:
		throw IOException("Broken pipe", code);
	case EBADF:
		throw IOException("Bad socket descriptor", code);
#endif
	default:
		throw IOException(NumberFormatter::format(code), arg, code);
	}
}