示例#1
0
bool Socket::listen() const
{

  if (!is_valid())
  {
    return false;
  }

  int listen_return = ::listen (_sd, SOMAXCONN);
  //This is defined as 5 in winsock.h, and 0x7FFFFFFF in winsock2.h.
  //linux 128//MAXCONNECTIONS =1

  if (listen_return == -1)
  {
    errormessage( getLastError(), "Socket::listen" );
    return false;
  }

  return true;
}
void test_initDriverDataDispatcherList_add_too_much_dispatchers(void) {
    init_driverDataDispatcherList();
    TEST_ASSERT_FALSE(isThereAnyError());
    TEST_ASSERT_EQUAL(0, getDriverDataDispatcherCount());

    // Add a first dispatcher
    DriverDataDispatcher* dispacher = addLocalDriverDataDispatcher();
    TEST_ASSERT_FALSE(isThereAnyError());
    TEST_ASSERT_EQUAL(1, getDriverDataDispatcherCount());
    // TEST_ASSERT_EQUAL(dispacher, getDriverDataDispatcherByIndex(0));
    
    // Add a second dispatcher
    dispacher = addLocalDriverDataDispatcher();
    TEST_ASSERT_FALSE(isThereAnyError());
    TEST_ASSERT_EQUAL(2, getDriverDataDispatcherCount());
    TEST_ASSERT_EQUAL(dispacher, getDriverDataDispatcherByIndex(1));

    dispacher = addLocalDriverDataDispatcher();
    TEST_ASSERT_EQUAL(TOO_MUCH_DRIVER_DATA_DISPATCHER, getLastError());
}
bool Socket::reconnect()
{
  if ( _sd != INVALID_SOCKET )
  {
    return true;
  }

  if( !create() )
    return false;

  int status = ::connect ( _sd, reinterpret_cast<sockaddr*>(&_sockaddr), sizeof ( _sockaddr ) );

  if ( status == SOCKET_ERROR )
  {
    errormessage( getLastError(), "Socket::connect" );
    return false;
  }

  return true;
}
bool Socket::setHostname ( const std::string& host )
{
  if (isalpha(host.c_str()[0]))
  {
    // host address is a name
    struct hostent *he = NULL;
    if ((he = gethostbyname( host.c_str() )) == 0)
    {
      errormessage( getLastError(), "Socket::setHostname");
      return false;
    }

    _sockaddr.sin_addr = *((in_addr *) he->h_addr);
  }
  else
  {
    _sockaddr.sin_addr.s_addr = inet_addr(host.c_str());
  }
  return true;
}
int Socket::sendto ( const char* data, unsigned int size, bool sendcompletebuffer)
{
  int sentbytes = 0;
  int i;

  do
  {
    i = ::sendto(_sd, data, size, 0, (const struct sockaddr*) &_sockaddr, sizeof( _sockaddr ) );

    if (i <= 0)
    {
      errormessage( getLastError(), "Socket::sendto");
      osCleanup();
      return i;
    }
    sentbytes += i;
  } while ( (sentbytes < (int) size) && (sendcompletebuffer == true));

  return i;
}
示例#6
0
/*
 * Write to an open file in storage. Will write all of the bytes in the
 * buffer or pass back an error.
 *
 * If not successful *ppszError will set to point to an error string,
 * on success it will be set to NULL.
 */
void
storageWrite(char** ppszError, int handle, char* buffer, long length) {
    long bytesWritten;

    *ppszError = NULL;
    bytesWritten = pcsl_file_write((void *)handle, (unsigned char*)buffer, length);

    REPORT_INFO2(LC_CORE, "storageWrite on fd %d res = %ld\n",
          handle, bytesWritten);

    if (-1 == bytesWritten) {
        *ppszError = getLastError("storageWrite()");
        return;
    }

    if (bytesWritten != length) {
        *ppszError = "storage full";
        return;
    }
}
示例#7
0
/*
 * Close a opened by storage_open. Does no block.
 *
 * If not successful *ppszError will set to point to an error string,
 * on success it will be set to NULL.
 */
void
storageClose(char** ppszError, int handle) {
    int status;

    *ppszError = NULL;
    status = pcsl_file_close((void *)handle);

    REPORT_INFO2(LC_CORE, "storageClose on file_desc %d returns %d\n",
          handle, status);

    if (status < 0) {
        *ppszError = getLastError("storageClose()");
    }

    /* File is successfully closed, decrement the count */
    if (midpDecResourceCount(RSC_TYPE_FILE, 1) == 0) {
        REPORT_INFO(LC_CORE, "FILE: resource"
                             " limit update error");
    }
}
示例#8
0
Socket *ServerSocket::accept() {
Socket *handleSocket = NULL;

struct sockaddr_in addr;
int len = sizeof(addr);

int fd = ::accept(_socketHandle, (struct sockaddr *) & addr, (socklen_t*) & len);

if (fd >= 0) {
handleSocket = new Socket();
handleSocket->setUp(fd, (struct sockaddr *)&addr);
} else {
int error = getLastError();
if (error != EAGAIN) {
SYS_LOG(ERROR, "%s(%d)", strerror(error), error);
}
}

return handleSocket;
}
示例#9
0
Net::Error Net::bind(NetSocket socket, U16 port)
{
   S32 error;

   sockaddr_in socketAddress;
   dMemset((char *)&socketAddress, 0, sizeof(socketAddress));
   socketAddress.sin_family = AF_INET;
   // It's entirely possible that there are two NIC cards.
   // We let the user specify which one the server runs on.

   // thanks to [TPG]P1aGu3 for the name
   const char* serverIP = Con::getVariable( "pref::Net::BindAddress" );
   // serverIP is guaranteed to be non-0.
   AssertFatal( serverIP, "serverIP is NULL!" );

   if( serverIP[0] != '\0' ) {
      // we're not empty
      socketAddress.sin_addr.s_addr = inet_addr( serverIP );

      if( socketAddress.sin_addr.s_addr != INADDR_NONE ) {
         Con::printf( "Binding server port to %s", serverIP );
      } else {
         Con::warnf( ConsoleLogEntry::General,
            "inet_addr() failed for %s while binding!",
            serverIP );
         socketAddress.sin_addr.s_addr = INADDR_ANY;
      }

   } else {
      Con::printf( "Binding server port to default IP" );
      socketAddress.sin_addr.s_addr = INADDR_ANY;
   }

   socketAddress.sin_port = htons(port);
   error = ::bind(socket, (sockaddr *) &socketAddress,  sizeof(socketAddress));

   if(!error)
      return NoError;
   return getLastError();
}
示例#10
0
AdbConReply* AdbConnection::send(wxString op, wxString param, bool send_only){
	int timeouts = 0;
	AdbConReply* r;
	while(max_timeouts>timeouts++){
		r = send_layer1(op, param, send_only);
		if(m_cb->abort()) break;
		if(r==NULL) continue; // timeout
		if(!op.StartsWith(wxT("LOGOUT"))&&(r->code==rLOGIN_FIRST||r->code==rINVALID_SESSION)){
			if(remaining_auth_attempts<=0){
				AERROR(wxT("Invalid session."));
				return NULL;
			}
			remaining_auth_attempts--;
			if(login())
				return send(op, param, send_only);
			return NULL;
		}
		return r;
	}
	ALOG(getLastError());
	return NULL;
}
示例#11
0
Error X86Compiler::_newStack(BaseMem* mem, uint32_t size, uint32_t alignment, const char* name) noexcept {
  if (size == 0)
    return kErrorInvalidArgument;

  if (alignment > 64)
    alignment = 64;

  VarInfo vi = { kInvalidVar, 0, kInvalidReg , kInvalidReg, 0, "" };
  VarData* vd = _newVd(vi, name);

  if (vd == nullptr) {
    static_cast<X86Mem*>(mem)->reset();
    return getLastError();
  }

  vd->_size = size;
  vd->_isStack = true;
  vd->_alignment = static_cast<uint8_t>(alignment);

  static_cast<X86Mem*>(mem)->_init(kMemTypeStackIndex, vd->getId(), 0, 0);
  return kErrorOk;
}
示例#12
0
bool Socket::bind ( const unsigned short port )
{

  if (!is_valid())
  {
    return false;
  }

  _sockaddr.sin_family = _family;
  _sockaddr.sin_addr.s_addr = INADDR_ANY;  //listen to all
  _sockaddr.sin_port = htons( port );

  int bind_return = ::bind(_sd, (sockaddr*)(&_sockaddr), sizeof(_sockaddr));

  if ( bind_return == -1 )
  {
    errormessage( getLastError(), "Socket::bind" );
    return false;
  }

  return true;
}
PRL_RESULT Task_MigrateCtSource::migrateStoppedCt()
{
	PRL_RESULT nRetCode = PRL_ERR_SUCCESS;
	int i;
	QList<QPair<QFileInfo, QString> > dList;
	QList<QPair<QFileInfo, QString> > fList;

	if ( !(m_nReservedFlags & PVM_DONT_COPY_VM) )
		/* get full directories and files lists for migration */
		if ((nRetCode = GetEntryLists(m_sVmHomePath, dList, fList)) != PRL_ERR_SUCCESS)
			return nRetCode;

	if (PRL_FAILED(nRetCode = SendStartRequest()))
		return nRetCode;

	/* calculate total transaction size */
	for (i = 0; i < fList.size(); ++i)
		m_nTotalSize += fList.at(i).first.size();

	m_pSender = SmartPtr<CVmFileListCopySender>(new CVmFileListCopySenderClient(m_pIoClient));
	m_pVmCopySource = SmartPtr<CVmFileListCopySource>(
			new CVmFileListCopySource(
				m_pSender.getImpl(),
				m_pVmConfig->getVmIdentification()->getVmUuid(),
				m_sVmHomePath,
				m_nTotalSize,
				getLastError(),
				m_nTimeout));
	m_pVmCopySource->SetRequest(getRequestPackage());
	m_pVmCopySource->SetVmDirectoryUuid(m_sVzDirUuid);
	m_pVmCopySource->SetProgressNotifySender(NotifyClientsWithProgress);

	nRetCode = m_pVmCopySource->Copy(dList, fList);
	if (PRL_FAILED(nRetCode))
		WRITE_TRACE(DBG_FATAL, "Error occurred while migration with code [%#x][%s]",
			nRetCode, PRL_RESULT_TO_STRING(nRetCode));

	return nRetCode;
}
示例#14
0
bool Socket::accept ( Socket& new_socket ) const
{
  if (!is_valid())
  {
    return false;
  }

  socklen_t addr_length = sizeof( _sockaddr );
  new_socket._sd = ::accept(_sd, const_cast<sockaddr*>( (const sockaddr*) &_sockaddr), &addr_length );

#ifdef TARGET_WINDOWS
  if (new_socket._sd == INVALID_SOCKET)
#else
  if (new_socket._sd <= 0)
#endif
  {
    errormessage( getLastError(), "Socket::accept" );
    return false;
  }

  return true;
}
void GhostManager::flushScopeAlwaysObjects()
{
   scopeAlwaysList.sort();

   SortableVector<AddListEntry>::iterator i;
   for(i = scopeAlwaysList.begin(); i != scopeAlwaysList.end(); i++)
   {
      if(!manager->registerObject((*i).obj))
      {
         if(!getLastError()[0])
            setLastError("Invalid packet.");
         return;
      }
      cleanupGroup->addObject((*i).obj);
      if((*i).obj->netFlags.test(SimNetObject::PolledGhost))
         owner->getEventManager()->addPolledObject((*i).obj);
   }
   scopeAlwaysList.clear();
   CSDelegate *delegate = (CSDelegate *) manager->findObject(SimCSDelegateId);
   if(delegate)
      delegate->onGhostAlwaysDone(getOwner());
}
示例#16
0
int Socket::send ( const char* data, const unsigned int len )
{
  fd_set set_w, set_e;
  struct timeval tv;
  int  result;

  if (!is_valid())
  {
    return 0;
  }

  // fill with new data
  tv.tv_sec  = 0;
  tv.tv_usec = 0;

  FD_ZERO(&set_w);
  FD_ZERO(&set_e);
  FD_SET(_sd, &set_w);
  FD_SET(_sd, &set_e);

  result = select(FD_SETSIZE, &set_w, NULL, &set_e, &tv);

  if (result < 0)
  {
    XBMC->Log(LOG_ERROR, "Socket::send  - select failed");
    _sd = INVALID_SOCKET;
    return 0;
  }

  int status = ::send(_sd, data, len, 0 );

  if (status == -1)
  {
    errormessage( getLastError(), "Socket::send");
    XBMC->Log(LOG_ERROR, "Socket::send  - failed to send data");
    _sd = INVALID_SOCKET;
  }
  return status;
}
SFR_RetCode SequenceFileReader::getPosition(Int64& pos)
{
  QRLogger::log(CAT_SQL_HDFS_SEQ_FILE_READER, LL_DEBUG, "SequenceFileReader::getPosition(%ld) called.", pos);

  if (initJNIEnv() != JOI_OK)
     return SFR_ERROR_GETPOS_EXCEPTION;

  // long getPosition();
  tsRecentJMFromJNI = JavaMethods_[JM_GETPOS].jm_full_name;
  Int64 result = jenv_->CallLongMethod(javaObj_, JavaMethods_[JM_GETPOS].methodID);

  if (result == -1) 
  {
    logError(CAT_SQL_HDFS_SEQ_FILE_READER, "SequenceFileReader::getPosition()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return SFR_ERROR_GETPOS_EXCEPTION;
  }

  pos = result;
  jenv_->PopLocalFrame(NULL);
  return SFR_OK;
}
示例#18
0
const int socketer::accetper()
{
    //int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
    
    int acceptfd = accept(fd_, (struct sockaddr*)NULL, NULL);
       // printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
        //continue;
    printf("listfd=%d,clinetfd=%d\n",fd_,acceptfd);
    if (acceptfd >= 0) {
        setNonBlock(acceptfd);
       // handleSocket = new Socket();
       // handleSocket->setUp(fd, (struct sockaddr *)&addr);
    } else {
        int error = getLastError();
        if (error != EAGAIN) {
            printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
        }
    }

    //setNonBlock(acceptfd);
    return acceptfd;
}
Int32 HdfsClient::hdfsRead(const char* data, Int64 len, HDFS_Client_RetCode &hdfsClientRetcode)
{
   QRLogger::log(CAT_SQL_HDFS, LL_DEBUG, "HdfsClient::hdfsWrite(%ld) called.", len);

   if (initJNIEnv() != JOI_OK) {
      hdfsClientRetcode = HDFS_CLIENT_ERROR_HDFS_READ_EXCEPTION;
      return 0;
   }
   jobject j_buf = jenv_->NewDirectByteBuffer((BYTE *)data, len);
   if (j_buf == NULL) {
      GetCliGlobals()->setJniErrorStr(getErrorText(HDFS_CLIENT_ERROR_HDFS_READ_PARAM));
      jenv_->PopLocalFrame(NULL);
      return HDFS_CLIENT_ERROR_HDFS_READ_PARAM;
   }
  if (hdfsStats_ != NULL)
     hdfsStats_->getHdfsTimer().start();

  tsRecentJMFromJNI = JavaMethods_[JM_HDFS_READ].jm_full_name;
  jint bytesRead = 0;
  bytesRead = jenv_->CallIntMethod(javaObj_, JavaMethods_[JM_HDFS_READ].methodID, j_buf);

  if (hdfsStats_ != NULL) {
      hdfsStats_->incMaxHdfsIOTime(hdfsStats_->getHdfsTimer().stop());
      hdfsStats_->incHdfsCalls();
  }
  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails();
    logError(CAT_SQL_HDFS, __FILE__, __LINE__);
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsRead()", getLastError());
    jenv_->PopLocalFrame(NULL);
    hdfsClientRetcode = HDFS_CLIENT_ERROR_HDFS_READ_EXCEPTION;
    return 0;
  }
  jenv_->PopLocalFrame(NULL);
  hdfsClientRetcode = HDFS_CLIENT_OK;
  return bytesRead; 
}
Task_MigrateCtTarget::Task_MigrateCtTarget(
	const QObject *parent,
	const SmartPtr<CDspDispConnection> &pDispConnection,
	CDispToDispCommandPtr pCmd,
	const SmartPtr<IOPackage> &p)
   :
	CDspTaskHelper(pDispConnection->getUserSession(), p),
	Task_DispToDispConnHelper(getLastError()),
	m_pParent(parent),
	m_pCheckDispConnection(pDispConnection),
	m_pCheckPackage(p),
	m_cDstHostInfo(CDspService::instance()->getHostInfo()->data()),
	m_pOpaqueLock(NULL),
	m_nSteps(0),
	m_nBundlePermissions(0),
	m_nConfigPermissions(0)
{
	CVmMigrateCheckPreconditionsCommand * pCheckCmd =
		CDispToDispProtoSerializer::CastToDispToDispCommand<CVmMigrateCheckPreconditionsCommand>(pCmd);

	m_hConnHandle = pDispConnection->GetConnectionHandle();
	m_nMigrationFlags = pCheckCmd->GetMigrationFlags();
	m_nReservedFlags = pCheckCmd->GetReservedFlags();
	m_nVersion = pCheckCmd->GetVersion();
	m_sVmConfig = pCheckCmd->GetVmConfig();
	m_nPrevVmState = pCheckCmd->GetVmPrevState();
	m_sVmDirPath = pCheckCmd->GetTargetVmHomePath();
	m_sSrcHostInfo = pCheckCmd->GetSourceHostHardwareInfo();

	/* initialize all vars from pCheckCmd - after exit from constructor package buffer will invalid */

	bool bConnected = QObject::connect(
		&CDspService::instance()->getIOServer(),
		SIGNAL(onClientDisconnected(IOSender::Handle)),
		SLOT(clientDisconnected(IOSender::Handle)),
		Qt::DirectConnection);
	PRL_ASSERT(bConnected);
}
示例#21
0
/*
 * Read from an open file in storage, returning the number of bytes read or
 * -1 for the end of the file. May read less than the length of the buffer.
 *
 * If not successful *ppszError will set to point to an error string,
 * on success it will be set to NULL.
 */
long
storageRead(char** ppszError, int handle, char* buffer, long length) {
    long bytesRead;

    *ppszError = NULL;
    if (0 == length) {
        return 0;
    }

    bytesRead = pcsl_file_read((void *)handle, (unsigned char*)buffer, length);

    REPORT_INFO2(LC_CORE, "storageRead on fd %d res = %ld\n",
          handle, bytesRead);

    if (-1 == bytesRead) {
        *ppszError = getLastError("storageRead()");
    } else if (0 == bytesRead) {
        /* end of file in java is -1 */
        bytesRead = -1;
    }

    return bytesRead;
}
示例#22
0
int SSLSocket::checkSSL(int ret) {
	if(!ssl) {
		return -1;
	}
	if(ret <= 0) {
		/* inspired by boost.asio (asio/ssl/detail/impl/engine.ipp, function engine::perform) and
		the SSL_get_error doc at <https://www.openssl.org/docs/ssl/SSL_get_error.html>. */
		auto err = SSL_get_error(ssl, ret);
		switch(err) {
		case SSL_ERROR_NONE:		// Fallthrough - YaSSL doesn't for example return an openssl compatible error on recv fail
		case SSL_ERROR_WANT_READ:	// Fallthrough
		case SSL_ERROR_WANT_WRITE:
			return -1;
		case SSL_ERROR_ZERO_RETURN:
			throw SocketException(STRING(CONNECTION_CLOSED));
		case SSL_ERROR_SYSCALL:
			{
				auto sys_err = ERR_get_error();
				if(sys_err == 0) {
					if(ret == 0) {
						dcdebug("TLS error: call ret = %d, SSL_get_error = %d, ERR_get_error = %d\n", ret, err, sys_err);
						throw SSLSocketException(STRING(CONNECTION_CLOSED));
					}
					sys_err = getLastError();
				}
				throw SSLSocketException(sys_err);
			}
		default:
			/* don't bother getting error messages from the codes because 1) there is some
			additional management necessary (eg SSL_load_error_strings) and 2) openssl error codes
			aren't shown to the end user; they only hit standard output in debug builds. */
			dcdebug("TLS error: call ret = %d, SSL_get_error = %d, ERR_get_error = %d\n", ret, err, ERR_get_error());
			throw SSLSocketException(STRING(TLS_ERROR));
		}
	}
	return ret;
}
示例#23
0
文件: VPoll.cpp 项目: Jamol/kuma
KMError VPoll::wait(uint32_t wait_ms)
{
#ifdef KUMA_OS_WIN
    int num_revts = WSAPoll(&poll_fds_[0], poll_fds_.size(), wait_ms);
#else
    int num_revts = poll(&poll_fds_[0], (nfds_t)poll_fds_.size(), wait_ms);
#endif
    if (-1 == num_revts) {
        if(EINTR == errno) {
            errno = 0;
        } else {
            KUMA_ERRTRACE("VPoll::wait, err="<<getLastError());
        }
        return KMError::INVALID_STATE;
    }

    // copy poll fds since event handler may unregister fd
    PollFdVector poll_fds = poll_fds_;
    
    int idx = 0;
    int last_idx = int(poll_fds.size() - 1);
    while(num_revts > 0 && idx <= last_idx) {
        if(poll_fds[idx].revents) {
            --num_revts;
            if(poll_fds[idx].fd < poll_items_.size()) {
                auto &item = poll_items_[poll_fds[idx].fd];
                auto revents = get_kuma_events(poll_fds[idx].revents);
                revents &= item.events;
                if (revents && item.cb) {
                    item.cb(revents, nullptr, 0);
                }
            }
        }
        ++idx;
    }
    return KMError::NOERR;
}
示例#24
0
int Socket::receive ( char* data, const unsigned int buffersize, const unsigned int minpacketsize ) const
{

  unsigned int receivedsize = 0;
  int status = 0;

  if ( !is_valid() )
  {
    return 0;
  }

  while ( (receivedsize <= minpacketsize) && (receivedsize < buffersize) )
  {
    status = ::recv(_sd, data+receivedsize, (buffersize - receivedsize), 0 );

    if ( status == SOCKET_ERROR )
    {
      int lasterror = getLastError();
#if defined(TARGET_WINDOWS)
      if ( lasterror != WSAEWOULDBLOCK)
        errormessage( lasterror, "Socket::receive" );
#else
      if ( lasterror != EAGAIN && lasterror != EWOULDBLOCK )
        errormessage( lasterror, "Socket::receive" );
#endif
      return status;
    }

    receivedsize += status;

	if (receivedsize >= minpacketsize)
		break;
  }

  return receivedsize;
}
示例#25
0
文件: Socket.cpp 项目: noriter/nit
bool TcpSocket::updateRecv()
{
	// Buffering into recv buffer
	int result = _recvBuf->receive(_handle);

	if (result == SOCKET_ERROR)
	{
		int err = getLastError();
		if (err != ERR_WOULD_BLOCK)
			return error("UpdateRecv", err);
	}
	else if (result == 0)
	{
		return error("Disconnected", ERR_CONN_RESET);
	}

	// At this point, all the bytes underlying API could read has been read and got WOULD_BLOCK state
	bool ok = _listener && _listener->onRecv(this); // It's listeners job to examine & consume (pop-front) buffer

	if (!ok || !_connected)
		return false;

	return true;
}
示例#26
0
Error X86Compiler::_newVar(Var* var, uint32_t vType, const char* name) noexcept {
  ASMJIT_ASSERT(vType < kX86VarTypeCount);
  vType = _targetVarMapping[vType];
  ASMJIT_ASSERT(vType != kInvalidVar);

  // The assertion won't be compiled in release build, however, we want to check
  // this anyway.
  if (vType == kInvalidVar) {
    static_cast<X86Var*>(var)->reset();
    return kErrorInvalidArgument;
  }

  const VarInfo& vInfo = _x86VarInfo[vType];
  VarData* vd = _newVd(vInfo, name);

  if (vd == nullptr) {
    static_cast<X86Var*>(var)->reset();
    return getLastError();
  }

  var->_init_packed_op_sz_w0_id(Operand::kTypeVar, vInfo.getSize(), vInfo.getRegType() << 8, vd->getId());
  var->_vreg.vType = vType;
  return kErrorOk;
}
示例#27
0
int Socket::receive ( char* data, const unsigned int buffersize, const unsigned int minpacketsize ) const
{
  unsigned int receivedsize = 0;

  if ( !is_valid() )
  {
    return 0;
  }

  while ( (receivedsize <= minpacketsize) && (receivedsize < buffersize) )
  {
    int status = ::recv(_sd, data+receivedsize, (buffersize - receivedsize), 0 );

    if ( status == SOCKET_ERROR )
    {
      errormessage( getLastError(), "Socket::receive" );
      return status;
    }

    receivedsize += status;
  }

  return receivedsize;
}
HDFS_Client_RetCode HdfsClient::getHiveTableMaxModificationTs( Int64& maxModificationTs, const char * tableDirPaths,  int levelDeep)
{
  QRLogger::log(CAT_SQL_HBASE, LL_DEBUG, "Enter HDFSClient_JNI::getHiveTableMaxModificationTs(%s) called.",tableDirPaths);
  if (initJNIEnv() != JOI_OK)
     return HDFS_CLIENT_ERROR_HIVE_TBL_MAX_MODIFICATION_TS_PARAM;
  if (getInstance() == NULL)
     return HDFS_CLIENT_ERROR_HIVE_TBL_MAX_MODIFICATION_TS_PARAM; 
  jstring js_tableDirPaths = jenv_->NewStringUTF(tableDirPaths);
  if (js_tableDirPaths == NULL)
  {
    GetCliGlobals()->setJniErrorStr(getErrorText(HDFS_CLIENT_ERROR_HIVE_TBL_MAX_MODIFICATION_TS_PARAM));
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HIVE_TBL_MAX_MODIFICATION_TS_PARAM;
  }

  jint jlevelDeep = levelDeep;
  tsRecentJMFromJNI = JavaMethods_[JM_HIVE_TBL_MAX_MODIFICATION_TS].jm_full_name;
  jlong jresult = jenv_->CallStaticLongMethod(javaClass_,
                                          JavaMethods_[JM_HIVE_TBL_MAX_MODIFICATION_TS].methodID,
										  js_tableDirPaths, jlevelDeep);
  jenv_->DeleteLocalRef(js_tableDirPaths);
  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails(jenv_);
    logError(CAT_SQL_HBASE, __FILE__, __LINE__);
    logError(CAT_SQL_HBASE, "HDFSClientI::getHiveTableMaxModificationTs()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HIVE_TBL_MAX_MODIFICATION_TS_EXCEPTION;
  }
  QRLogger::log(CAT_SQL_HBASE, LL_DEBUG,
       "Exit HDFSClient_JNI::getHiveTableMaxModificationTs() called.");
  maxModificationTs = jresult;
  jenv_->PopLocalFrame(NULL);

  return HDFS_CLIENT_OK;
}
示例#29
0
req::ptr<File>
HttpStreamWrapper::open(const String& filename,
                        const String& mode,
                        int options,
                        const req::ptr<StreamContext>& context) {
  if (RuntimeOption::ServerHttpSafeMode && !is_cli_mode()) {
    return nullptr;
  }

  if (strncmp(filename.data(), "http://",  sizeof("http://")  - 1) &&
      strncmp(filename.data(), "https://", sizeof("https://") - 1)) {
    return nullptr;
  }

  Array headers;
  String method = s_GET;
  String post_data = null_string;
  String proxy_host;
  String proxy_user;
  String proxy_pass;
  int proxy_port = -1;
  int max_redirs = 20;
  int timeout = -1;
  bool ignore_errors = false;

  if (context && !context->getOptions().isNull() &&
      !context->getOptions()[s_http].isNull()) {
    Array opts = context->getOptions()[s_http].toArray();
    if (opts.exists(s_method)) {
      method = opts[s_method].toString();
    }
    if (opts.exists(s_header)) {
      Array lines;
      if (opts[s_header].isString()) {
        lines = StringUtil::Explode(
          opts[s_header].toString(), "\r\n").toArray();
      } else if (opts[s_header].isArray()) {
        lines = opts[s_header];
      }

      for (ArrayIter it(lines); it; ++it) {
        Array parts = StringUtil::Explode(
          it.second().toString(), ":", 2).toArray();
        headers.set(parts.rvalAt(0), parts.rvalAt(1));
      }
    }
    if (opts.exists(s_user_agent) && !headers.exists(s_User_Agent)) {
      headers.set(s_User_Agent, opts[s_user_agent]);
    }
    if (opts.exists(s_max_redirects)) {
      max_redirs = opts[s_max_redirects].toInt64();
    }
    if (opts.exists(s_timeout)) {
      timeout = opts[s_timeout].toInt64();
    }
    if (opts.exists(s_ignore_errors)) {
      ignore_errors = opts[s_ignore_errors].toBoolean();
    }
    if (opts.exists(s_proxy)) {
      Variant host = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_HOST);
      Variant port = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PORT);
      if (!same(host, false) && !same(port, false)) {
        proxy_host = host.toString();
        proxy_port = port.toInt64();
        Variant user = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_USER);
        Variant pass = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PASS);
        if (!same(user, false) && !same(pass, false)) {
          proxy_user = user.toString();
          proxy_pass = pass.toString();
        }
      }
    }
    post_data = opts[s_content].toString();
  }

  if (!headers.exists(s_User_Agent)) {
    auto default_user_agent = ThreadInfo::s_threadInfo.getNoCheck()
      ->m_reqInjectionData.getUserAgent();
    if (!default_user_agent.empty()) {
      headers.set(s_User_Agent, default_user_agent);
    }
  }
  auto file = req::make<UrlFile>(method.data(), headers,
                                    post_data, max_redirs,
                                    timeout, ignore_errors);
  file->setStreamContext(context);
  file->setProxy(proxy_host, proxy_port, proxy_user, proxy_pass);
  bool ret = file->open(filename, mode);
  if (!ret) {
    raise_warning("Failed to open %s (%s)", filename.data(),
                  file->getLastError().c_str());
    return nullptr;
  }
  return file;
}
PRL_RESULT Task_GetBackupTreeSource::prepareTask()
{
	PRL_RESULT ret = PRL_ERR_SUCCESS;
	try {
		if ((m_nFlags & (PBT_BACKUP_ID | PBT_CHAIN)) && m_sUuid.isEmpty()) {
			WRITE_TRACE(DBG_FATAL, "A backup UUID must be specified to get information "
								   "on a single backup or backup chain.");
			throw PRL_ERR_INVALID_PARAM;
		}
		if ((m_nFlags & PBT_BACKUP_ID) && (m_nFlags & PBT_CHAIN)) {
			WRITE_TRACE(DBG_FATAL, "The PBT_BACKUP_ID and PBT_CHAIN flags are mutually exclusive.");
			throw PRL_ERR_INVALID_PARAM;
		}
	} catch (PRL_RESULT code) {
		getLastError()->setEventCode(code);
		ret = code;
		WRITE_TRACE(DBG_FATAL, "An error occurred while preparing to get the backup tree [%#x][%s]",
			code, PRL_RESULT_TO_STRING(code));
	}

	return ret;
}