示例#1
0
JNIEXPORT jstring JNICALL Java_com_beegfs_JBeeGFS_getMountID(JNIEnv* env, jobject obj) {
   char* mountID;
   bool res = beegfs_getMountID(getFd(env, obj), &mountID);
   if (res) {
      jstring jret = env->NewStringUTF(mountID);
      free(mountID);
      return jret;
   } else {
      return NULL;
   }
}
示例#2
0
JNIEXPORT jstring JNICALL Java_com_beegfs_JBeeGFS_getRuntimeConfigPath(JNIEnv* env, jobject obj) {
   char* runtimeConfigPath;
   bool res = beegfs_getRuntimeConfigFile(getFd(env, obj), &runtimeConfigPath);
   if (res) {
      jstring jret = env->NewStringUTF(runtimeConfigPath);
      free(runtimeConfigPath);
      return jret;
   } else {
      return NULL;
   }
}
示例#3
0
void SslServerConn::createSsl()
{
    if (_ssl)
    {
        PARROT_ASSERT(false);
    }
    _ssl = SslHelper::genSsl(_sslCtx);
    PARROT_ASSERT(_ssl);
    BIO* bio = BIO_new_socket(getFd(), BIO_NOCLOSE);
    SSL_set_bio(_ssl, bio, bio);
}
  void Stream::connect(const std::string& ipaddr, unsigned short int port)
  {
    log_debug("connect to " << ipaddr << " port " << port);

    Addrinfo ai(ipaddr, port);

    log_debug("do connect");
    for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)
    {
      try
      {
        Socket::create(it->ai_family, SOCK_STREAM, 0);
      }
      catch (const Exception&)
      {
        continue;
      }

      if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)
      {
        // save our information
        memmove(&peeraddr, it->ai_addr, it->ai_addrlen);
        return;
      }

      if (errno == EINPROGRESS && getTimeout() > 0)
      {
        poll(POLLOUT);

        if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)
        {
          // save our information
          memmove(&peeraddr, it->ai_addr, it->ai_addrlen);
          return;
        }
      }

    }

    throw Exception("connect");
  }
示例#5
0
bool PlainFile::closeImpl() {
  bool ret = true;
  s_pcloseRet = 0;
  if (!isClosed()) {
    if (m_stream) {
      s_pcloseRet = fclose(m_stream);
      m_stream = nullptr;
    } else if (getFd() >= 0) {
      s_pcloseRet = ::close(getFd());
    }
    if (m_buffer) {
      free(m_buffer);
      m_buffer = nullptr;
    }
    ret = (s_pcloseRet == 0);
    setIsClosed(true);
    setFd(-1);
  }
  File::closeImpl();
  return ret;
}
示例#6
0
int64_t PlainFile::readImpl(char *buffer, int64_t length) {
  assert(valid());
  assert(length > 0);
  // use read instead of fread to handle EOL in stdin
  size_t ret = ::read(getFd(), buffer, length);
  if (ret == 0
   || (ret == (size_t)-1
    && errno != EWOULDBLOCK && errno != EINTR && errno != EBADF)) {
    setEof(true);
  }
  return ret == (size_t)-1 ? 0 : ret;
}
  void Stream::accept(const Server& server)
  {
    close();

    socklen_t peeraddr_len;
    peeraddr_len = sizeof(peeraddr);
    log_debug("accept " << server.getFd());
    int fd = ::accept(server.getFd(), reinterpret_cast <struct sockaddr *> (&peeraddr), &peeraddr_len);
    if (fd < 0)
      throw Exception("accept");
    setFd(fd);
    log_debug("accepted " << server.getFd() << " => " << getFd());
  }
示例#8
0
bool SSLSocket::checkLiveness() {
  if (getFd() == -1) {
    return false;
  }

  pollfd p;
  p.fd = getFd();
  p.events = POLLIN | POLLERR | POLLHUP | POLLPRI;
  p.revents = 0;
  if (poll(&p, 1, 0) > 0 && p.revents > 0) {
    char buf;
    if (m_data->m_ssl_active) {
      while (true) {
        int n = SSL_peek(m_data->m_handle, &buf, sizeof(buf));
        if (n <= 0) {
          int err = SSL_get_error(m_data->m_handle, n);
          if (err == SSL_ERROR_SYSCALL) {
            return errno == EAGAIN;
          }

          if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
            /* re-negotiate */
            continue;
          }

          /* any other problem is a fatal error */
          return false;
        }
        /* either peek succeeded or there was an error; we
         * have set the alive flag appropriately */
        break;
      }
    } else if (0 == recv(getFd(), &buf, sizeof(buf), MSG_PEEK) &&
               errno != EAGAIN) {
      return false;
    }
  }
  return true;
}
示例#9
0
void Quorum::start(boost::shared_ptr<sys::Poller> p) {
    poller = p;
    QPID_LOG(debug, "Connecting to quorum service.");
    cman = cman_init(0);
    if (cman == 0) throw ErrnoException("Can't connect to cman service");
    if (!cman_is_quorate(cman)) {
        QPID_LOG(notice, "Waiting for cluster quorum.");
        while(!cman_is_quorate(cman)) sys::sleep(5);
    }
    int err = cman_start_notification(cman, cmanCallbackFn);
    if (err != 0) throw ErrnoException("Can't register for cman notifications");
    watch(getFd());
}
示例#10
0
JNIEXPORT void JNICALL Java_org_lirc_socket_UnixSocketImpl_close
		(JNIEnv *env, jobject obj) {
	int fd = getFd(env, obj);

#ifdef DEBUG
	printf("junixsocket: Closing %i\n", fd);
#endif

	if (close(fd) < 0) {
		throwIOExc(env, strerror(errno));
		return;
	}
}
示例#11
0
void TcpClientBase::realConnect(bool useSsl){
	if(::connect(m_socket.get(), static_cast<const ::sockaddr *>(SockAddr::getData()), SockAddr::getSize()) != 0){
		if(errno != EINPROGRESS){
			DEBUG_THROW(SystemException);
		}
	}
	if(useSsl){
		LOG_POSEIDON_INFO("Initiating SSL handshake...");

		AUTO(ssl, g_clientSslFactory.createSsl());
		boost::scoped_ptr<SslFilterBase> filter(new SslFilter(STD_MOVE(ssl), getFd()));
		initSsl(STD_MOVE(filter));
	}
}
static void openAndLockNameFile(const std::string &nameFile, T &fstream)
{
    fstream.open(nameFile);
    if (!fstream.is_open()) {
        LogError("Unable to open file" << nameFile << ": " << GetErrnoString(errno));
        ThrowMsg(PermissibleSetException::FileOpenError, "Unable to open file ");
    }

    int ret = TEMP_FAILURE_RETRY(flock(getFd(fstream), LOCK_EX));
    if (ret == -1) {
        LogError("Unable to lock file " << nameFile << ": " << GetErrnoString(errno));
        ThrowMsg(PermissibleSetException::FileLockError, "Unable to lock file");
    }
}
示例#13
0
void jsTTY_t :: onCtrlC( void )
{
   exitStatus_ = 3 ;
   exitRequested_ = true ;
   tcsetattr( getFd(), TCSANOW, &oldTermState_ );
   
   // flag <Ctrl-C> for menu code
   FILE *fCtrlc = fopen( "/tmp/ctrlc", "wb" );
   if( fCtrlc )
   {
      fprintf( fCtrlc, "<Ctrl-C> hit\n" );
      fclose( fCtrlc );
   }
}
示例#14
0
JNIEXPORT void JNICALL Java_org_lirc_socket_UnixSocketImpl_shutdownOutput
		(JNIEnv *env, jobject obj) {
	int fd;
	fd = getFd(env, obj);

#ifdef DEBUG
	printf("junixsocket: Shutting down output for %i\n", fd);
#endif

	if (shutdown(fd, 1) < 0) {
		throwIOExc(env, strerror(errno));
		return;
	}
}
示例#15
0
  void GnuTlsStream::handshake(const GnuTlsServer& server)
  {
    log_debug("gnutls_init(session, GNUTLS_SERVER)");
    int ret = gnutls_init(&_session, GNUTLS_SERVER);
    if (ret != 0)
      throw GnuTlsException("gnutls_init", ret);

    log_debug("gnutls_set_default_priority");
    ret = gnutls_set_default_priority(_session);
    if (ret != 0)
      throw GnuTlsException("gnutls_set_default_priority", ret);

    log_debug("gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, "
      << server.getCred() << ')');
    ret = gnutls_credentials_set(_session, GNUTLS_CRD_CERTIFICATE, server.getCred());
    if (ret != 0)
      throw GnuTlsException("gnutls_credentials_set", ret);

    log_debug("gnutls_dh_set_prime_bits(session, 1024)");
    gnutls_dh_set_prime_bits(_session, 1024);

    _fdInfo.fd = getFd();
    _fdInfo.timeout = getTimeout();

    log_debug("gnutls_transport_set_ptr(ptr)");
    gnutls_transport_set_ptr(_session, static_cast<gnutls_transport_ptr_t>(&_fdInfo));

    log_debug("gnutls_transport_set_pull_function()");
    gnutls_transport_set_pull_function(_session, pull_func);

    log_debug("gnutls_transport_set_push_function()");
    gnutls_transport_set_push_function(_session, push_func);

    // non-blocking/with timeout

    _fdInfo.timeout = 10000;

    log_debug("gnutls_handshake");
    ret = gnutls_handshake(_session);
    log_debug("gnutls_handshake => " << ret);

    if (ret != 0)
      throw GnuTlsException("gnutls_handshake", ret);

    _connected = true;
    _fdInfo.timeout = getTimeout();

    log_debug("ssl-handshake was completed");
  }
/*
 * public native void sync()
 */
static void fd_sync(JNIEnv* env, jobject obj) {
    int fd = getFd(env, obj);

    if (fsync(fd) != 0) {
        /*
         * If fd is a socket, then fsync(fd) is defined to fail with
         * errno EINVAL. This isn't actually cause for concern.
         * TODO: Look into not bothering to call fsync() at all if
         * we know we are dealing with a socket.
         */
        if (errno != EINVAL) {
            jniThrowException(env, "java/io/SyncFailedException", "");
        }
    }
}
示例#17
0
JNIEXPORT void JNICALL Java_org_lirc_socket_UnixSocketImpl_listen
		(JNIEnv *env, jobject obj, jint backlog) {
	// get fd
	int fd = getFd(env, obj);

#ifdef DEBUG
	printf("junixsocket: listen(%i, %i)\n", fd, backlog);
#endif

	// listen
	if (listen(fd, backlog) < 0) {
		close(fd);
		throwIOExc(env, strerror(errno));
		return;
	}
}
示例#18
0
JNIEXPORT jobject JNICALL Java_com_beegfs_JBeeGFS_getStripeInfo(JNIEnv* env, jobject obj) {
   unsigned patternType;
   unsigned chunkSize;
   uint16_t numTargets;
   if (beegfs_getStripeInfo(getFd(env, obj), &patternType, &chunkSize, &numTargets) ) {
      jclass jstripeinfo = env->FindClass("com/beegfs/JBeeGFS$StripeInfo");
      if (!jstripeinfo) return NULL;
      jmethodID jstripeinfoconstructor = env->GetMethodID(jstripeinfo, "<init>", "(IJI)V");
      if (!jstripeinfoconstructor) return NULL;
      jobject jstripeinfoobject = env->NewObject(jstripeinfo, jstripeinfoconstructor,
            patternType, chunkSize, numTargets);

      return jstripeinfoobject;
   } else {
      return NULL;
   }
}
示例#19
0
static unsigned long volatile *getReg(unsigned long addr){
	static void *map = 0 ;
	static unsigned prevPage = -1U ;
	unsigned page = addr & ~MAP_MASK ;
	if( page != prevPage ){
		if( map ){
		   munmap(map,MAP_SIZE);
		}
		map = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, getFd(), page );
		if( MAP_FAILED == map ){
			perror("mmap");
			exit(1);
		}
		prevPage = page ;
	}
	unsigned offs = addr & MAP_MASK ;
	return (unsigned long volatile *)((char *)map+offs);
}
示例#20
0
bool PlainFile::open(const String& filename, const String& mode) {
  int fd;
  FILE *f;
  assert(m_stream == nullptr);
  assert(getFd() == -1);

  // For these definded in php fopen but C stream have different modes
  switch (mode[0]) {
    case 'x':
      if (mode.find('+') == -1) {
        fd = ::open(filename.data(), O_WRONLY|O_CREAT|O_EXCL, 0666);
        if (fd < 0) return false;
        f = fdopen(fd, "w");
      } else {
        fd = ::open(filename.data(), O_RDWR|O_CREAT|O_EXCL, 0666);
        if (fd < 0) return false;
        f = fdopen(fd, "w+");
      }
      break;
    case 'c':
      if (mode.find('+') == -1) {
        fd = ::open(filename.data(), O_WRONLY|O_CREAT, 0666);
        if (fd < 0) return false;
        f = fdopen(fd, "w");
      } else {
        fd = ::open(filename.data(), O_RDWR|O_CREAT, 0666);
        if (fd < 0) return false;
        f = fdopen(fd, "w+");
      }
      break;
    default:
      f = fopen(filename.data(), mode.data());
  }
  if (!f) {
    return false;
  }
  m_stream = f;
  setFd(fileno(f));
  m_buffer = (char *)malloc(BUFSIZ);
  setName(filename.toCppString());
  if (m_buffer)
    setbuffer(f, m_buffer, BUFSIZ);
  return true;
}
示例#21
0
int Sequencer_oss::transmitVoiceMessage(void) {
   synth_write_message[0] = EV_CHN_VOICE;
   synth_write_message[1] = synth_message_curr_device;
   synth_write_message[2] = synth_message_buffer[0] & 0xf0;
   synth_write_message[3] = synth_message_buffer[0] & 0x0f;
   synth_write_message[4] = synth_message_buffer[1];
   synth_write_message[5] = synth_message_buffer[2];
   synth_write_message[6] = 0;
   synth_write_message[7] = 0;

   int status;
   status = ::write(getFd(), synth_write_message, sizeof(synth_write_message));
 
   if (status > 0) {
      return 1;
   } else {
      return 0;
   }
}
示例#22
0
static void startOperation(asyncOp *op,
                           IoActionTy action,
                           uint64_t usTimeout)
{
  selectBase *localBase = (selectBase*)op->info.object->base;
  op->info.currentAction = action;
  
  if (op->info.currentAction == ioMonitor)
    op->info.status = aosMonitoring;
  else
    op->info.status = aosPending;
  
  if (op->useInternalBuffer && (action == ioWrite || action == ioWriteMsg)) {
    if (op->internalBuffer == 0) {
      op->internalBuffer = malloc(op->info.transactionSize);
      op->internalBufferSize = op->info.transactionSize;      
    } else if (op->internalBufferSize < op->info.transactionSize) {
      op->internalBufferSize = op->info.transactionSize;
      op->internalBuffer = realloc(op->internalBuffer,
                                   op->info.transactionSize);
    }
    memcpy(op->internalBuffer, op->info.buffer, op->info.transactionSize);
  }


  OpLinksMap &links = isWriteOperation(action) ?
    localBase->writeOps : localBase->readOps;
  
  switch (action) {
    case ioMonitorStop :
      asyncOpUnlink(op);
      break;
    default :
      asyncOpLink(getFdOperations(links, getFd(op)), op);
      break;
  }

  if (action == ioMonitorStop || action == ioMonitor)
    selectPostEmptyOperation((asyncBase*)localBase);
  
  if (usTimeout)
    startTimer(op, usTimeout, 0);
}
示例#23
0
void TCPPipe::initializePipe(TCPPipe::Endianness sEndianness)
	{
	/* Set socket options: */
	TCPSocket::setNoDelay(true);
	
	if(sEndianness==LittleEndian)
		{
		#if __BYTE_ORDER==__BIG_ENDIAN
		readMustSwapEndianness=writeMustSwapEndianness=true;
		#endif
		}
	else if(sEndianness==BigEndian)
		{
		#if __BYTE_ORDER==__LITTLE_ENDIAN
		readMustSwapEndianness=writeMustSwapEndianness=true;
		#endif
		}
	else if(sEndianness==Automatic)
		{
		/* Exchange a magic value to test for endianness on the other end: */
		unsigned int magic=0x12345678U;
		blockingWrite(&magic,sizeof(unsigned int));
		blockingRead(&magic,sizeof(unsigned int));
		if(magic==0x78563412U)
			readMustSwapEndianness=true;
		else if(magic!=0x12345678U)
			Misc::throwStdErr("Comm::TCPPipe: Unable to establish connection with host %s on port %d",getPeerHostname().c_str(),getPeerPortId());
		}
	
	/* Allocate the read and write buffers: */
	int maxSegSize=-1;
	socklen_t maxSegLen=sizeof(int);
	if(getsockopt(getFd(),IPPROTO_TCP,TCP_MAXSEG,&maxSegSize,&maxSegLen)<0)
		Misc::throwStdErr("Comm::TCPPipe: Unable to determine maximum TCP segment size");
	bufferSize=size_t(maxSegSize);
	readBuffer=new char[bufferSize];
	rbPos=readBuffer;
	readSize=0;
	writeBuffer=new char[bufferSize];
	wbPos=writeBuffer;
	writeSize=bufferSize;
	}
示例#24
0
int SerialImpl::write(void * buf, int size)
{
	if ( (NULL == buf) || (0 >= size) ) {
		kuDebug (kuERR, "[SerialImpl::read] input is invalid \n");
		return (kuNOK);
	}

	if (kuTRUE == kuCanPrint (kuDATA)) {
		kuDebug (kuMON, "[SerialImpl::write] dev(%s) ----------------------\n", m_strDevName.c_str());
		kuStd::dump (size, (char *)buf);
	}

	if (size != writeWithControl (getFd(), (char *)buf, size)) {
		return (kuNOK);
	}

	kuDebug (kuTRACE, "[SerialImpl::write] dev(%s) : writes(%d)\n", getDevName(), size);

	return (kuOK);
}
static jlong android_os_ParcelFileDescriptor_getStatSize(JNIEnv* env,
    jobject clazz)
{
    jint fd = getFd(env, clazz);
    if (fd < 0) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "bad file descriptor");
        return -1;
    }
    
    struct stat st;
    if (fstat(fd, &st) != 0) {
        return -1;
    }
    
    if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
        return st.st_size;
    }
    
    return -1;
}
示例#26
0
int Sequencer_oss::write(int device, int aByte) {
   int status = 0;

   switch (getOutputType(device)) {
      case MIDI_EXTERNAL:
         midi_write_packet[1] = (uchar) (0xff & aByte);
         midi_write_packet[2] = getOutDeviceValue(device);
         status = ::write(getFd(), midi_write_packet,sizeof(midi_write_packet));
         break;
      case MIDI_INTERNAL:
         status = writeInternal(getOutDeviceValue(device), aByte);
         break;
   }

   if (status > 0) {
      return 1;
   } else {
      return 0;
   }

}
示例#27
0
void udpRxPoll_t :: onDataAvail( void )
{
   sockaddr_in fromAddr ;
   deviceMsg_t msg ;
   socklen_t   fromSize = sizeof( fromAddr );
   int numRead = recvfrom( getFd(), 
                           (char *)&msg, sizeof( msg ), 0,
                           (struct sockaddr *)&fromAddr, 
                           &fromSize );
   if( offsetof( deviceMsg_t, data_ ) <= numRead )
   {
      // check message lengths
      if( deviceMsg_t :: audio_e == msg.type_ )
      {
         unsigned const expected = sizeof( msg )-sizeof( msg.data_ )+msg.length_ ;
         if( expected != numRead )
         {
            fprintf( stderr, "Weird size : len %lu, expected %lu, read %u\n", msg.length_, expected, numRead );
            return ;
         }
      }
      else if( deviceMsg_t :: unlock_e == msg.type_ )
      {
      }
      else if( deviceMsg_t :: lock_e == msg.type_ )
      {
      }
      else
      {
         printf( "unknown msgtype %d\n", msg.type_ );
         return ;
      }
      
      onMsg( msg );
   }
   else
   {
      fprintf( stderr, "udpRecvfrom:%d:%d:%m\n", numRead, errno );
   }
}
示例#28
0
int Sequencer_oss::transmitCommonMessage(void) {
   synth_write_message[0] = EV_CHN_COMMON;
   synth_write_message[1] = synth_message_curr_device;
   synth_write_message[2] = synth_message_buffer[0] & 0xf0;
   synth_write_message[3] = synth_message_buffer[0] & 0x0f;

   switch (synth_write_message[2]) {
      case 0xB0:                           // Control change
         synth_write_message[4] = synth_message_buffer[1];
         synth_write_message[5] = 0;
         synth_write_message[6] = synth_message_buffer[2];
         synth_write_message[7] = 0;
         break;
      case 0xC0:                           // Patch change
      case 0xD0:                           // Channel pressure
         synth_write_message[4] = synth_message_buffer[1];
         synth_write_message[5] = 0;
         synth_write_message[6] = 0;
         synth_write_message[7] = 0;
         break;
      case 0xE0:                           // Pitch wheel
         synth_write_message[4] = 0;
         synth_write_message[5] = 0;
         synth_write_message[6] = synth_message_buffer[1];
         synth_write_message[7] = synth_message_buffer[2];
         break;
      default:
         std::cerr << "Unknown Common MIDI message" << std::endl;
         exit(1);
   }

   int status;
   status = ::write(getFd(), synth_write_message, sizeof(synth_write_message));

   if (status > 0) {
      return 1;
   } else {
      return 0;
   }
}
示例#29
0
文件: Server.cpp 项目: offa/seasocks
std::string Server::getStatsDocument() const {
    std::ostringstream doc;
    doc << "clear();" << std::endl;
    for (auto it = _connections.begin(); it != _connections.end(); ++it) {
        doc << "connection({";
        auto connection = it->first;
        jsonKeyPairToStream(doc,
                "since", EpochTimeAsLocal(it->second),
                "fd", connection->getFd(),
                "id", reinterpret_cast<uint64_t>(connection),
                "uri", connection->getRequestUri(),
                "addr", formatAddress(connection->getRemoteAddress()),
                "user", connection->credentials() ?
                        connection->credentials()->username : "******",
                "input", connection->inputBufferSize(),
                "read", connection->bytesReceived(),
                "output", connection->outputBufferSize(),
                "written", connection->bytesSent()
        );
        doc << "});" << std::endl;
    }
    return doc.str();
}
示例#30
0
touchPoll_t :: touchPoll_t
   ( pollHandlerSet_t &set,
     char const       *devName )
   : pollHandler_t( openTouchDev( getTouchDev(devName) ), set )
   , timer_( 0 )
   , isSerial_( isSerial(getTouchDev(devName)) )
   , state_( findStart )
   , iVal_( 0 )
   , jVal_( 0 )
   , nextTrace_( 0 )
   , lastRead_( 0 )
   , lastChar_( 0 )
{
debugPrint( "touchPoll constructed, dev = %s, fd == %d\n", getTouchDev(devName), getFd() );   
   if( isOpen() )
   {
      fcntl( fd_, F_SETFD, FD_CLOEXEC );
      fcntl( fd_, F_SETFL, O_NONBLOCK );
      setMask( POLLIN );
      set.add( *this );
      if( isSerial_ )
         timer_ = new touchPollTimer_t( *this );
   }
}