コード例 #1
0
void  CControldClient::shutdown()
{
	send(CControldMsg::CMD_SHUTDOWN);
	close_connection();
}
コード例 #2
0
ファイル: AuthSocket.cpp プロジェクト: maydayzm/mangos
/// Logon Proof command handler
bool AuthSocket::_HandleLogonProof()
{
    DEBUG_LOG("Entering _HandleLogonProof");
    ///- Read the packet
    sAuthLogonProof_C lp;
    if (!recv((char *)&lp, sizeof(sAuthLogonProof_C)))
        return false;

    ///- Check if the client has one of the expected version numbers
    bool valid_version = FindBuildInfo(_build) != NULL;

    /// <ul><li> If the client has no valid version
    if (!valid_version)
    {
        if (this->patch_ != ACE_INVALID_HANDLE)
            return false;

        ///- Check if we have the apropriate patch on the disk
        // file looks like: 65535enGB.mpq
        char tmp[64];

        snprintf(tmp, 24, "./patches/%d%s.mpq", _build, _localizationName.c_str());

        char filename[PATH_MAX];
        if (ACE_OS::realpath(tmp, filename) != NULL)
        {
            patch_ = ACE_OS::open(filename, GENERIC_READ | FILE_FLAG_SEQUENTIAL_SCAN);
        }

        if (patch_ == ACE_INVALID_HANDLE)
        {
            // no patch found
            ByteBuffer pkt;
            pkt << (uint8) CMD_AUTH_LOGON_CHALLENGE;
            pkt << (uint8) 0x00;
            pkt << (uint8) WOW_FAIL_VERSION_INVALID;
            DEBUG_LOG("[AuthChallenge] %u is not a valid client version!", _build);
            DEBUG_LOG("[AuthChallenge] Patch %s not found", tmp);
            send((char const*)pkt.contents(), pkt.size());
            return true;
        }

        XFER_INIT xferh;

        ACE_OFF_T file_size = ACE_OS::filesize(this->patch_);

        if (file_size == -1)
        {
            close_connection();
            return false;
        }

        if (!PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5))
        {
            // calculate patch md5, happens if patch was added while realmd was running
            PatchCache::instance()->LoadPatchMD5(tmp);
            PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5);
        }

        uint8 data[2] = { CMD_AUTH_LOGON_PROOF, WOW_FAIL_VERSION_UPDATE};
        send((const char*)data, sizeof(data));

        memcpy(&xferh, "0\x05Patch", 7);
        xferh.cmd = CMD_XFER_INITIATE;
        xferh.file_size = file_size;

        send((const char*)&xferh, sizeof(xferh));
        return true;
    }
    /// </ul>

    ///- Continue the SRP6 calculation based on data received from the client
    BigNumber A;

    A.SetBinary(lp.A, 32);

    // SRP safeguard: abort if A==0
    if (A.isZero())
        return false;

    Sha1Hash sha;
    sha.UpdateBigNumbers(&A, &B, NULL);
    sha.Finalize();
    BigNumber u;
    u.SetBinary(sha.GetDigest(), 20);
    BigNumber S = (A * (v.ModExp(u, N))).ModExp(b, N);

    uint8 t[32];
    uint8 t1[16];
    uint8 vK[40];
    memcpy(t, S.AsByteArray(32), 32);
    for (int i = 0; i < 16; ++i)
    {
        t1[i] = t[i * 2];
    }
    sha.Initialize();
    sha.UpdateData(t1, 16);
    sha.Finalize();
    for (int i = 0; i < 20; ++i)
    {
        vK[i * 2] = sha.GetDigest()[i];
    }
    for (int i = 0; i < 16; ++i)
    {
        t1[i] = t[i * 2 + 1];
    }
    sha.Initialize();
    sha.UpdateData(t1, 16);
    sha.Finalize();
    for (int i = 0; i < 20; ++i)
    {
        vK[i * 2 + 1] = sha.GetDigest()[i];
    }
    K.SetBinary(vK, 40);

    uint8 hash[20];

    sha.Initialize();
    sha.UpdateBigNumbers(&N, NULL);
    sha.Finalize();
    memcpy(hash, sha.GetDigest(), 20);
    sha.Initialize();
    sha.UpdateBigNumbers(&g, NULL);
    sha.Finalize();
    for (int i = 0; i < 20; ++i)
    {
        hash[i] ^= sha.GetDigest()[i];
    }
    BigNumber t3;
    t3.SetBinary(hash, 20);

    sha.Initialize();
    sha.UpdateData(_login);
    sha.Finalize();
    uint8 t4[SHA_DIGEST_LENGTH];
    memcpy(t4, sha.GetDigest(), SHA_DIGEST_LENGTH);

    sha.Initialize();
    sha.UpdateBigNumbers(&t3, NULL);
    sha.UpdateData(t4, SHA_DIGEST_LENGTH);
    sha.UpdateBigNumbers(&s, &A, &B, &K, NULL);
    sha.Finalize();
    BigNumber M;
    M.SetBinary(sha.GetDigest(), 20);

    ///- Check if SRP6 results match (password is correct), else send an error
    if (!memcmp(M.AsByteArray(), lp.M1, 20))
    {
        BASIC_LOG("User '%s' successfully authenticated", _login.c_str());

        ///- Update the sessionkey, last_ip, last login time and reset number of failed logins in the account table for this account
        // No SQL injection (escaped user name) and IP address as received by socket
        const char* K_hex = K.AsHexStr();
        LoginDatabase.PExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = '%u', os = '%s', failed_logins = 0 WHERE username = '******'", K_hex, get_remote_address().c_str(), GetLocaleByName(_localizationName), _os.c_str(), _safelogin.c_str() );
        OPENSSL_free((void*)K_hex);

        ///- Finish SRP6 and send the final result to the client
        sha.Initialize();
        sha.UpdateBigNumbers(&A, &M, &K, NULL);
        sha.Finalize();

        SendProof(sha);

        ///- Set _authed to true!
        _authed = true;
    }
    else
    {
        if (_build > 6005)                                  // > 1.12.2
        {
            char data[4] = { CMD_AUTH_LOGON_PROOF, WOW_FAIL_UNKNOWN_ACCOUNT, 3, 0};
            send(data, sizeof(data));
        }
        else
        {
            // 1.x not react incorrectly at 4-byte message use 3 as real error
            char data[2] = { CMD_AUTH_LOGON_PROOF, WOW_FAIL_UNKNOWN_ACCOUNT};
            send(data, sizeof(data));
        }
        BASIC_LOG("[AuthChallenge] account %s tried to login with wrong password!",_login.c_str ());

        uint32 MaxWrongPassCount = sConfig.GetIntDefault("WrongPass.MaxCount", 0);
        if (MaxWrongPassCount > 0)
        {
            //Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP
            LoginDatabase.PExecute("UPDATE account SET failed_logins = failed_logins + 1 WHERE username = '******'",_safelogin.c_str());

            if (QueryResult *loginfail = LoginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '******'", _safelogin.c_str()))
            {
                Field* fields = loginfail->Fetch();
                uint32 failed_logins = fields[1].GetUInt32();

                if ( failed_logins >= MaxWrongPassCount )
                {
                    uint32 WrongPassBanTime = sConfig.GetIntDefault("WrongPass.BanTime", 600);
                    bool WrongPassBanType = sConfig.GetBoolDefault("WrongPass.BanType", false);

                    if (WrongPassBanType)
                    {
                        uint32 acc_id = fields[0].GetUInt32();
                        LoginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','MaNGOS realmd','Failed login autoban',1)",
                            acc_id, WrongPassBanTime);
                        BASIC_LOG("[AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times",
                            _login.c_str(), WrongPassBanTime, failed_logins);
                    }
                    else
                    {
                        std::string current_ip = get_remote_address();
                        LoginDatabase.escape_string(current_ip);
                        LoginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','MaNGOS realmd','Failed login autoban')",
                            current_ip.c_str(), WrongPassBanTime);
                        BASIC_LOG("[AuthChallenge] IP %s got banned for '%u' seconds because account %s failed to authenticate '%u' times",
                            current_ip.c_str(), WrongPassBanTime, _login.c_str(), failed_logins);
                    }
                }
                delete loginfail;
            }
        }
    }
    return true;
}
コード例 #3
0
ファイル: socket.c プロジェクト: Papafox/imapfilter
/*
 * Read data from socket.
 */
ssize_t
socket_read(session *ssn, char *buf, size_t len, long timeout, int timeoutfail)
{
	int s;
	ssize_t r;
	fd_set fds;

	struct timeval tv;

	struct timeval *tvp;

	r = 0;
	s = 1;
	tvp = NULL;

	memset(buf, 0, len + 1);

	if (timeout > 0) {
		tv.tv_sec = timeout;
		tv.tv_usec = 0;
		tvp = &tv;
	}

	FD_ZERO(&fds);
	FD_SET(ssn->socket, &fds);
 
	if (ssn->sslconn) {
		if (SSL_pending(ssn->sslconn) > 0 ||
		    ((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0 &&
		    FD_ISSET(ssn->socket, &fds))) {
			r = socket_secure_read(ssn, buf, len);

			if (r <= 0)
				goto fail;
		}
	} else {
		if ((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0 &&
		    FD_ISSET(ssn->socket, &fds)) {
			r = read(ssn->socket, buf, len);

			if (r == -1) {
				error("reading data; %s\n", strerror(errno));
				goto fail;
			} else if (r == 0) {
				goto fail;
			}
		}
	}

	if (s == -1) {
		error("waiting to read from socket; %s\n", strerror(errno));
		goto fail;
	} else if (s == 0 && timeoutfail) {
		error("timeout period expired while waiting to read data\n");
		goto fail;
	}

	return r;
fail:
	close_connection(ssn);

	return -1;

}
コード例 #4
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
void CZapitClient::unlockPlayBack()
{
	send(CZapitMessages::CMD_SB_UNLOCK_PLAYBACK);
	close_connection();
}
コード例 #5
0
ファイル: http_load.c プロジェクト: boojoo-exp/cacheperf
static void
handle_connect( int cnum, struct timeval* nowP, int double_check )
    {
    int url_num;
    char buf[600];
    int bytes, r;

    url_num = connections[cnum].url_num;
    if ( double_check )
	{
	/* Check to make sure the non-blocking connect succeeded. */
	int err, errlen;

	if ( connect(
		 connections[cnum].conn_fd,
		 (struct sockaddr*) &connections[cnum].sa,
		 connections[cnum].sa_len ) < 0 )
	    {
	    switch ( errno )
		{
		case EISCONN:
		/* Ok! */
		break;
		case EINVAL:
		errlen = sizeof(err);
		if ( getsockopt( connections[cnum].conn_fd, SOL_SOCKET, SO_ERROR, (void*) &err, &errlen ) < 0 )
		    (void) fprintf(
			stderr, "%s: unknown connect error\n",
			urls[url_num].url_str );
		else
		    (void) fprintf(
			stderr, "%s: %s\n", urls[url_num].url_str,
			strerror( err ) );
		close_connection( cnum );
		return;
		default:
		perror( urls[url_num].url_str );
		close_connection( cnum );
		return;
		}
	    }
	}
#ifdef USE_SSL
    if ( urls[url_num].protocol == PROTO_HTTPS )
	{
	int flags;

	/* Make SSL connection. */
	if ( ssl_ctx == (SSL_CTX*) 0 )
	    {
	    SSL_load_error_strings();
	    SSLeay_add_ssl_algorithms();
	    ssl_ctx = SSL_CTX_new( SSLv23_client_method() );
	    if ( cipher != (char*) 0 )
		{
		if ( ! SSL_CTX_set_cipher_list( ssl_ctx, cipher ) )
		    {
		    (void) fprintf(
			stderr, "%s: cannot set cipher list\n", argv0 );
		    ERR_print_errors_fp( stderr );
		    close_connection( cnum );
		    return;
		    }
		}
	    }
	if ( ! RAND_status() )
	    {
	    unsigned char bytes[1024];
	    int i;
	    for ( i = 0; i < sizeof(bytes); ++i )
		bytes[i] = random() % 0xff;
	    RAND_seed( bytes, sizeof(bytes) );
	    }
	flags = fcntl( connections[cnum].conn_fd, F_GETFL, 0 );
	if ( flags != -1 )
	    (void) fcntl(
		connections[cnum].conn_fd, F_SETFL, flags & ~ (int) O_NDELAY );
	connections[cnum].ssl = SSL_new( ssl_ctx );
	SSL_set_fd( connections[cnum].ssl, connections[cnum].conn_fd );
	r = SSL_connect( connections[cnum].ssl );
	if ( r <= 0 )
	    {
	    (void) fprintf(
		stderr, "%s: SSL connection failed - %d\n", argv0, r );
	    ERR_print_errors_fp( stderr );
	    close_connection( cnum );
	    return;
	    }
	}
#endif
    connections[cnum].did_connect = 1;

    /* Format the request. */
    if ( do_proxy )
	{
#ifdef USE_SSL
	bytes = snprintf(
	    buf, sizeof(buf), "GET %s://%.500s:%d%.500s HTTP/1.0\r\n",
	    urls[url_num].protocol == PROTO_HTTPS ? "https" : "http",
	    urls[url_num].hostname, (int) urls[url_num].port,
	    urls[url_num].filename );
#else
	bytes = snprintf(
	    buf, sizeof(buf), "GET http://%.500s:%d%.500s HTTP/1.0\r\n",
	    urls[url_num].hostname, (int) urls[url_num].port,
	    urls[url_num].filename );
#endif
	}
    else
	bytes = snprintf(
	    buf, sizeof(buf), "GET %.500s HTTP/1.0\r\n",
	    urls[url_num].filename );
    bytes += snprintf(
	&buf[bytes], sizeof(buf) - bytes, "Host: %s\r\n",
	urls[url_num].hostname );
    bytes += snprintf(
	&buf[bytes], sizeof(buf) - bytes, "User-Agent: %s\r\n", VERSION );
    bytes += snprintf( &buf[bytes], sizeof(buf) - bytes, "\r\n" );

    /* Send the request. */
    connections[cnum].request_at = *nowP;
#ifdef USE_SSL
    if ( urls[url_num].protocol == PROTO_HTTPS )
	r = SSL_write( connections[cnum].ssl, buf, bytes );
    else
	r = write( connections[cnum].conn_fd, buf, bytes );
#else
    r = write( connections[cnum].conn_fd, buf, bytes );
#endif
    if ( r < 0 )
	{
	perror( urls[url_num].url_str );
	close_connection( cnum );
	return;
	}
    connections[cnum].conn_state = CNST_HEADERS;
    connections[cnum].header_state = HDST_LINE1_PROTOCOL;
    }
コード例 #6
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
/* set diseqcRepeat*/
void CZapitClient::setScanBouquetMode(const bouquetMode mode)
{
	send(CZapitMessages::CMD_SCANSETBOUQUETMODE, (const char *) & mode, sizeof(mode));
	close_connection();
}
コード例 #7
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
/* necessarily after bouquet editing operations*/
void CZapitClient::renumChannellist()
{
	send(CZapitMessages::CMD_BQ_RENUM_CHANNELLIST);
	close_connection();
}
コード例 #8
0
//-------------------------------------------------------------------------
int CTimerdClient::addTimerEvent( CTimerd::CTimerEventTypes evType, void* data, time_t announcetime, time_t alarmtime,time_t stoptime,
				  CTimerd::CTimerEventRepeat evrepeat, uint32_t repeatcount,bool forceadd)
{
	if(checkDouble(evType, data, announcetime,  alarmtime, stoptime, evrepeat,  repeatcount))//check if timer is add double
		return -1;

	if (!forceadd)
	{
		//printf("[CTimerdClient] checking for overlapping timers\n");
		CTimerd::TimerList overlappingTimer;
		overlappingTimer = getOverlappingTimers(alarmtime, stoptime);
		if (!overlappingTimer.empty())
		{
			// timerd starts eventID at 0 so we can return -1
			return -1;
		}
	}
	bool adzaptimer = false;
	if(evType == CTimerd::TIMER_ADZAP){
		evType = CTimerd::TIMER_ZAPTO;
		adzaptimer = true;
	}
	CTimerd::TransferEventInfo tei; 
	CTimerd::TransferRecordingInfo tri;
	CTimerdMsg::commandAddTimer msgAddTimer;
	VALGRIND_PARANOIA(tei);
	VALGRIND_PARANOIA(tri);
	VALGRIND_PARANOIA(msgAddTimer);
	msgAddTimer.alarmTime  = alarmtime;
	msgAddTimer.announceTime = announcetime;
	msgAddTimer.stopTime   = stoptime;
	msgAddTimer.eventType = evType;
	msgAddTimer.eventRepeat = evrepeat;
	msgAddTimer.repeatCount = repeatcount;
	int length;
	if( evType == CTimerd::TIMER_SHUTDOWN || evType == CTimerd::TIMER_SLEEPTIMER )
	{
		length = 0;
	}
	/* else if(evType == CTimerd::TIMER_NEXTPROGRAM || evType == CTimerd::TIMER_ZAPTO || */
	else if (evType == CTimerd::TIMER_ZAPTO ||
		evType == CTimerd::TIMER_IMMEDIATE_RECORD || 
		evType == CTimerd::TIMER_ADZAP)
	{
		CTimerd::EventInfo *ei=static_cast<CTimerd::EventInfo*>(data); 
		tei.apids = ei->apids;
		tei.channel_id = ei->channel_id;
		tei.epg_starttime	= ei->epg_starttime;
		tei.epgID = ei->epgID;
		tei.recordingSafety = ei->recordingSafety;
		length = sizeof( CTimerd::TransferEventInfo);
		data = &tei;
	}
	else if(evType == CTimerd::TIMER_RECORD)
	{
		CTimerd::RecordingInfo *ri=static_cast<CTimerd::RecordingInfo*>(data); 
		tri.apids = ri->apids;
		tri.channel_id = ri->channel_id;
		tri.epg_starttime	= ri->epg_starttime;
		tri.epgID = ri->epgID;
		tri.recordingSafety = ri->recordingSafety;
		strncpy(tri.recordingDir, ri->recordingDir, RECORD_DIR_MAXLEN-1);
		length = sizeof( CTimerd::TransferRecordingInfo);
		data = &tri;
	}
	else if(evType == CTimerd::TIMER_STANDBY)
	{
		length = sizeof(CTimerdMsg::commandSetStandby);
	}
	else if(evType == CTimerd::TIMER_REMIND)
	{
		length = sizeof(CTimerdMsg::commandRemind);
	}
	else if(evType == CTimerd::TIMER_EXEC_PLUGIN)
	{
		length = sizeof(CTimerdMsg::commandExecPlugin);
	}
	else
	{
		length = 0;
	}

	send(CTimerdMsg::CMD_ADDTIMER, (char*)&msgAddTimer, sizeof(msgAddTimer));

	if((data != NULL) && (length > 0))
		send_data((char*)data, length);

	CTimerdMsg::responseAddTimer response;
	receive_data((char*)&response, sizeof(response));
	close_connection();
	
	if(adzaptimer){
		adzap_eventID = response.eventID;//set adzap flag
	}
	return( response.eventID);
}
コード例 #9
0
ファイル: peer_connection.cpp プロジェクト: sfinder/graphene
    void peer_connection::destroy()
    {
      VERIFY_CORRECT_THREAD();

#if 0 // this gets too verbose
#ifndef NDEBUG
      struct scope_logger {
        fc::optional<fc::ip::endpoint> endpoint;
        scope_logger(const fc::optional<fc::ip::endpoint>& endpoint) : endpoint(endpoint) { dlog("entering peer_connection::destroy() for peer ${endpoint}", ("endpoint", endpoint)); }
        ~scope_logger() { dlog("leaving peer_connection::destroy() for peer ${endpoint}", ("endpoint", endpoint)); }
      } send_message_scope_logger(get_remote_endpoint());
#endif
#endif

      try
      {
        dlog("calling close_connection()");
        close_connection();
        dlog("close_connection completed normally");
      }
      catch ( const fc::canceled_exception& )
      {
        assert(false && "the task that deletes peers should not be canceled because it will prevent us from cleaning up correctly");
      }
      catch ( ... )
      {
        dlog("close_connection threw");
      }

      try
      {
        dlog("canceling _send_queued_messages task");
        _send_queued_messages_done.cancel_and_wait(__FUNCTION__);
        dlog("cancel_and_wait completed normally");
      }
      catch( const fc::exception& e )
      {
        wlog("Unexpected exception from peer_connection's send_queued_messages_task : ${e}", ("e", e));
      }
      catch( ... )
      {
        wlog("Unexpected exception from peer_connection's send_queued_messages_task");
      }

      try
      {
        dlog("canceling accept_or_connect_task");
        accept_or_connect_task_done.cancel_and_wait(__FUNCTION__);
        dlog("accept_or_connect_task completed normally");
      }
      catch( const fc::exception& e )
      {
        wlog("Unexpected exception from peer_connection's accept_or_connect_task : ${e}", ("e", e));
      }
      catch( ... )
      {
        wlog("Unexpected exception from peer_connection's accept_or_connect_task");
      }

      _message_connection.destroy_connection(); // shut down the read loop
    }
コード例 #10
0
ファイル: svnserve.c プロジェクト: 2asoft/freebsd
/*
 * On success, leave *EXIT_CODE untouched and return SVN_NO_ERROR. On error,
 * either return an error to be displayed, or set *EXIT_CODE to non-zero and
 * return SVN_NO_ERROR.
 */
static svn_error_t *
sub_main(int *exit_code, int argc, const char *argv[], apr_pool_t *pool)
{
  enum run_mode run_mode = run_mode_unspecified;
  svn_boolean_t foreground = FALSE;
  apr_socket_t *sock;
  apr_sockaddr_t *sa;
  svn_error_t *err;
  apr_getopt_t *os;
  int opt;
  serve_params_t params;
  const char *arg;
  apr_status_t status;
#ifndef WIN32
  apr_proc_t proc;
#endif
  svn_boolean_t is_multi_threaded;
  enum connection_handling_mode handling_mode = CONNECTION_DEFAULT;
  svn_boolean_t cache_fulltexts = TRUE;
  svn_boolean_t cache_txdeltas = TRUE;
  svn_boolean_t cache_revprops = FALSE;
  svn_boolean_t use_block_read = FALSE;
  apr_uint16_t port = SVN_RA_SVN_PORT;
  const char *host = NULL;
  int family = APR_INET;
  apr_int32_t sockaddr_info_flags = 0;
#if APR_HAVE_IPV6
  svn_boolean_t prefer_v6 = FALSE;
#endif
  svn_boolean_t quiet = FALSE;
  svn_boolean_t is_version = FALSE;
  int mode_opt_count = 0;
  int handling_opt_count = 0;
  const char *config_filename = NULL;
  const char *pid_filename = NULL;
  const char *log_filename = NULL;
  svn_node_kind_t kind;
  apr_size_t min_thread_count = THREADPOOL_MIN_SIZE;
  apr_size_t max_thread_count = THREADPOOL_MAX_SIZE;
#ifdef SVN_HAVE_SASL
  SVN_ERR(cyrus_init(pool));
#endif

  /* Check library versions */
  SVN_ERR(check_lib_versions());

  /* Initialize the FS library. */
  SVN_ERR(svn_fs_initialize(pool));

  SVN_ERR(svn_cmdline__getopt_init(&os, argc, argv, pool));

  params.root = "/";
  params.tunnel = FALSE;
  params.tunnel_user = NULL;
  params.read_only = FALSE;
  params.base = NULL;
  params.cfg = NULL;
  params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_DEFAULT;
  params.logger = NULL;
  params.config_pool = NULL;
  params.authz_pool = NULL;
  params.fs_config = NULL;
  params.vhost = FALSE;
  params.username_case = CASE_ASIS;
  params.memory_cache_size = (apr_uint64_t)-1;
  params.zero_copy_limit = 0;
  params.error_check_interval = 4096;

  while (1)
    {
      status = apr_getopt_long(os, svnserve__options, &opt, &arg);
      if (APR_STATUS_IS_EOF(status))
        break;
      if (status != APR_SUCCESS)
        {
          usage(argv[0], pool);
          *exit_code = EXIT_FAILURE;
          return SVN_NO_ERROR;
        }
      switch (opt)
        {
        case '6':
#if APR_HAVE_IPV6
          prefer_v6 = TRUE;
#endif
          /* ### Maybe error here if we don't have IPV6 support? */
          break;

        case 'h':
          help(pool);
          return SVN_NO_ERROR;

        case 'q':
          quiet = TRUE;
          break;

        case SVNSERVE_OPT_VERSION:
          is_version = TRUE;
          break;

        case 'd':
          if (run_mode != run_mode_daemon)
            {
              run_mode = run_mode_daemon;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_FOREGROUND:
          foreground = TRUE;
          break;

        case SVNSERVE_OPT_SINGLE_CONN:
          handling_mode = connection_mode_single;
          handling_opt_count++;
          break;

        case 'i':
          if (run_mode != run_mode_inetd)
            {
              run_mode = run_mode_inetd;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_LISTEN_PORT:
          {
            apr_uint64_t val;

            err = svn_cstring_strtoui64(&val, arg, 0, APR_UINT16_MAX, 10);
            if (err)
              return svn_error_createf(SVN_ERR_CL_ARG_PARSING_ERROR, err,
                                       _("Invalid port '%s'"), arg);
            port = (apr_uint16_t)val;
          }
          break;

        case SVNSERVE_OPT_LISTEN_HOST:
          host = arg;
          break;

        case 't':
          if (run_mode != run_mode_tunnel)
            {
              run_mode = run_mode_tunnel;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_TUNNEL_USER:
          params.tunnel_user = arg;
          break;

        case 'X':
          if (run_mode != run_mode_listen_once)
            {
              run_mode = run_mode_listen_once;
              mode_opt_count++;
            }
          break;

        case 'r':
          SVN_ERR(svn_utf_cstring_to_utf8(&params.root, arg, pool));

          SVN_ERR(svn_io_check_resolved_path(params.root, &kind, pool));
          if (kind != svn_node_dir)
            {
              return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
                       _("Root path '%s' does not exist "
                         "or is not a directory"), params.root);
            }

          params.root = svn_dirent_internal_style(params.root, pool);
          SVN_ERR(svn_dirent_get_absolute(&params.root, params.root, pool));
          break;

        case 'R':
          params.read_only = TRUE;
          break;

        case 'T':
          handling_mode = connection_mode_thread;
          handling_opt_count++;
          break;

        case 'c':
          params.compression_level = atoi(arg);
          if (params.compression_level < SVN_DELTA_COMPRESSION_LEVEL_NONE)
            params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_NONE;
          if (params.compression_level > SVN_DELTA_COMPRESSION_LEVEL_MAX)
            params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_MAX;
          break;

        case 'M':
          params.memory_cache_size = 0x100000 * apr_strtoi64(arg, NULL, 0);
          break;

        case SVNSERVE_OPT_CACHE_TXDELTAS:
          cache_txdeltas = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CACHE_FULLTEXTS:
          cache_fulltexts = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CACHE_REVPROPS:
          cache_revprops = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_BLOCK_READ:
          use_block_read = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CLIENT_SPEED:
          {
            apr_size_t bandwidth = (apr_size_t)apr_strtoi64(arg, NULL, 0);

            /* for slower clients, don't try anything fancy */
            if (bandwidth >= 1000)
              {
                /* block other clients for at most 1 ms (at full bandwidth).
                   Note that the send buffer is 16kB anyways. */
                params.zero_copy_limit = bandwidth * 120;

                /* check for aborted connections at the same rate */
                params.error_check_interval = bandwidth * 120;
              }
          }
          break;

        case SVNSERVE_OPT_MIN_THREADS:
          min_thread_count = (apr_size_t)apr_strtoi64(arg, NULL, 0);
          break;

        case SVNSERVE_OPT_MAX_THREADS:
          max_thread_count = (apr_size_t)apr_strtoi64(arg, NULL, 0);
          break;

#ifdef WIN32
        case SVNSERVE_OPT_SERVICE:
          if (run_mode != run_mode_service)
            {
              run_mode = run_mode_service;
              mode_opt_count++;
            }
          break;
#endif

        case SVNSERVE_OPT_CONFIG_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&config_filename, arg, pool));
          config_filename = svn_dirent_internal_style(config_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&config_filename, config_filename,
                                          pool));
          break;

        case SVNSERVE_OPT_PID_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&pid_filename, arg, pool));
          pid_filename = svn_dirent_internal_style(pid_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&pid_filename, pid_filename, pool));
          break;

         case SVNSERVE_OPT_VIRTUAL_HOST:
           params.vhost = TRUE;
           break;

         case SVNSERVE_OPT_LOG_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&log_filename, arg, pool));
          log_filename = svn_dirent_internal_style(log_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&log_filename, log_filename, pool));
          break;

        }
    }

  if (is_version)
    {
      SVN_ERR(version(quiet, pool));
      return SVN_NO_ERROR;
    }

  if (os->ind != argc)
    {
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  if (mode_opt_count != 1)
    {
      svn_error_clear(svn_cmdline_fputs(
#ifdef WIN32
                      _("You must specify exactly one of -d, -i, -t, "
                        "--service or -X.\n"),
#else
                      _("You must specify exactly one of -d, -i, -t or -X.\n"),
#endif
                       stderr, pool));
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  if (handling_opt_count > 1)
    {
      svn_error_clear(svn_cmdline_fputs(
                      _("You may only specify one of -T or --single-thread\n"),
                      stderr, pool));
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  /* construct object pools */
  is_multi_threaded = handling_mode == connection_mode_thread;
  params.fs_config = apr_hash_make(pool);
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_DELTAS,
                cache_txdeltas ? "1" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_FULLTEXTS,
                cache_fulltexts ? "1" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_REVPROPS,
                cache_revprops ? "2" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_BLOCK_READ,
                use_block_read ? "1" :"0");

  SVN_ERR(svn_repos__config_pool_create(&params.config_pool,
                                        is_multi_threaded,
                                        pool));
  SVN_ERR(svn_repos__authz_pool_create(&params.authz_pool,
                                       params.config_pool,
                                       is_multi_threaded,
                                       pool));

  /* If a configuration file is specified, load it and any referenced
   * password and authorization files. */
  if (config_filename)
    {
      params.base = svn_dirent_dirname(config_filename, pool);

      SVN_ERR(svn_repos__config_pool_get(&params.cfg, NULL,
                                         params.config_pool,
                                         config_filename,
                                         TRUE, /* must_exist */
                                         FALSE, /* names_case_sensitive */
                                         NULL,
                                         pool));
    }

  if (log_filename)
    SVN_ERR(logger__create(&params.logger, log_filename, pool));
  else if (run_mode == run_mode_listen_once)
    SVN_ERR(logger__create_for_stderr(&params.logger, pool));

  if (params.tunnel_user && run_mode != run_mode_tunnel)
    {
      return svn_error_create(SVN_ERR_CL_ARG_PARSING_ERROR, NULL,
               _("Option --tunnel-user is only valid in tunnel mode"));
    }

  if (run_mode == run_mode_inetd || run_mode == run_mode_tunnel)
    {
      apr_pool_t *connection_pool;
      svn_ra_svn_conn_t *conn;
      svn_stream_t *stdin_stream;
      svn_stream_t *stdout_stream;

      params.tunnel = (run_mode == run_mode_tunnel);
      apr_pool_cleanup_register(pool, pool, apr_pool_cleanup_null,
                                redirect_stdout);

      SVN_ERR(svn_stream_for_stdin(&stdin_stream, pool));
      SVN_ERR(svn_stream_for_stdout(&stdout_stream, pool));

      /* Use a subpool for the connection to ensure that if SASL is used
       * the pool cleanup handlers that call sasl_dispose() (connection_pool)
       * and sasl_done() (pool) are run in the right order. See issue #3664. */
      connection_pool = svn_pool_create(pool);
      conn = svn_ra_svn_create_conn4(NULL, stdin_stream, stdout_stream,
                                     params.compression_level,
                                     params.zero_copy_limit,
                                     params.error_check_interval,
                                     connection_pool);
      err = serve(conn, &params, connection_pool);
      svn_pool_destroy(connection_pool);

      return err;
    }

#ifdef WIN32
  /* If svnserve needs to run as a Win32 service, then we need to
     coordinate with the Service Control Manager (SCM) before
     continuing.  This function call registers the svnserve.exe
     process with the SCM, waits for the "start" command from the SCM
     (which will come very quickly), and confirms that those steps
     succeeded.

     After this call succeeds, the service is free to run.  At some
     point in the future, the SCM will send a message to the service,
     requesting that it stop.  This is translated into a call to
     winservice_notify_stop().  The service is then responsible for
     cleanly terminating.

     We need to do this before actually starting the service logic
     (opening files, sockets, etc.) because the SCM wants you to
     connect *first*, then do your service-specific logic.  If the
     service process takes too long to connect to the SCM, then the
     SCM will decide that the service is busted, and will give up on
     it.
     */
  if (run_mode == run_mode_service)
    {
      err = winservice_start();
      if (err)
        {
          svn_handle_error2(err, stderr, FALSE, "svnserve: ");

          /* This is the most common error.  It means the user started
             svnserve from a shell, and specified the --service
             argument.  svnserve cannot be started, as a service, in
             this way.  The --service argument is valid only valid if
             svnserve is started by the SCM. */
          if (err->apr_err ==
              APR_FROM_OS_ERROR(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT))
            {
              svn_error_clear(svn_cmdline_fprintf(stderr, pool,
                  _("svnserve: The --service flag is only valid if the"
                    " process is started by the Service Control Manager.\n")));
            }

          svn_error_clear(err);
          *exit_code = EXIT_FAILURE;
          return SVN_NO_ERROR;
        }

      /* The service is now in the "starting" state.  Before the SCM will
         consider the service "started", this thread must call the
         winservice_running() function. */
    }
#endif /* WIN32 */

  /* Make sure we have IPV6 support first before giving apr_sockaddr_info_get
     APR_UNSPEC, because it may give us back an IPV6 address even if we can't
     create IPV6 sockets. */

#if APR_HAVE_IPV6
#ifdef MAX_SECS_TO_LINGER
  /* ### old APR interface */
  status = apr_socket_create(&sock, APR_INET6, SOCK_STREAM, pool);
#else
  status = apr_socket_create(&sock, APR_INET6, SOCK_STREAM, APR_PROTO_TCP,
                             pool);
#endif
  if (status == 0)
    {
      apr_socket_close(sock);
      family = APR_UNSPEC;

      if (prefer_v6)
        {
          if (host == NULL)
            host = "::";
          sockaddr_info_flags = APR_IPV6_ADDR_OK;
        }
      else
        {
          if (host == NULL)
            host = "0.0.0.0";
          sockaddr_info_flags = APR_IPV4_ADDR_OK;
        }
    }
#endif

  status = apr_sockaddr_info_get(&sa, host, family, port,
                                 sockaddr_info_flags, pool);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't get address info"));
    }


#ifdef MAX_SECS_TO_LINGER
  /* ### old APR interface */
  status = apr_socket_create(&sock, sa->family, SOCK_STREAM, pool);
#else
  status = apr_socket_create(&sock, sa->family, SOCK_STREAM, APR_PROTO_TCP,
                             pool);
#endif
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't create server socket"));
    }

  /* Prevents "socket in use" errors when server is killed and quickly
   * restarted. */
  status = apr_socket_opt_set(sock, APR_SO_REUSEADDR, 1);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't set options on server socket"));
    }

  status = apr_socket_bind(sock, sa);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't bind server socket"));
    }

  status = apr_socket_listen(sock, ACCEPT_BACKLOG);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't listen on server socket"));
    }

#if APR_HAS_FORK
  if (run_mode != run_mode_listen_once && !foreground)
    /* ### ignoring errors... */
    apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);

  apr_signal(SIGCHLD, sigchld_handler);
#endif

#ifdef SIGPIPE
  /* Disable SIGPIPE generation for the platforms that have it. */
  apr_signal(SIGPIPE, SIG_IGN);
#endif

#ifdef SIGXFSZ
  /* Disable SIGXFSZ generation for the platforms that have it, otherwise
   * working with large files when compiled against an APR that doesn't have
   * large file support will crash the program, which is uncool. */
  apr_signal(SIGXFSZ, SIG_IGN);
#endif

  if (pid_filename)
    SVN_ERR(write_pid_file(pid_filename, pool));

#ifdef WIN32
  status = apr_os_sock_get(&winservice_svnserve_accept_socket, sock);
  if (status)
    winservice_svnserve_accept_socket = INVALID_SOCKET;

  /* At this point, the service is "running".  Notify the SCM. */
  if (run_mode == run_mode_service)
    winservice_running();
#endif

  /* Configure FS caches for maximum efficiency with svnserve.
   * For pre-forked (i.e. multi-processed) mode of operation,
   * keep the per-process caches smaller than the default.
   * Also, apply the respective command line parameters, if given. */
  {
    svn_cache_config_t settings = *svn_cache_config_get();

    if (params.memory_cache_size != -1)
      settings.cache_size = params.memory_cache_size;

    settings.single_threaded = TRUE;
    if (handling_mode == connection_mode_thread)
      {
#if APR_HAS_THREADS
        settings.single_threaded = FALSE;
#else
        /* No requests will be processed at all
         * (see "switch (handling_mode)" code further down).
         * But if they were, some other synchronization code
         * would need to take care of securing integrity of
         * APR-based structures. That would include our caches.
         */
#endif
      }

    svn_cache_config_set(&settings);
  }

#if APR_HAS_THREADS
  SVN_ERR(svn_root_pools__create(&connection_pools));

  if (handling_mode == connection_mode_thread)
    {
      /* create the thread pool with a valid range of threads */
      if (max_thread_count < 1)
        max_thread_count = 1;
      if (min_thread_count > max_thread_count)
        min_thread_count = max_thread_count;

      status = apr_thread_pool_create(&threads,
                                      min_thread_count,
                                      max_thread_count,
                                      pool);
      if (status)
        {
          return svn_error_wrap_apr(status, _("Can't create thread pool"));
        }

      /* let idle threads linger for a while in case more requests are
         coming in */
      apr_thread_pool_idle_wait_set(threads, THREADPOOL_THREAD_IDLE_LIMIT);

      /* don't queue requests unless we reached the worker thread limit */
      apr_thread_pool_threshold_set(threads, 0);
    }
  else
    {
      threads = NULL;
    }
#endif

  while (1)
    {
      connection_t *connection = NULL;
      SVN_ERR(accept_connection(&connection, sock, &params, handling_mode,
                                pool));
      if (run_mode == run_mode_listen_once)
        {
          err = serve_socket(connection, connection->pool);
          close_connection(connection);
          return err;
        }

      switch (handling_mode)
        {
        case connection_mode_fork:
#if APR_HAS_FORK
          status = apr_proc_fork(&proc, connection->pool);
          if (status == APR_INCHILD)
            {
              /* the child would't listen to the main server's socket */
              apr_socket_close(sock);

              /* serve_socket() logs any error it returns, so ignore it. */
              svn_error_clear(serve_socket(connection, connection->pool));
              close_connection(connection);
              return SVN_NO_ERROR;
            }
          else if (status != APR_INPARENT)
            {
              err = svn_error_wrap_apr(status, "apr_proc_fork");
              logger__log_error(params.logger, err, NULL, NULL);
              svn_error_clear(err);
            }
#endif
          break;

        case connection_mode_thread:
          /* Create a detached thread for each connection.  That's not a
             particularly sophisticated strategy for a threaded server, it's
             little different from forking one process per connection. */
#if APR_HAS_THREADS
          attach_connection(connection);

          status = apr_thread_pool_push(threads, serve_thread, connection,
                                        0, NULL);
          if (status)
            {
              return svn_error_wrap_apr(status, _("Can't push task"));
            }
#endif
          break;

        case connection_mode_single:
          /* Serve one connection at a time. */
          /* serve_socket() logs any error it returns, so ignore it. */
          svn_error_clear(serve_socket(connection, connection->pool));
        }

      close_connection(connection);
    }

  /* NOTREACHED */
}
コード例 #11
0
ファイル: notify.c プロジェクト: JoshCooley/irrd
/* This is the old guy.  We are migrating away from this version of performing
 * the transactions.   However this works and is what we will use for now.
 *
 * Our migration path will be like this:
 *
 * (old guy) -> (irr_submit, irrd transaction compliant) -> (rpsdist)
 *
 * To get to the next step, this routine should be phased out and 
 * perform_transactions_new () should be used.
 * Then to get to the last step perform_transactions_new () should be
 * phased out in favor of perform_rpsdist_trans ().
 */
void perform_transactions (trace_t *tr, FILE *fin, ret_info_t *start,
			   int null_submission, 
			   char *IRRd_HOST, int IRRd_PORT, char *pgpdir) {
  char buf[MAXLINE], *ret_code;
  int fd, num_trans = 0;
  int open_conn = 0, abort_trans = 0;
  long offset;
  trans_info_t ti;
  irrd_result_t *p;
/* pgp_data_t pdat; */
  
  /* fprintf (dfile, "\n----\nEnter perform_transactions()\n");*/

  /* rewind */
  fseek (fin, 0L, SEEK_SET);

  while (fgets (buf, MAXLINE, fin) != NULL) {
    if (strncmp (HDR_START, buf, strlen (HDR_START) - 1))
      continue;
    /* JW commented out to dup rawhoisd 
       if (!abort_trans)
       */
    offset = ftell (fin);
    /* fprintf (dfile, "HDR_START offset (%ld)\n", offset);*/
    /* illegal hdr field found or EOF or no object after hdr */
    if (parse_header (tr, fin, &offset, &ti)) {
      abort_trans = 1;
      /* fprintf (dfile, "calling update_trans_outcome_list (internal error)...\n"); */
      update_trans_outcome_list (tr, start, &ti, offset, INTERNAL_ERROR_RESULT,
				 "\" Internal error: malformed header!\"\n");
      free_ti_mem (&ti);
      continue;
    }
    else if (update_has_errors (&ti))
      abort_trans = 1;
    else if (null_submission == 0) {
      update_trans_outcome_list (tr, start, &ti, offset, NULL_SUBMISSION, NULL);
      continue;
    }

    update_trans_outcome_list (tr, start, &ti, offset, 0, NULL);
    free_ti_mem (&ti);
  }

  /* JW commented out to dup rawhoisd 
   * want to bring back for transaction semantic support
  if (abort_trans)
    reinit_return_list (dfile, start, SKIP_RESULT);
  else {
  */
    for (p = start->first; p != NULL; p = p->next) {
      /* JW want to bring back in later, dup rawhoisd
      if (p->svr_res & NOOP_RESULT)
	continue;
	*/
      /* JW take next 3 sections out to reverse rawhoisd behavior */
      if (p->svr_res & INTERNAL_ERROR_RESULT ||
	  p->svr_res & NULL_SUBMISSION) {
	trace (ERROR, tr, 
	       "Internal error or NULL submission.  Object not added to IRRd.\n");
	continue;
      }

      if (p->svr_res & USER_ERROR) {
	trace (NORM, tr, 
	       "Syntax or authorization error.  Object not added to IRRd.\n");
	continue;
      }

      if (p->svr_res & NOOP_RESULT) {
	trace (NORM, tr, "NOOP object.  Object not added to IRRd.\n");
	continue;
      }

      /* what the eff is this segment doing? */
      if (EOF == fseek (fin, p->offset, SEEK_SET))
	  fprintf (stderr, "ERROR: fseek (%ld)\n", p->offset);
      else {
	fgets (buf, MAXLINE, fin);
	/*fprintf (dfile, "irrd_trans () line: %s", buf);*/
	fseek (fin, p->offset, SEEK_SET);
      }
      /* fprintf (dfile, "perform_trans () calling irrd_transaction ()...\n");*/
      ret_code = irrd_transaction (tr, (char *) WARN_TAG, &fd, fin, p->op, 
				   p->source, ++num_trans, &open_conn, 
				   IRRd_HOST, IRRd_PORT);

      /* check for no IRRd errors and we have a key-cert object */
      if (!put_transaction_code (tr, p, ret_code) &&
	  is_keycert_obj (p)                      &&
	  p->op != NULL) {
	update_pgp_ring_new (tr, p, pgpdir);
	/* 
	if (strcmp (p->op, DEL_OP)) {
	  pgp_add (tr, pgpdir, p->keycertfn, &pdat);
	  pgp_free (&pdat);
	}
	else
	  pgp_del (tr, pgpdir, p->obj_key + 7);
	*/
      }
    }

    if (open_conn) {
      end_irrd_session (tr, fd); /* send '!q' */
      fflush (fin);   /* JW only needed when irrd commands are sent to terminal */
      close_connection (fd);
    }

    /* Remove any key certificate files from our temp directory area */
    for (p = start->first; p != NULL; p = p->next)
      if (p->keycertfn != NULL)
	remove (p->keycertfn);

  /* JW want to bring back in later, dup rawhoisd
  }
  */
    /* fprintf (dfile, "Exit perform_transactions()\n----\n");*/
}
コード例 #12
0
ファイル: mpmt_server.c プロジェクト: p1rate5s/c-icap
int thread_main(server_decl_t * srv)
{
     ci_connection_t con;
     char clientname[CI_MAXHOSTNAMELEN + 1];
     int ret, request_status = CI_NO_STATUS;
     int keepalive_reqs;
//***********************
     thread_signals(0);
//*************************
     srv->srv_id = getpid();    //Setting my pid ...

     for (;;) {
          /*
             If we must shutdown IMEDIATELLY it is time to leave the server
             else if we are going to shutdown GRACEFULLY we are going to die 
             only if there are not any accepted connections
           */
          if (child_data->to_be_killed == IMMEDIATELY) {
               srv->running = 0;
               return 1;
          }

          if ((ret = get_from_queue(con_queue, &con)) == 0) {
               if (child_data->to_be_killed) {
                    srv->running = 0;
                    return 1;
               }
               ret = wait_for_queue(con_queue);
               continue;
          }

          if (ret < 0) {        //An error has occured
               ci_debug_printf(1,
                               "Fatal Error!!! Error getting a connection from connections queue!!!\n");
               break;
          }

          ci_thread_mutex_lock(&counters_mtx);  /*Update counters as soon as possible */
          (child_data->freeservers)--;
          (child_data->usedservers)++;
          ci_thread_mutex_unlock(&counters_mtx);

          ci_netio_init(con.fd);
          ret = 1;
          if (srv->current_req == NULL)
               srv->current_req = newrequest(&con);
          else
               ret = recycle_request(srv->current_req, &con);

          if (srv->current_req == NULL || ret == 0) {
               ci_sockaddr_t_to_host(&(con.claddr), clientname,
                                     CI_MAXHOSTNAMELEN);
               ci_debug_printf(1, "Request from %s denied...\n", clientname);
               hard_close_connection((&con));
               goto end_of_main_loop_thread;    /*The request rejected. Log an error and continue ... */
          }

          keepalive_reqs = 0;
          do {
               if (MAX_KEEPALIVE_REQUESTS > 0
                   && keepalive_reqs >= MAX_KEEPALIVE_REQUESTS)
                    srv->current_req->keepalive = 0;    /*do not keep alive connection */
               if (child_data->to_be_killed)    /*We are going to die do not keep-alive */
                    srv->current_req->keepalive = 0;

               if ((request_status = process_request(srv->current_req)) == CI_NO_STATUS) {
                    ci_debug_printf(5,
                                    "Process request timeout or interrupted....\n");
                    ci_request_reset(srv->current_req);
                    break;
               }
               srv->served_requests++;
               srv->served_requests_no_reallocation++;
               keepalive_reqs++;

               /*Increase served requests. I dont like this. The delay is small but I don't like... */
               ci_thread_mutex_lock(&counters_mtx);
               (child_data->requests)++;
               ci_thread_mutex_unlock(&counters_mtx);

               log_access(srv->current_req, request_status);
//             break; //No keep-alive ......

               if (child_data->to_be_killed  == IMMEDIATELY)
                    break;      //Just exiting the keep-alive loop

               /*if we are going to term gracefully we will try to keep our promice for
                 keepalived request....
                */
               if (child_data->to_be_killed  == GRACEFULLY && 
                   srv->current_req->keepalive == 0)
                    break;

               ci_debug_printf(8, "Keep-alive:%d\n",
                               srv->current_req->keepalive);
               if (srv->current_req->keepalive && keepalive_request(srv->current_req)) {
                   ci_debug_printf(8,
                                   "Server %d going to serve new request from client (keep-alive) \n",
                                   srv->srv_id);
               }
               else
                    break;
          } while (1);

          if (srv->current_req) {
               if (request_status != CI_OK || child_data->to_be_killed) {
                    hard_close_connection(srv->current_req->connection);
               }
               else {
                    close_connection(srv->current_req->connection);
               }
          }
          if (srv->served_requests_no_reallocation >
              MAX_REQUESTS_BEFORE_REALLOCATE_MEM) {
               ci_debug_printf(5,
                               "Max requests reached, reallocate memory and buffers .....\n");
               ci_request_destroy(srv->current_req);
               srv->current_req = NULL;
               srv->served_requests_no_reallocation = 0;
          }


        end_of_main_loop_thread:
          ci_thread_mutex_lock(&counters_mtx);
          (child_data->freeservers)++;
          (child_data->usedservers)--;
          ci_thread_mutex_unlock(&counters_mtx);
          ci_thread_cond_signal(&free_server_cond);

     }
     srv->running = 0;
     return 0;
}
コード例 #13
0
ファイル: publish.c プロジェクト: capensis/canopsis-externals
int main(int argc, const char **argv)
{
	amqp_connection_state_t conn;
	char *exchange = NULL;
	char *routing_key = NULL;
	char *content_type = NULL;
	char *content_encoding = NULL;
	char *body = NULL;
	amqp_basic_properties_t props;
	amqp_bytes_t body_bytes;
	int delivery = 1; /* non-persistent by default */

	struct poptOption options[] = {
		INCLUDE_OPTIONS(connect_options),
		{"exchange", 'e', POPT_ARG_STRING, &exchange, 0,
		 "the exchange to publish to", "exchange"},
		{"routing-key", 'r', POPT_ARG_STRING, &routing_key, 0,
		 "the routing key to publish with", "routing key"},
		{"persistent", 'p', POPT_ARG_VAL, &delivery, 2,
		 "use the persistent delivery mode", NULL},
		{"content-type", 'C', POPT_ARG_STRING, &content_type, 0,
		 "the content-type for the message", "content type"},
		{"content-encoding", 'E', POPT_ARG_STRING,
		 &content_encoding, 0,
		 "the content-encoding for the message", "content encoding"},
		{"body", 'b', POPT_ARG_STRING, &body, 0,
                 "specify the message body", "body"},
		POPT_AUTOHELP
		{ NULL, 0, 0, NULL, 0 }
	};

	process_all_options(argc, argv, options);

	if (!exchange && !routing_key) {
		fprintf(stderr,
			"neither exchange nor routing key specified\n");
		return 1;
	}

	memset(&props, 0, sizeof props);
	props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;
	props.delivery_mode = 2; /* persistent delivery mode */

	if (content_type) {
		props._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
		props.content_type = amqp_cstring_bytes(content_type);
	}

	if (content_encoding) {
		props._flags |= AMQP_BASIC_CONTENT_ENCODING_FLAG;
		props.content_encoding = amqp_cstring_bytes(content_encoding);
	}

	conn = make_connection();

	if (body)
		body_bytes = amqp_cstring_bytes(body);
	else
		body_bytes = read_all(0);

	do_publish(conn, exchange, routing_key, &props, body_bytes);

	if (!body)
		free(body_bytes.bytes);

	close_connection(conn);
	return 0;
}
コード例 #14
0
ファイル: test_ddl.c プロジェクト: HengWang/mysql-audit
int main(int argc, char* argv[])
{
  char* host="localhost";
  char* user="******";
  char* password="";
  char* database="audit";
  char* sock="/tmp/mysql.sock";
  uint port=3306;

  MYSQL* mysql;  
  my_bool flag = TRUE;
  char* table="test";
  ulonglong origin_audit_ops = opt_audit_ops;
  uint origin_audit_class = opt_audit_class;
  static int success = 0;
  static int failed = 0;

  opt_audit_ops = 0;

  mysql_init(mysql);  
  if(!open_connection( mysql, host,user,password, database, port, sock,0))
  {
    printf("Error: Connection failed when testing the dml operation for audit\n");
    return FALSE;
  }

  opt_audit_class = 2;
  opt_audit_ops |=AUDIT_DDL;

  flag = check_create(2,mysql,table);
  printf("Audit the create operation into file\n");
  if(flag)
  {
    success++;
    printf("Create: SUCCESS!\n");
  }
  else{
    failed++;
    printf("Create: FAILED!\n");
  }

  flag = check_alter(2,mysql,table);
  printf("Audit the alter operation into file\n");
  if(flag)
  {
    success++;
    printf("Alter: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Alter: FAILED!\n");
  }  

  flag = check_drop(2,mysql,"test");
  printf("Audit the drop operation file\n");
  if(flag)
  {
    success++;
    printf("Drop: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Drop: FAILED!\n");
  } 

  opt_audit_class = 4;
  flag = check_create(4,mysql,"test");
  printf("Audit the create operation into table\n");
  if(flag)
  {
    success++;
    printf("Create: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Create: FAILED!\n");
  }

  flag = check_alter(4,mysql,"test");
  printf("Audit the alter operation into table\n");
  if(flag)
  {
    success++;
    printf("Alter: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Alter: FAILED!\n");
  } 

  flag = check_drop(4,mysql,"test");
  printf("Audit the drop operation table\n");
  if(flag)
  {
    success++;
    printf("Drop: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Drop: FAILED!\n");
  }  

  opt_audit_class = 2;
  opt_audit_ops &=~AUDIT_DDL;

  flag = check_create(2,mysql,table);
  printf("Don't audit the create operation into file\n");
  if(!flag)
  {
    success++;
    printf("Create: SUCCESS!\n");
  }
  else{
    failed++;
    printf("Create: FAILED!\n");
  }

  flag = check_alter(2,mysql,table);
  printf("Don't audit the alter operation into file\n");
  if(!flag)
  {
    success++;
    printf("Alter: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Alter: FAILED!\n");
  }  

  flag = check_drop(2,mysql,"test");
  printf("Don't audit the drop operation file\n");
  if(!flag)
  {
    success++;
    printf("Drop: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Drop: FAILED!\n");
  } 

  opt_audit_class = 4;
  flag = check_create(4,mysql,"test");
  printf("Don't audit the create operation into table\n");
  if(!flag)
  {
    success++;
    printf("Create: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Create: FAILED!\n");
  }

  flag = check_alter(4,mysql,"test");
  printf("Don't audit the alter operation into table\n");
  if(!flag)
  {
    success++;
    printf("Alter: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Alter: FAILED!\n");
  } 

  flag = check_drop(4,mysql,"test");
  printf("Don't audit the drop operation table\n");
  if(!flag)
  {
    success++;
    printf("Drop: SUCCESS!\n");
  } 
  else{
    failed++;
    printf("Drop: FAILED!\n");
  }  

  opt_audit_ops = origin_audit_ops;
  opt_audit_class = origin_audit_class;

  close_connection(mysql);

  printf("=============================\n");
  printf("total: %d, success: %d, failed: %d\n",success+failed,success,failed);
  return 0;   
}
コード例 #15
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
/* set diseqcType*/
void CZapitClient::setDiseqcType(const diseqc_t diseqc)
{
	send(CZapitMessages::CMD_SCANSETDISEQCTYPE, (const char *) & diseqc, sizeof(diseqc));
	close_connection();
}
コード例 #16
0
ファイル: jsonrpc-c.c プロジェクト: Marcus366/jsonrpc-c
static void connection_cb(struct ev_loop *loop, ev_io *w, int revents) {
	struct jrpc_connection *conn;
	struct jrpc_server *server = (struct jrpc_server *) w->data;
	size_t bytes_read = 0;
	//get our 'subclassed' event watcher
	conn = (struct jrpc_connection *) w;
	int fd = conn->fd;
	if (conn->pos == (conn->buffer_size - 1)) {
		char * new_buffer = realloc(conn->buffer, conn->buffer_size *= 2);
		if (new_buffer == NULL) {
			perror("Memory error");
			return close_connection(loop, w);
		}
		conn->buffer = new_buffer;
		memset(conn->buffer + conn->pos, 0, conn->buffer_size - conn->pos);
	}
	// can not fill the entire buffer, string must be NULL terminated
	int max_read_size = conn->buffer_size - conn->pos - 1;
	if ((bytes_read = read(fd, conn->buffer + conn->pos, max_read_size))
			== -1) {
		perror("read");
		return close_connection(loop, w);
	}
	if (!bytes_read) {
		// client closed the sending half of the connection
		if (server->debug_level)
			printf("Client closed connection.\n");
		return close_connection(loop, w);
	} else {
		cJSON *root;
		char *end_ptr = NULL;
		conn->pos += bytes_read;

		if ((root = cJSON_Parse_Stream(conn->buffer, &end_ptr)) != NULL) {
			if (server->debug_level > 1) {
				char * str_result = cJSON_Print(root);
				printf("Valid JSON Received:\n%s\n", str_result);
				free(str_result);
			}

			if (root->type == cJSON_Object) {
				eval_request(server, conn, root);
			}
			//shift processed request, discarding it
			memmove(conn->buffer, end_ptr, strlen(end_ptr) + 2);

			conn->pos = strlen(end_ptr);
			memset(conn->buffer + conn->pos, 0,
					conn->buffer_size - conn->pos - 1);

			cJSON_Delete(root);
		} else {
			// did we parse the all buffer? If so, just wait for more.
			// else there was an error before the buffer's end
			if (end_ptr != (conn->buffer + conn->pos)) {
				if (server->debug_level) {
					printf("INVALID JSON Received:\n---\n%s\n---\n",
							conn->buffer);
				}
				send_error(conn, JRPC_PARSE_ERROR,
						strdup(
								"Parse error. Invalid JSON was received by the server."),
						NULL);
				return close_connection(loop, w);
			}
		}
	}

}
コード例 #17
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
/* set diseqcRepeat*/
void CZapitClient::setDiseqcRepeat(const uint32_t  repeat)
{
	send(CZapitMessages::CMD_SCANSETDISEQCREPEAT, (const char *) & repeat, sizeof(repeat));
	close_connection();
}
コード例 #18
0
int main(int argc, char** argv) {

    int port = atoi(argv[1]);

    Server* server = create_server(port);

    listen_port(server);

    Connection* con = accept_connection(server);

    char client_addr[50];
    get_connection_address(con, client_addr);

    printf("CLIENT %s CONNECTED\n", client_addr);

    receive_greet(con);
    send_greet_ack(con);


    //Receive folder anem
    char buffer[MAX_MSG];
    receive_msg(con, buffer);
    send_ack(con);

    char filename[100];
    strcpy(filename, client_addr);
    strcat(filename, buffer);

    int i;
    for(i = 0; filename[i] != '\0'; i++){
        filename[i] = filename[i] == '/'? '.': filename[i];
    }

    char* filebuffer = calloc(sizeof(char), MAX_MSG);
    int filebuffer_size = MAX_MSG;
    filebuffer[0] = '\0';

    int usedbuffer = 0;

    //receive filenames
    while(receive_msg(con, buffer)){
        usedbuffer += strlen(buffer)+1;
        if(usedbuffer > filebuffer_size){
            filebuffer_size *= 2;
            filebuffer = (char*) realloc(filebuffer, sizeof(char)*filebuffer_size*2);
        }
        printf("%s\n", buffer);
        sprintf(filebuffer, "%s%s\n", filebuffer, buffer);
        send_ack(con);
    }

    shutdown_server(server);
    close_connection(con);

    FILE* f = fopen(filename, "w");
    fprintf(f, "%s", filebuffer);
    fclose(f);

    free(filebuffer);


    return 0;
}
コード例 #19
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
/* set Scan-TYpe for channelsearch */
void CZapitClient::setScanType(const scanType mode)
{
	send(CZapitMessages::CMD_SCANSETTYPE, (const char *) & mode, sizeof(mode));
  	close_connection();
}
コード例 #20
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
void CZapitClient::shutdown()
{
	send(CZapitMessages::CMD_SHUTDOWN);
	close_connection();
}
コード例 #21
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
void CZapitClient::startPlayBack()
{
	send(CZapitMessages::CMD_SB_START_PLAYBACK);
	close_connection();
}
コード例 #22
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
bool CZapitClient::stopScan()
{
        bool reply = send(CZapitMessages::CMD_SCANSTOP);
        close_connection();
        return reply;
}
コード例 #23
0
ファイル: http_load.c プロジェクト: boojoo-exp/cacheperf
static void
handle_read( int cnum, struct timeval* nowP )
    {
    char buf[30000];	/* must be larger than throttle / 2 */
    int bytes_to_read, bytes_read, bytes_handled;
    float elapsed;
    ClientData client_data;
    register long checksum;

    tmr_reset( nowP, connections[cnum].idle_timer );

    if ( do_throttle )
	bytes_to_read = throttle / 2.0;
    else
	bytes_to_read = sizeof(buf);
    if ( ! connections[cnum].did_response )
	{
	connections[cnum].did_response = 1;
	connections[cnum].response_at = *nowP;
	}
#ifdef USE_SSL
    if ( urls[connections[cnum].url_num].protocol == PROTO_HTTPS )
	bytes_read = SSL_read( connections[cnum].ssl, buf, bytes_to_read );
    else
	bytes_read = read( connections[cnum].conn_fd, buf, bytes_to_read );
#else
    bytes_read = read( connections[cnum].conn_fd, buf, bytes_to_read );
#endif
    if ( bytes_read <= 0 )
	{
	close_connection( cnum );
	return;
	}

    for ( bytes_handled = 0; bytes_handled < bytes_read; )
	{
	switch ( connections[cnum].conn_state )
	    {
	    case CNST_HEADERS:
	    /* State machine to read until we reach the file part.  Looks for
	    ** Content-Length header too.
	    */
	    for ( ; bytes_handled < bytes_read && connections[cnum].conn_state == CNST_HEADERS; ++bytes_handled )
		{
		switch ( connections[cnum].header_state )
		    {

		    case HDST_LINE1_PROTOCOL:
		    switch ( buf[bytes_handled] )
			{
			case ' ': case '\t':
			connections[cnum].header_state = HDST_LINE1_WHITESPACE;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			}
		    break;

		    case HDST_LINE1_WHITESPACE:
		    switch ( buf[bytes_handled] )
			{
			case ' ': case '\t':
			break;
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
			connections[cnum].http_status =
			    buf[bytes_handled] - '0';
			connections[cnum].header_state = HDST_LINE1_STATUS;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_LINE1_STATUS:
		    switch ( buf[bytes_handled] )
			{
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
			connections[cnum].http_status =
			    connections[cnum].http_status * 10 +
			    buf[bytes_handled] - '0';
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_BOL:
		    switch ( buf[bytes_handled] )
			{
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			case 'C': case 'c':
			connections[cnum].header_state = HDST_C;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_TEXT:
		    switch ( buf[bytes_handled] )
			{
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			break;
			}
		    break;

		    case HDST_LF:
		    switch ( buf[bytes_handled] )
			{
			case '\n':
			connections[cnum].conn_state = CNST_READING;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			case 'C': case 'c':
			connections[cnum].header_state = HDST_C;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CR:
		    switch ( buf[bytes_handled] )
			{
			case '\n':
			connections[cnum].header_state = HDST_CRLF;
			break;
			case '\r':
			connections[cnum].conn_state = CNST_READING;
			break;
			case 'C': case 'c':
			connections[cnum].header_state = HDST_C;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CRLF:
		    switch ( buf[bytes_handled] )
			{
			case '\n':
			connections[cnum].conn_state = CNST_READING;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CRLFCR;
			break;
			case 'C': case 'c':
			connections[cnum].header_state = HDST_C;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CRLFCR:
		    switch ( buf[bytes_handled] )
			{
			case '\n': case '\r':
			connections[cnum].conn_state = CNST_READING;
			break;
			case 'C': case 'c':
			connections[cnum].header_state = HDST_C;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_C:
		    switch ( buf[bytes_handled] )
			{
			case 'O': case 'o':
			connections[cnum].header_state = HDST_CO;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CO:
		    switch ( buf[bytes_handled] )
			{
			case 'N': case 'n':
			connections[cnum].header_state = HDST_CON;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CON:
		    switch ( buf[bytes_handled] )
			{
			case 'T': case 't':
			connections[cnum].header_state = HDST_CONT;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONT:
		    switch ( buf[bytes_handled] )
			{
			case 'E': case 'e':
			connections[cnum].header_state = HDST_CONTE;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTE:
		    switch ( buf[bytes_handled] )
			{
			case 'N': case 'n':
			connections[cnum].header_state = HDST_CONTEN;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTEN:
		    switch ( buf[bytes_handled] )
			{
			case 'T': case 't':
			connections[cnum].header_state = HDST_CONTENT;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT:
		    switch ( buf[bytes_handled] )
			{
			case '-':
			connections[cnum].header_state = HDST_CONTENT_;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_:
		    switch ( buf[bytes_handled] )
			{
			case 'L': case 'l':
			connections[cnum].header_state = HDST_CONTENT_L;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_L:
		    switch ( buf[bytes_handled] )
			{
			case 'E': case 'e':
			connections[cnum].header_state = HDST_CONTENT_LE;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LE:
		    switch ( buf[bytes_handled] )
			{
			case 'N': case 'n':
			connections[cnum].header_state = HDST_CONTENT_LEN;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LEN:
		    switch ( buf[bytes_handled] )
			{
			case 'G': case 'g':
			connections[cnum].header_state = HDST_CONTENT_LENG;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENG:
		    switch ( buf[bytes_handled] )
			{
			case 'T': case 't':
			connections[cnum].header_state = HDST_CONTENT_LENGT;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENGT:
		    switch ( buf[bytes_handled] )
			{
			case 'H': case 'h':
			connections[cnum].header_state = HDST_CONTENT_LENGTH;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENGTH:
		    switch ( buf[bytes_handled] )
			{
			case ':':
			connections[cnum].header_state = HDST_CONTENT_LENGTH_COLON;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENGTH_COLON:
		    switch ( buf[bytes_handled] )
			{
			case ' ': case '\t':
			connections[cnum].header_state = HDST_CONTENT_LENGTH_COLON_WHITESPACE;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENGTH_COLON_WHITESPACE:
		    switch ( buf[bytes_handled] )
			{
			case ' ': case '\t':
			break;
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
			connections[cnum].content_length = buf[bytes_handled] - '0';
			connections[cnum].header_state = HDST_CONTENT_LENGTH_COLON_WHITESPACE_NUM;
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    case HDST_CONTENT_LENGTH_COLON_WHITESPACE_NUM:
		    switch ( buf[bytes_handled] )
			{
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
			connections[cnum].content_length =
			    connections[cnum].content_length * 10 +
			    buf[bytes_handled] - '0';
			break;
			case '\n':
			connections[cnum].header_state = HDST_LF;
			break;
			case '\r':
			connections[cnum].header_state = HDST_CR;
			break;
			default:
			connections[cnum].header_state = HDST_TEXT;
			break;
			}
		    break;

		    }
		}
	    break;

	    case CNST_READING:
	    connections[cnum].bytes += bytes_read - bytes_handled;
	    if ( do_throttle )
		{
		/* Check if we're reading too fast. */
		elapsed = delta_timeval( &connections[cnum].started_at, nowP ) / 1000000.0;
		if ( elapsed > 0.01 && connections[cnum].bytes / elapsed > throttle )
		    {
		    connections[cnum].conn_state  = CNST_PAUSING;
		    client_data.i = cnum;
		    connections[cnum].wakeup_timer = tmr_create(
			nowP, wakeup_connection, client_data, 1000L, 0 );
		    }
		}
	    if ( do_checksum )
		{
		checksum = connections[cnum].checksum;
		for ( ; bytes_handled < bytes_read; ++bytes_handled )
		    {
		    if ( checksum & 1 )
			checksum = ( checksum >> 1 ) + 0x8000;
		    else
			checksum >>= 1;
		    checksum += buf[bytes_handled];
		    checksum &= 0xffff;
		    }
		connections[cnum].checksum = checksum;
		}
	    else
		bytes_handled = bytes_read;

	    if ( connections[cnum].content_length != -1 &&
		 connections[cnum].bytes >= connections[cnum].content_length )
		{
		close_connection( cnum );
		return;
		}

	    break;
	    }
コード例 #24
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
void CZapitClient::getConfig (Zapit_config * Cfg)
{
	send(CZapitMessages::CMD_GETCONFIG);
	CBasicClient::receive_data((char *) Cfg, sizeof(Zapit_config));
	close_connection();
}
コード例 #25
0
ファイル: http1.c プロジェクト: ifzz/h2o
static void handle_incoming_request(struct st_h2o_http1_conn_t *conn)
{
    size_t inreqlen = conn->sock->input->size < H2O_MAX_REQLEN ? conn->sock->input->size : H2O_MAX_REQLEN;
    int reqlen, minor_version;
    struct phr_header headers[H2O_MAX_HEADERS];
    size_t num_headers = H2O_MAX_HEADERS;
    ssize_t entity_body_header_index;
    h2o_iovec_t expect;

    /* need to set request_begin_at here for keep-alive connection */
    if (conn->req.timestamps.request_begin_at.tv_sec == 0)
        conn->req.timestamps.request_begin_at = *h2o_get_timestamp(conn->super.ctx, NULL, NULL);

    reqlen = phr_parse_request(conn->sock->input->bytes, inreqlen, (const char **)&conn->req.input.method.base,
                               &conn->req.input.method.len, (const char **)&conn->req.input.path.base, &conn->req.input.path.len,
                               &minor_version, headers, &num_headers, conn->_prevreqlen);
    conn->_prevreqlen = inreqlen;

    switch (reqlen) {
    default: // parse complete
        conn->_reqsize = reqlen;
        if ((entity_body_header_index = fixup_request(conn, headers, num_headers, minor_version, &expect)) != -1) {
            conn->req.timestamps.request_body_begin_at = *h2o_get_timestamp(conn->super.ctx, NULL, NULL);
            if (expect.base != NULL) {
                if (!h2o_lcstris(expect.base, expect.len, H2O_STRLIT("100-continue"))) {
                    set_timeout(conn, NULL, NULL);
                    h2o_socket_read_stop(conn->sock);
                    h2o_send_error(&conn->req, 417, "Expectation Failed", "unknown expectation",
                                   H2O_SEND_ERROR_HTTP1_CLOSE_CONNECTION);
                    return;
                }
                static const h2o_iovec_t res = {H2O_STRLIT("HTTP/1.1 100 Continue\r\n\r\n")};
                h2o_socket_write(conn->sock, (void *)&res, 1, on_continue_sent);
            }
            if (create_entity_reader(conn, headers + entity_body_header_index) != 0) {
                return;
            }
            if (expect.base != NULL) {
                /* processing of the incoming entity is postponed until the 100 response is sent */
                h2o_socket_read_stop(conn->sock);
                return;
            }
            conn->_req_entity_reader->handle_incoming_entity(conn);
        } else {
            set_timeout(conn, NULL, NULL);
            h2o_socket_read_stop(conn->sock);
            process_request(conn);
        }
        return;
    case -2: // incomplete
        if (inreqlen == H2O_MAX_REQLEN) {
            // request is too long (TODO notify)
            close_connection(conn, 1);
        }
        return;
    case -1: // error
        /* upgrade to HTTP/2 if the request starts with: PRI * HTTP/2 */
        if (conn->super.ctx->globalconf->http1.upgrade_to_http2) {
            /* should check up to the first octet that phr_parse_request returns an error */
            static const h2o_iovec_t HTTP2_SIG = {H2O_STRLIT("PRI * HTTP/2")};
            if (conn->sock->input->size >= HTTP2_SIG.len && memcmp(conn->sock->input->bytes, HTTP2_SIG.base, HTTP2_SIG.len) == 0) {
                h2o_accept_ctx_t accept_ctx = {conn->super.ctx, conn->super.hosts};
                h2o_socket_t *sock = conn->sock;
                struct timeval connected_at = conn->super.connected_at;
                /* destruct the connection after detatching the socket */
                conn->sock = NULL;
                close_connection(conn, 1);
                /* and accept as http2 connection */
                h2o_http2_accept(&accept_ctx, sock, connected_at);
                return;
            }
        }
        close_connection(conn, 1);
        return;
    }
}
コード例 #26
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
bool CZapitClient::Rezap()
{
        bool reply = send(CZapitMessages::CMD_REZAP);
        close_connection();
        return reply;
}
コード例 #27
0
ファイル: AuthSocket.cpp プロジェクト: maydayzm/mangos
/// Reconnect Challenge command handler
bool AuthSocket::_HandleReconnectChallenge()
{
    DEBUG_LOG("Entering _HandleReconnectChallenge");
    if (recv_len() < sizeof(sAuthLogonChallenge_C))
        return false;

    ///- Read the first 4 bytes (header) to get the length of the remaining of the packet
    std::vector<uint8> buf;
    buf.resize(4);

    recv((char *)&buf[0], 4);

    EndianConvert(*((uint16*)(buf[0])));
    uint16 remaining = ((sAuthLogonChallenge_C *)&buf[0])->size;
    DEBUG_LOG("[ReconnectChallenge] got header, body is %#04x bytes", remaining);

    if ((remaining < sizeof(sAuthLogonChallenge_C) - buf.size()) || (recv_len() < remaining))
        return false;

    //No big fear of memory outage (size is int16, i.e. < 65536)
    buf.resize(remaining + buf.size() + 1);
    buf[buf.size() - 1] = 0;
    sAuthLogonChallenge_C *ch = (sAuthLogonChallenge_C*)&buf[0];

    ///- Read the remaining of the packet
    recv((char *)&buf[4], remaining);
    DEBUG_LOG("[ReconnectChallenge] got full packet, %#04x bytes", ch->size);
    DEBUG_LOG("[ReconnectChallenge] name(%d): '%s'", ch->I_len, ch->I);

    _login = (const char*)ch->I;

    _safelogin = _login;
    LoginDatabase.escape_string(_safelogin);

    EndianConvert(ch->build);
    _build = ch->build;
    _os = (const char*)ch->os;

    if (_os.size() > 4)
        return false;

    QueryResult *result = LoginDatabase.PQuery ("SELECT sessionkey FROM account WHERE username = '******'", _safelogin.c_str ());

    // Stop if the account is not found
    if (!result)
    {
        sLog.outError("[ERROR] user %s tried to login and we cannot find his session key in the database.", _login.c_str());
        close_connection();
        return false;
    }

    Field* fields = result->Fetch ();
    K.SetHexStr (fields[0].GetString ());
    delete result;

    ///- Sending response
    ByteBuffer pkt;
    pkt << (uint8)  CMD_AUTH_RECONNECT_CHALLENGE;
    pkt << (uint8)  0x00;
    _reconnectProof.SetRand(16 * 8);
    pkt.append(_reconnectProof.AsByteArray(16),16);         // 16 bytes random
    pkt << (uint64) 0x00 << (uint64) 0x00;                  // 16 bytes zeros
    send((char const*)pkt.contents(), pkt.size());
    return true;
}
コード例 #28
0
ファイル: zapitclient.cpp プロジェクト: Firmeware/max-tdt
bool CZapitClient::tune_TP(TP_params TP)
{
	bool reply = send(CZapitMessages::CMD_TUNE_TP, (char*)&TP, sizeof(TP));
	close_connection();
	return reply;
}
コード例 #29
0
ファイル: rsc_server.c プロジェクト: virtualsquare/view-os
static void 
main_loop(int listen_fd, int event_sub_fd) {
  int i, nready;
  int new_fd;
  int deleted_entry;

  struct sockaddr_in client_addr;
  socklen_t client_len;

  pollfd_add(pfdinfo, listen_fd, POLLIN, NULL); 
  pollfd_add(pfdinfo, event_sub_fd, POLLIN, NULL); 

  /* Main loop */
  while(1) {
    deleted_entry = 0;
		GDEBUG(1, "Before poll():");
    PRINT_POLLFDINFO(pfdinfo);

    /* Poll */
    nready = poll(pfdinfo->pollfd, pfdinfo->nfds, -1);
    /* There is an error? */
    if(nready == -1) {
      fprintf(stderr, "poll() error: %s; I continue.\n", strerror(errno));
      continue;
    }

    for(i = 0; i < pfdinfo->nfds; i++) {
      if(pfdinfo->pollfd[i].revents == 0)
        continue;
      GDEBUG(1, "fd = %d is ready for event 0x%X\n", pfdinfo->pollfd[i].fd, pfdinfo->pollfd[i].revents);
      /* If there is an error, I close the connection */
      if( pfdinfo->pollfd[i].revents & POLLERR || pfdinfo->pollfd[i].revents & POLLHUP || 
          pfdinfo->pollfd[i].revents & POLLNVAL) {
          /* printf("Error, getchar():\n"); getchar(); */
          close_connection(pfdinfo, i);
          deleted_entry = 1;
          if(--nready < 0) break;
          continue;
      }

	    /*********************************************/
	    /* New Connection/Event Subscribe management */
	    /*********************************************/
	    if((pfdinfo->pollfd[i].fd == listen_fd || pfdinfo->pollfd[i].fd == event_sub_fd) 
          && pfdinfo->pollfd[i].revents & POLLIN) {
        enum client_type type;
        int size;
        enum client_state state;
        if(pfdinfo->pollfd[i].fd == listen_fd) {
          type = REQ_RESP;
          size = sizeof(struct handshake);
          state = WAITING_ARCH;
        } else {
          type = EVENT_SUB;
          size = sizeof(struct rsc_es_hdr);
          state = CONN_READING_HDR;
        }
        
	      bzero(&client_addr, sizeof(client_addr));
	      client_len = sizeof(client_addr);
	
	      /* I accept the new connection */
	      new_fd = accept(pfdinfo->pollfd[i].fd, (struct sockaddr *)&client_addr, &client_len); 
	
	      if(new_fd == -1) {
	        fprintf(stderr, "Accept() error: %s\n", strerror(errno));
	      } else {
	        /* I create the new client structure */
	        struct client *new_client;
          void *data;
	        new_client = create_client(new_fd, type, state);
          data = malloc(sizeof(struct handshake));
          if(data == NULL) {
            close(new_fd);
            if(--nready < 0) break;
            continue;
          }

	        if(new_client == NULL || data == NULL) {
	          fprintf(stderr, "I cannot create a new client struct for fd %d\n", new_fd);
            if(new_client == NULL)
              free(new_client);
            if(data == NULL);
              free(data);
	          close(new_fd);
	        } else {
            buff_enq(new_client->rbuf, data, size);
			      GDEBUG(1, "Accepting new connection from "); print_addr_port(new_client->fd); GDEBUG(1, " (fd = %d).\n", new_client->fd);
            pollfd_add(pfdinfo, new_client->fd, POLLIN, new_client);
	        }
	      }
	      if(--nready <= 0) break;
        /*************************************************************************/
        /* Management of descriptors ready to read of type REQ_RESP or EVENT_SUB */
        /*************************************************************************/
      } else if(pfdinfo->clients[i]->type == REQ_RESP || pfdinfo->clients[i]->type == EVENT_SUB) {
        struct client *client = pfdinfo->clients[i];
        /***********************************************/
        /*  POLLIN                                     */
        /***********************************************/
        if(pfdinfo->pollfd[i].revents &  POLLIN) {
	        void *buf;
	        int size, nread;
          /* If there are data to read, but the read buffer is empty 
           * I create a new message */
          if(client->rbuf->first == NULL) {
            int size = 0;
            void *data;
            if(pfdinfo->clients[i]->type == REQ_RESP && 
                pfdinfo->clients[i]->state == CONN_READING_HDR)
              size = sizeof(struct req_header);
            else if(pfdinfo->clients[i]->type == EVENT_SUB && 
                pfdinfo->clients[i]->state == CONN_READING_HDR)
              size = sizeof(struct rsc_es_hdr);
            if(size != 0) {
              data = malloc(size);
              if(data == NULL) {
                close_connection(pfdinfo, i);
                deleted_entry = 1;
                if(--nready < 0) break;
                continue;
              }

              buff_enq(client->rbuf, data, size);
            }
          }
		      GDEBUG(1, "There are data ready do be read for fd %d", pfdinfo->pollfd[i].fd);
          /* I read the data from the first message */
	        buf = client->rbuf->first->data + client->rbuf->first->n;
	        size = client->rbuf->first->tot - client->rbuf->first->n;
			    nread = read(client->fd, buf, size);
	        if(nread <= 0 ) {
	          /* If there is an error or the connection was close,
             * I close the connection from my side */
            close_connection(pfdinfo, i);
            deleted_entry = 1;
            if(--nready <= 0) break;
            continue;
          } else {
	          client->rbuf->first->n += nread;
          }
			    
          /* If I've read all the data, I remove the buffer from client->rbuf
           * and I process the data */
			    if(client->rbuf->first->n == client->rbuf->first->tot) {
            void *read_data = buff_deq(client->rbuf);
	          if(pfdinfo->clients[i]->type == REQ_RESP) {
				      if(client->state == WAITING_ARCH) {
			          /* I read the architecture of the client */
					      struct handshake *client_arch, *server_arch;
			          client_arch = (struct handshake *)read_data;
				
						    client->arch = ntohl(client_arch->arch);
						    GDEBUG(1, "Client (%d) architecture is %s\n", client->fd, aconv_arch2str(client->arch));
                free(read_data);
						    
						    /* Now I can send my architecture */
		            client->state = SENDING_ARCH;
		            server_arch = calloc(1, sizeof(struct handshake));
		            if(server_arch == NULL) {
                  close_connection(pfdinfo, i);
                  deleted_entry = 1;
                  if(--nready < 0) break;
                  continue;
                }
                server_arch->arch = htonl(my_arch);
		            buff_enq(client->wbuf, server_arch, sizeof(struct handshake));
                pfdinfo->pollfd[i].events |=  POLLOUT;
                client->state = SENDING_ARCH;
				      }else if(client->state == CONN_READING_HDR) {
			          struct req_header *req_hd;
                struct msg *m;
		            int req_size;
                void *new_data;
		            /* I've read all the request header, now I've to read all the request body */
                client->state = CONN_READING_BODY;
		            req_hd = (struct req_header *)read_data;
			          req_size = rsc_req_msg_size(req_hd);
                new_data = realloc(read_data, req_size);
                if(new_data == NULL) {
                  close_connection(pfdinfo, i);
                  deleted_entry = 1;
                  if(--nready < 0) break;
                  continue;
                }

		            m = buff_enq(client->rbuf, new_data, req_size);
                /* I've already read the req_header, so I need to update m->n field */
                m->n = sizeof(struct req_header);
		          }else if(client->state == CONN_READING_BODY) {
			          /* Now I've read all the request and I can pass it to RSC function */
                struct iovec *resp;
					      resp = rscs_manage_request(client->arch, read_data);
                /* If there is an error, I close the connection */
                if(resp == NULL) {
                  close_connection(pfdinfo, i);
                  deleted_entry = 1;
                  if(--nready < 0) break;
                  continue;
                }
		            buff_enq(client->wbuf, resp[0].iov_base, resp[0].iov_len);
                pfdinfo->pollfd[i].events |=  POLLOUT;
                client->state = CONN_SENDING_RESP;
                free(read_data);
              }
            } else {
	            /* type == EVENT_SUB */
				      if(client->state == CONN_READING_HDR) {
	              struct rsc_es_hdr *hdr;
	              int size;
                void *new_data;
                struct msg *m;
	              hdr = (struct rsc_es_hdr *)read_data;
	              size = rsc_es_msg_size(hdr->type);
	              if(size == -1) {
                  close_connection(pfdinfo, i);
                  deleted_entry = 1;
                  if(--nready < 0) break;
                  continue;
                }
                new_data = realloc(read_data, size);
                if(new_data == NULL) {
                  close_connection(pfdinfo, i);
                  deleted_entry = 1;
                  if(--nready < 0) break;
                  continue;
                }
                m = buff_enq(client->rbuf, new_data, size);
                m->n = sizeof(struct rsc_es_hdr);
                client->state = CONN_READING_BODY;
	            } else if(client->state == CONN_READING_BODY) {
	              struct rsc_es_ack *ack;
	              ack = rscs_es_manage_msg(client->fd, read_data);
                free(read_data);
			          /* I take the appropriate action based on ack->response field.
			           * If the response is ACK_FD_REG I've to insert the fd into the
			           * pollfd set. If the response is ACK_FD_DEREG_NOT_READY or ACK_FD_READY,
			           * I remove the fd from the pollfd. */
			          if(ack->response == ACK_FD_REG) {
				          struct client *c;
			            /* Into the client structure I insert the stream fd and not the 
			             * fd to subscribe, In this way I can know where to send data */
			            c = create_client(client->fd, SUBSCRIBED_FD, CONN_SENDING_RESP);
                  if(c == NULL) {
                    close_connection(pfdinfo, i);
                    deleted_entry = 1;
                    if(--nready < 0) break;
                    continue;
                  }
                  c->esfd_index = i;
			            pollfd_add(pfdinfo, ntohl(ack->fd), ntohl(ack->how), c);
			          } else if(ack->response == ACK_FD_DEREG_NOT_READY || ack->response == ACK_FD_DEREG_READY) {
			            int j;
			            for(j = 0; j < pfdinfo->size; j++) 
			              if( pfdinfo->pollfd[j].fd != -1 &&
			                  pfdinfo->clients[j] != NULL &&
			                  pfdinfo->clients[j]->type == SUBSCRIBED_FD &&
			                  pfdinfo->clients[j]->fd == client->fd && 
			                  pfdinfo->pollfd[j].fd == ntohl(ack->fd) && 
			                  pfdinfo->pollfd[j].events == ntohl(ack->how))
			                break;
			            if(j < pfdinfo->size)
			              pollfd_del(pfdinfo, j);
			          }
			          GDEBUG(1, "After rscem_manage_msg:");
			          PRINT_POLLFDINFO(pfdinfo);
	              /* Now I can send ack back */
                buff_enq(client->wbuf, ack, sizeof(struct rsc_es_ack));
                pfdinfo->pollfd[i].events |=  POLLOUT;
                /* It's not an error, I don't need to keep trace of the sending state */
                client->state = CONN_READING_HDR;
	            }
	          }
          }
          /***********************************************/
          /*  POLLOUT                                    */
          /***********************************************/
        } else if(pfdinfo->pollfd[i].revents & POLLOUT) {
	        void *buf;
	        int size, nwrite;
          /* If write buffer is empty, I remove the POLLOUT event and I continue */
          if(client->wbuf->first == NULL) {
            pfdinfo->pollfd[i].events &= (~POLLOUT);
            if(--nready <= 0) 
              break;
            continue;
          }
		      GDEBUG(1, "There are data ready do be written for fd %d", pfdinfo->pollfd[i].fd);
	        buf = client->wbuf->first->data + client->wbuf->first->n;
	        size = client->wbuf->first->tot - client->wbuf->first->n;
			    nwrite = write(client->fd, buf, size);
          if(nwrite < 0) {
            close_connection(pfdinfo, i);
            deleted_entry = 1;
            if(--nready < 0) break;
            continue;
          } else {
            client->wbuf->first->n += nwrite;
          }
			    if(client->wbuf->first->n == client->wbuf->first->tot) {
            /* I remove the message from the buffer and I free it */
            void *data = buff_deq(client->wbuf);
            free(data);
            /* If it's a request/response fd and I've sent an arch or response message,
             * I change my state to reading header */
	          if( pfdinfo->clients[i]->type == REQ_RESP && 
                ( client->state == SENDING_ARCH || client->state == CONN_SENDING_RESP) )
              client->state = CONN_READING_HDR;
	          /* if client->type is EVENT_SUB  there is nothing to do: I need only
            * to continue to send the buffered data */
          }
        }
        if(--nready <= 0) break;
      /*******************************************/
      /* An event subscribed fd is waken up      */
      /*******************************************/
      /* The event is occurred, I send back a response I didn't it before */
      }else if(pfdinfo->clients[i]->type == SUBSCRIBED_FD) {
        struct rsc_es_resp *resp;
        int esfd_index = pfdinfo->clients[i]->esfd_index;

        resp = rscs_es_event_occurred(pfdinfo->pollfd[esfd_index].fd, pfdinfo->pollfd[i].fd, pfdinfo->pollfd[i].revents);
        if(resp != NULL) {
          buff_enq(pfdinfo->clients[esfd_index]->wbuf, resp, sizeof(struct rsc_es_resp)); 
          pfdinfo->pollfd[esfd_index].events |=  POLLOUT;
        } 
	      if(--nready <= 0) break;
      }
    } /* for(i = 0; i < nready; i++) */
    /* If I've deleted a pfdinfo, I compact it */
    if(deleted_entry)
      pollfd_compact(pfdinfo);
  } /* while(1) */
}
コード例 #30
0
void CControldClient::saveSettings()
{
        send(CControldMsg::CMD_SAVECONFIG);
        close_connection();
}