Example #1
0
//## int cbufferevent.socket_connect(Sockaddr_in sa);
static KMETHOD cbufferevent_socket_connect(KonohaContext *kctx, KonohaStack *sfp)
{
	kcbufferevent *bev = (kcbufferevent *)sfp[0].asObject;
	kSockaddr_in *sa = (kSockaddr_in *)sfp[1].asObject;
	int ret = bufferevent_socket_connect(bev->bev, (struct sockaddr *)&sa->sockaddr, sizeof sa->sockaddr);
	KReturnUnboxValue(ret);
}
Example #2
0
void InitConnectTo(Server *pServer) {

    struct sockaddr_in sa;

    u32 ip;
    inet_aton(pServer->host, &ip);
    sa.sin_addr = *((struct in_addr *) & ip);
    sa.sin_family = AF_INET;
    sa.sin_port = htons(pServer->port);
    bzero(&sa.sin_zero, 8);


    gettimeofday(&tv, NULL);
    printf("InitConnectTo()  [time: %d]\n", tv.tv_sec);

    pServer->poll->status = 1;
    timerclear(&tv);
     tv.tv_usec=pServer->timeout*1000*1000;

    pServer->poll->bev = bufferevent_socket_new(pServer->evConfig.ev_base, -1, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_socket_connect(pServer->poll->bev ,(struct sockaddr *)&sa, sizeof(sa));
    bufferevent_setcb(pServer->poll->bev, OnBufferedRead, OnBufferedWrite, OnBufferedError, pServer);
    bufferevent_enable(pServer->poll->bev, EV_READ|EV_WRITE |EV_TIMEOUT);
    bufferevent_set_timeouts(pServer->poll->bev, &tv, &tv);

}
Example #3
0
static void
bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
    void *arg)
{
	struct bufferevent *bev = arg;
	struct bufferevent_private *bev_p =
	    EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
	int r;
	BEV_LOCK(bev);

	bufferevent_unsuspend_write_(bev, BEV_SUSPEND_LOOKUP);
	bufferevent_unsuspend_read_(bev, BEV_SUSPEND_LOOKUP);

	if (result != 0) {
		bev_p->dns_error = result;
		bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR);
		bufferevent_decref_and_unlock_(bev);
		if (ai)
			evutil_freeaddrinfo(ai);
		return;
	}

	/* XXX use the other addrinfos? */
	/* XXX use this return value */
	r = bufferevent_socket_connect(bev, ai->ai_addr, (int)ai->ai_addrlen);
	(void)r;
	bufferevent_decref_and_unlock_(bev);
	evutil_freeaddrinfo(ai);
}
Example #4
0
int BotMonitor::connect(const InetAddr& serverAddr)
{
	MutexLockConditionGuard lock(this->m_mutex, this->threadType() == TT_multi_thread);
	for (int i = BOT_DATA->m_nAccountIndex; //
			i < BOT_DATA->m_nAccountIndex + BOT_DATA->m_nBotAmout; ++i)
	{
		BotConnection *conn = new BotConnection();
		conn->init(i, this, true);
		bufferevent_socket_connect(conn->bevent(),//
				(struct sockaddr *)&serverAddr.addr_,//
				sizeof(serverAddr.addr_));

		std::string strIndex = convert<std::string>(i);
		std::string strAccount = BOT_DATA->m_strAccountPre + strIndex + "&";

		this->m_connMap.insert(std::make_pair(i, conn));
		GameBot* bot = new GameBot(i, strAccount);
		this->m_botMap.insert(std::make_pair(i, bot));

		int hz = BOT_DATA->m_nConnectHz > 0 ? BOT_DATA->m_nConnectHz : 10;
		usleep(1000000 / hz);
	}

	return 0;
}
Example #5
0
        void CTcpHandler::TcpConnect(CCommand *pCmd)
        {
	        NsqLogPrintf(LOG_DEBUG, "TcpConnect\n");
            CTcpConnectCommand *pConnectCmd = dynamic_cast<CTcpConnectCommand *>(pCmd);
            m_strHost = pConnectCmd->m_strHost;
            m_iPort = pConnectCmd->m_iPort;
            sockaddr_in sAddr;
            memset(&sAddr, 0, sizeof(sockaddr_in));
            sAddr.sin_addr.s_addr = inet_addr(pConnectCmd->m_strHost.c_str());
            sAddr.sin_port = htons(pConnectCmd->m_iPort);
            sAddr.sin_family = AF_INET;

            CNetThread *pThread = dynamic_cast<CNetThread *>(GetThread()); 
            m_pBufevt = bufferevent_socket_new(pThread->GetEventBase(), -1, BEV_OPT_THREADSAFE);
            int32_t iRet = bufferevent_socket_connect(m_pBufevt, (sockaddr*)&sAddr, sizeof(sockaddr_in));
             
            if (iRet != 0)
            {
                OnError(errno); 
                return ;
            }

            bufferevent_setcb(m_pBufevt, CNetThread::OnStaticRead, CNetThread::OnStaticWrite, CNetThread::OnStaticError, this);
            bufferevent_enable(m_pBufevt, EV_READ|EV_PERSIST|EV_ET);		

            //设置读入最低水位,防止无效回调
            bufferevent_setwatermark(m_pBufevt, EV_READ, 
                                     OnRead(NULL, 0), 0);

            SetTimeout();
        }
Example #6
0
static void
bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
    void *arg)
{
	struct bufferevent *bev = arg;
	int r;
	BEV_LOCK(bev);

	bufferevent_unsuspend_write(bev, BEV_SUSPEND_LOOKUP);
	bufferevent_unsuspend_read(bev, BEV_SUSPEND_LOOKUP);

	if (result != 0) {
		/* XXX Communicate the error somehow. */
		_bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
		_bufferevent_decref_and_unlock(bev);
		if (ai)
			evutil_freeaddrinfo(ai);
		return;
	}

	/* XXX use the other addrinfos? */
	r = bufferevent_socket_connect(bev, ai->ai_addr, ai->ai_addrlen);
	_bufferevent_decref_and_unlock(bev);
	evutil_freeaddrinfo(ai);
}
Example #7
0
File: 3c.c Project: edwardL/edward
int main(int argc, char** argv)
{
	if(argc < 3)
	{
		printf("please input 2 parameter\n");
		return -1;
	}
	struct event_base* base = event_base_new();
	struct bufferevent* bev = bufferevent_socket_new(base,-1,
			BEV_OPT_CLOSE_ON_FREE);
	struct event* ev_cmd = event_new(base,STDIN_FILENO,
			EV_READ|EV_PERSIST,
			cmd_msg_cb,(void*)bev);
	event_add(ev_cmd,NULL);
	struct sockaddr_in server_addr;
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	inet_aton(argv[1],&server_addr.sin_addr);

	bufferevent_socket_connect(bev,(struct sockaddr*)&server_addr,
			sizeof(server_addr));
	bufferevent_setcb(bev,server_msg_cb,NULL,event_cb,(void*)ev_cmd);
	bufferevent_enable(bev,EV_READ|EV_PERSIST);

	printf("finished\n");
	return 0;
}
Example #8
0
// return 0 if there is valid bufferevent
int CBinaryWriter::connect(){
	int ret;
	if( state == CONNECTING || state == CONNECTED ){
		ret = 0;
		goto ret;
	}
	if( be != NULL ){
		bufferevent_free(be);
		be = NULL;
	}
	be =  bufferevent_socket_new((struct event_base *)base, -1, 0);
	if( bufferevent_disable (be, EV_READ) ){
		goto error;
	}
	bufferevent_setcb(be, NULL, NULL, event_cb, this);
	if( bufferevent_socket_connect(be, addr, addr_len) ){
		goto error;
	}
	ret = 0;
	state = CONNECTING;
ret:
	return ret;

error:
	ret = -1;
	if( be != NULL ){
		bufferevent_free(be);
		be = NULL;
	}   
	goto ret;    
}
Example #9
0
	void Conn::run()
	{
		if(conn_type & CONN_TYPE_LISTENER)
		{
			this->pEvbase = event_base_new();
			struct evconnlistener* pEvConn = evconnlistener_new_bind(this->pEvbase,
																	OnConnListenerCb,
																	(void*)this,
																	LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
																	-1,
																	(struct sockaddr*)&sAddrIn,
																	sizeof(struct sockaddr_in));

			if(!pEvConn)
			{
				LOG_DEBUG("server on " << addr << ":" << ntohs(sAddrIn.sin_port) << " fail");
				return;
			}

			LOG_DEBUG("server on " << addr << ":" << ntohs(sAddrIn.sin_port));
			evconnlistener_set_error_cb(pEvConn, OnConnListenerErrCb);
			event_base_dispatch(this->pEvbase);
			return;
		}

		if(conn_type & CONN_TYPE_CONNECTER)
		{
			this->pEvbase = event_base_new();
			this->pConnEvBuf = bufferevent_socket_new(this->pEvbase, -1, BEV_OPT_CLOSE_ON_FREE);
			bufferevent_setcb(this->pConnEvBuf, OnReadCbAddr, NULL, OnConnEventCb, (void*)this);

			if(bufferevent_socket_connect(this->pConnEvBuf, (struct sockaddr*)&sAddrIn, sizeof(struct sockaddr_in)) != 0)
			{
				LOG_DEBUG("conn on " << addr << ":" << ntohs(sAddrIn.sin_port) << " fail");
				bufferevent_free(this->pConnEvBuf);
				return;
			}

			LOG_DEBUG("conn on " << addr << ":" << ntohs(sAddrIn.sin_port));

			struct event* pEvent = NULL;
			evutil_socket_t fd = bufferevent_getfd(this->pConnEvBuf);

			if(fd != -1 && OnTimingCbAddr != NULL)
			{
				pEvent = event_new(this->pEvbase, fd, EV_PERSIST, OnTimingEventCb, (void*)this);
				event_add(pEvent, &this->tv);
			}

			bufferevent_enable(this->pConnEvBuf, EV_READ);
			event_base_dispatch(this->pEvbase);

			if(fd != -1 && OnTimingCbAddr != NULL)
			{
				event_del(pEvent);
			}

			return;
		}
	}
Example #10
0
    void connectToServer(const char *address, const char *port,
            EventHandler *pProcessor) {
        sockaddr_in sin = { 0 };

        sin.sin_family = AF_INET;
        sin.sin_port = htons(atoi(port));
        inet_pton(AF_INET, address, &(sin.sin_addr));

        // Investigate: set reuse address and make socket nonblocking?

        bufferevent *bev = bufferevent_socket_new(m_ebase, -1,
                BEV_OPT_CLOSE_ON_FREE);

        bufferevent_setcb(bev, readfn, NULL, errorfn, (void*) pProcessor);
        pProcessor->setContext((Context*) bev);
        setParent(pProcessor);
        if (bufferevent_socket_connect(bev, (struct sockaddr *) &sin,
                sizeof(sin)) < 0) {
            ERROR_OUT("Cannot bind to port %s", port);
            /* Error starting connection */
            bufferevent_free(bev);
            exit(1);
        }

    }
Example #11
0
bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB&  _disconnected)
{
    if (b_conn)
        Disconnect();
    // Parse target address:port
    struct sockaddr_storage connect_to_addr;
    int connect_to_addrlen = sizeof(connect_to_addr);
    if (evutil_parse_sockaddr_port(target.c_str(),
        (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
        LogPrintf("tor: Error parsing socket address %s\n", target);
        return false;
    }

    // Create a new socket, set up callbacks and enable notification bits
    b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
    if (!b_conn)
        return false;
    bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this);
    bufferevent_enable(b_conn, EV_READ|EV_WRITE);
    this->connected = _connected;
    this->disconnected = _disconnected;

    // Finally, connect to target
    if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
        LogPrintf("tor: Error connecting to address %s\n", target);
        return false;
    }
    return true;
}
Example #12
0
int main(int argc, char **argv)
{
    struct sockaddr_in serv_addr;
    struct event_base *base;
    struct bufferevent *bev, *bev_stdout;
    int i, addr_len = sizeof serv_addr;
    struct timeval timeout = {1, 0};
    
    base = event_base_new();
    if (evutil_parse_sockaddr_port("127.0.0.1:8200", (struct sockaddr *)&serv_addr, &addr_len)) {
        printf("evutil_parse_sockaddr_port");
        exit(1);
    }


    for (i = 0; i < 10; i++) {

        bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
        bufferevent_setcb(bev, readcb, writecb, eventcb, NULL);
        bufferevent_enable(bev, EV_READ | EV_WRITE);
        bufferevent_set_timeouts(bev, &timeout, &timeout);
        evbuffer_add_printf(bufferevent_get_output(bev), websocket_request);

        if (bufferevent_socket_connect(bev, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
            bufferevent_free(bev);
            printf("bufferevent_socket_connect");
            exit(1);
        }
    }

    event_base_dispatch(base);
}
Example #13
0
bufferevent * connect_by_ipport(const char * ip_port)
{
	bufferevent * bev =NULL;
	do 
	{
		struct sockaddr saddr;
		int saddr_len =sizeof(saddr);
		if(0!=evutil_parse_sockaddr_port(ip_port, &saddr, &saddr_len))
		{
			printf("evutil_parse_sockaddr_port failed! \n");
			break;
		}

		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
		int rt =bufferevent_socket_connect(bev,(struct sockaddr *)&saddr, sizeof(saddr));
		if ( rt!= 0) {
				bufferevent_free(bev);
				break;
		}
		bufferevent_setcb(bev, readcb, writecb, eventcb, NULL);
		bufferevent_enable(bev, EV_READ|EV_WRITE);

	} while (0);
	return bev;
}
Example #14
0
static void go_connecting(int fd, short what, void *arg)
{
	CONNECTOR *cr = (CONNECTOR *)arg;
	bufferevent_socket_connect(cr->bev, cr->sa, cr->socklen);
	PUTS("bufferevent_socket_connect %s", __FUNCTION__);

}
Example #15
0
    /**
     * Redisサーバへ接続
     *
     * @access public
     * @return bool
     */
    bool rediscli::connection() {
        struct sockaddr *address;
        int length;

        if (port >= 1 && port <= 65535) {
            struct sockaddr_in sin;
            bzero(&sin, sizeof(sin));
            sin.sin_family = AF_INET;
            sin.sin_addr.s_addr = inet_addr(listen.c_str());
            sin.sin_port = htons(port);
            
            address = (struct sockaddr *)&sin;
            length  = sizeof(sin);
        } else {
            struct sockaddr_un sun;
            bzero(&sun, sizeof(sun));
            sun.sun_family = AF_LOCAL;
            strcpy(sun.sun_path, listen.c_str());

            address = (struct sockaddr *)&sun;
            length  = sizeof(sun);
        }


        if (bufferevent_socket_connect(bev, address, length) < 0) {
            log::error("Could not connect a redis server!");
            return false;
        }

        return true;
    }
Example #16
0
static void accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
    struct sockaddr *a, int slen, void *p)
{
        struct bufferevent *b_out, *b_in;
        b_in = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
        b_out = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);

        if(!(b_in && b_out))
	    {
			printf("bufferevent_sock_new Error\n");
			exit(1);
		}
          

		if (bufferevent_socket_connect(b_out, (struct sockaddr*)&client_addr, client_addrlen)<0) {
                perror("bufferevent_socket_connect");
                bufferevent_free(b_out);
                bufferevent_free(b_in);
                return;
        }

        bufferevent_setcb(b_in, readcb, NULL, NULL, b_out);
        bufferevent_setcb(b_out, readcb, NULL, NULL, b_in);

        bufferevent_enable(b_in, EV_READ|EV_WRITE);
        bufferevent_enable(b_out, EV_READ|EV_WRITE);
}
int
main ()
{
    int sockfd;
    struct bufferevent *p_event;
    struct sockaddr_in addr;

    ff = fopen("/tmp/log", "w");
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);

    if (inet_pton(AF_INET, SVRADDR, &addr.sin_addr) <= 0) {
        printf("inet_pton");
        exit(1);
    }

    if ((p_base = event_base_new()) == NULL) {
        printf("event_base_new ");
        return 1;
    }

    /* we do not need invoke socket function to create socket */
    if ((p_event = bufferevent_socket_new(p_base, -1, BEV_OPT_CLOSE_ON_FREE)) == NULL) {
        printf("bufferevent_socket_new ");
        return 1;
    }

    /* client actually connecte to server at this time. */
    if ((sockfd = bufferevent_socket_connect(p_event, (struct sockaddr *) &addr,
                                             sizeof(addr))) < 0) {
        printf("bufferevent_socket_connect ");
        return 1;
    }

    /* EV_WRITE is enbaled by default, so the underlying evbuffer writecb will be called when dispatch.
     * evbuffer writecb FOUND that there is no data to be sent, return.
     * evbuffer writecb is not persisted. (If persisted, evbuffer writecb will be called again and agian, see event_write
     * So there is no pending event in base, base will exit.
     */
    bufferevent_setcb(p_event, NULL, event_output, buff_ev_cb, p_base);

    /* write data to evbuffer, So when evbuffer cb FOUND there is data, send it out. 
     * And, call the bufferevent cb based on water mark.
     */
    bufferevent_write (p_event, "nisssssssssdssssssssa", 20);

    /*
     * normally, If evbuffer cb send data, FOUND that : the left data len is < 10, then bufferevent writecb
     * will be invoked to tell ME.
     * hey, there almost no data!!
     */
    bufferevent_setwatermark(p_event, EV_WRITE, 10, -1);
    
    sleep (10);
    event_base_dispatch(p_base);

    return 0;
}
Example #18
0
	static void
accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
		struct sockaddr *a, int slen, void *p)
{
	/* Extract and display the address we're connect. */
	struct sockaddr_storage ss;
	ev_socklen_t socklen = sizeof(ss);
	char addrbuf[128];
	void *inaddr;
	const char *addr;
	int got_port = -1;
	memset(&ss, 0, sizeof(ss));
	if (getpeername(fd, (struct sockaddr *)&ss, &socklen)) {
		perror("getpeerkname() failed");
		return ;
	}
	if (ss.ss_family == AF_INET) {
		got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
		inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
	} else if (ss.ss_family == AF_INET6) {
		got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
		inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
	} else {
		fprintf(stderr, "Weird address family %d\n",
				ss.ss_family);
		return;
	}
	addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf, sizeof(addrbuf));
	if (addr) {
		printf("connection from address %s:%d\n", addr, got_port);
	} else {
		fprintf(stderr, "evutil_inet_ntop failed\n");
		return ;
	}
	struct bufferevent *b_out, *b_in;
	/* Create two linked bufferevent objects: one to connect, one for the
	 * new connection */
	b_in = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);

	b_out = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);


	assert(b_in && b_out);

	if (bufferevent_socket_connect(b_out, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) 
	{
		perror("bufferevent_socket_connect");
		bufferevent_free(b_out);
		bufferevent_free(b_in);
		return;
	}

	bufferevent_setcb(b_in, readcbin, NULL, eventcbin, b_out);
	bufferevent_setcb(b_out, readcbout, NULL, eventcbout, b_in);

	bufferevent_enable(b_in, EV_READ|EV_WRITE);
	bufferevent_enable(b_out, EV_READ|EV_WRITE);
}
Example #19
0
File: conn.c Project: 0xffea/shim
int
conn_connect_bufferevent(struct bufferevent *bev, struct evdns_base *dns,
			 int family, const char *name, int port,
			 conn_connectcb conncb, void *arg)
{
	struct conninfo *info;
	int rv = -1;
	

	info = mem_calloc(1, sizeof(*info));
	info->bev = bev;
	info->on_connect = conncb;
	info->cbarg = arg;
	info->connecting = 1;
	info->socks = use_socks;

	bufferevent_setcb(bev, conn_readcb, NULL, conn_errorcb, info);
	if (use_socks != SOCKS_NONE) {
		info->host = mem_strdup(name);
		info->port = port;
		if (use_socks == SOCKS_4a) {
			rv = bufferevent_socket_connect(bev,
					(struct sockaddr*)&socks_addr,
					socks_addr_len);
			return rv;
		}
#ifndef DISABLE_DIRECT_CONNECTIONS
		else {
			struct evutil_addrinfo hint;
			char portstr[NI_MAXSERV];

			evutil_snprintf(portstr, sizeof(portstr), "%d", port);
			memset(&hint, 0, sizeof(hint));
			hint.ai_family = AF_INET;
			hint.ai_protocol = IPPROTO_TCP;
			hint.ai_socktype = SOCK_STREAM;

			evdns_getaddrinfo(dns, name, portstr, &hint,
				          socks_resolvecb, info);
			return 0;
		}
#endif
	}
#ifdef DISABLE_DIRECT_CONNECTIONS
	{
		const char *msg;
		msg = "Direct connections disabled, but I have no SOCKS 4a "
		      "proxy to connect to!";
		log_error("conn: %s", msg);
		finish_connection(info, 0, msg);
	}
#else
	rv =  bufferevent_socket_connect_hostname(bev, dns, family, name, port);
#endif

	return rv;
}
Example #20
0
static void
test_bufferevent_connect(void *arg)
{
	struct basic_test_data *data = arg;
	struct evconnlistener *lev=NULL;
	struct bufferevent *bev1=NULL, *bev2=NULL;
	struct sockaddr_in localhost;
	struct sockaddr *sa = (struct sockaddr*)&localhost;

	memset(&localhost, 0, sizeof(localhost));

	localhost.sin_port = htons(27015);
	localhost.sin_addr.s_addr = htonl(0x7f000001L);
	localhost.sin_family = AF_INET;

	lev = evconnlistener_new_bind(data->base, listen_cb, data->base,
	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
	    16, sa, sizeof(localhost));
	tt_assert(lev);
	tt_assert(!evconnlistener_enable(lev));
	bev1 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
	bev2 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
	bufferevent_setcb(bev1, NULL, NULL, reader_eventcb, data->base);
	bufferevent_setcb(bev2, NULL, NULL, reader_eventcb, data->base);

	tt_want(!bufferevent_socket_connect(bev1, sa, sizeof(localhost)));
	tt_want(!bufferevent_socket_connect(bev2, sa, sizeof(localhost)));

	bufferevent_enable(bev1, EV_READ);
	bufferevent_enable(bev2, EV_READ);

	event_base_dispatch(data->base);

	tt_int_op(n_strings_read, ==, 2);
end:
	if (lev)
		evconnlistener_free(lev);

	if (bev1)
		bufferevent_free(bev1);

	if (bev2)
		bufferevent_free(bev2);
}
Example #21
0
static void
connect_peer(struct peer* p)
{
	bufferevent_enable(p->bev, EV_READ|EV_WRITE);
	bufferevent_socket_connect(p->bev, 
		(struct sockaddr*)&p->addr, sizeof(p->addr));
	socket_set_nodelay(bufferevent_getfd(p->bev));
	paxos_log_info("Connect to %s:%d", 
		inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port));
}
Example #22
0
static void new_connection(state *s) {
    struct bufferevent *bev;
    struct timeval timeout={3, 0}; /* 3 seconds */

    s->mode=0;
    s->ptr=0;
    s->len=sizeof(record);
    bev=bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_set_timeouts(bev, &timeout, &timeout);
    bufferevent_setcb(bev, read_cb, write_cb, event_cb, s);
    bufferevent_socket_connect(bev, addr, addr_len);
}
Example #23
0
static void drone_rampup_timer_cb(evutil_socket_t fd, short what, void *arg) {
    struct job *job = arg;
    Drone__JobRequest *request = job->request;
    struct session *session;
    struct bufferevent *bev;
    struct sockaddr_in echo_sin;
    struct timeval timeout;
    u_int64_t sessions;
    u_int64_t i;

    if (job->client == NULL)
        return;

    if ((request->sessions - job->cur_sessions) > request->rampup_sessions)
        sessions = request->rampup_sessions;
    else
        sessions = request->sessions - job->cur_sessions;

    memset(&echo_sin, 0, sizeof(echo_sin));
    echo_sin.sin_family = AF_INET;
    echo_sin.sin_addr.s_addr = htonl(request->ipv4);
    echo_sin.sin_port = htons(request->port);

    for (i = 0; i < sessions; i++) {
        bev = bufferevent_socket_new(job->client->base, -1,
                BEV_OPT_CLOSE_ON_FREE);

        session = malloc(sizeof(struct session));

        bufferevent_setcb(bev, drone_read_cb, NULL, drone_event_cb, session);
        bufferevent_enable(bev, EV_READ | EV_WRITE);

        timeout.tv_sec = request->timeout;
        timeout.tv_usec = 0;
        bufferevent_set_timeouts(bev, NULL, &timeout);

        if (bufferevent_socket_connect(bev, (struct sockaddr *) &echo_sin,
                sizeof(echo_sin)) < 0) {
            bufferevent_free(bev);
            free(session);
            perror("Error during connection");
            return;
        }

        session->job = job;
        session->bev = bev;
        session->remaining_data = 0;

        job->sessions[job->cur_sessions] = session;
        job->cur_sessions++;
    }
}
int
main ()
{
    int sockfd;
    struct bufferevent *p_event;
    struct sockaddr_in addr;

    ff = fopen("/tmp/log", "w");
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);

    if (inet_pton(AF_INET, SVRADDR, &addr.sin_addr) <= 0) {
        printf("inet_pton");
        exit(1);
    }

    if ((p_base = event_base_new()) == NULL) {
        printf("event_base_new ");
        return 1;
    }

    /* we do not need invoke socket function to create socket */
    if ((p_event = bufferevent_socket_new(p_base, -1, BEV_OPT_CLOSE_ON_FREE)) == NULL) {
        printf("bufferevent_socket_new ");
        return 1;
    }

    /* client actually connecte to server at this time. */
    if ((sockfd = bufferevent_socket_connect(p_event, (struct sockaddr *) &addr,
                                             sizeof(addr))) < 0) {
        printf("bufferevent_socket_connect ");
        return 1;
    }

    /* EV_WRITE is default enabled, EV_READ is default disabled */
    /* So If we disable READ, evbuffer callback will not be added to base (read and write) */
    bufferevent_setcb(p_event, buff_input_cb, NULL, eventcb, p_base);
    bufferevent_enable(p_event, EV_WRITE);

    /* edge-triggered */
    /* default read low-water  mark is 0. */
    /* default read high-water mark is unlimited. */

    /* If the underlying data received over 20, remove the READ event from base */
    bufferevent_setwatermark(p_event, EV_READ, 10, 20);

    event_base_dispatch(p_base);

    return 0;
}
Example #25
0
/* Callback: Invoked when we are done resolving (or failing to resolve) the
 * hostname */
static void
dns_reply_callback(int result, char type, int count, int ttl, void *addresses,
                   void *arg)
{
    struct resolveinfo *info = arg;
    struct sockaddr_in sin;
    struct sockaddr_in6 sin6;
    struct sockaddr *sa = NULL;
    int socklen;

    EVUTIL_ASSERT(info->bev);
    BEV_LOCK(info->bev);

    if (result != DNS_ERR_NONE || count == 0) {
        _bufferevent_run_eventcb(info->bev, BEV_EVENT_ERROR);
        _bufferevent_decref_and_unlock(info->bev);
        memset(info, 0, sizeof(*info));
        mm_free(info);
        return;
    }

    if (type == DNS_IPv4_A) {
        EVUTIL_ASSERT(info->family == AF_INET);
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        sin.sin_port = info->port;
        /* XXX handle multiple addresses better */
        sin.sin_addr.s_addr = *(ev_uint32_t*)addresses;
        sa = (struct sockaddr*)&sin;
        socklen = sizeof(sin);
    } else if (type == DNS_IPv6_AAAA) {
        EVUTIL_ASSERT(info->family == AF_INET6);
        memset(&sin6, 0, sizeof(sin6));
        sin6.sin6_family = AF_INET;
        sin6.sin6_port = info->port;
        /* XXX handle multiple addresses better */
        memcpy(sin6.sin6_addr.s6_addr, addresses, 16);
        sa = (struct sockaddr*)&sin6;
        socklen = sizeof(sin6);
    } else {
        EVUTIL_ASSERT(info->family == AF_INET ||
                      info->family == AF_INET6);
        return; /* unreachable */
    }

    bufferevent_socket_connect(info->bev, sa, socklen);
    _bufferevent_decref_and_unlock(info->bev);
    memset(info, 0, sizeof(*info));
    mm_free(info);
}
Example #26
0
/* Open a client socket to connect to localhost on sin */
static void
start_client(struct event_base *base)
{
	struct bufferevent *bev = bufferevent_socket_new(base, -1,
                                                         BEV_OPT_CLOSE_ON_FREE);
	bufferevent_setcb(bev, client_read_cb, NULL, client_event_cb, NULL);

	if (bufferevent_socket_connect(bev, (struct sockaddr *)&saddr,
                                       sizeof(saddr)) < 0) {
		my_perror("Could not connect!");
		bufferevent_free(bev);
		exit(2);
	}
}
Example #27
0
static struct bufferevent* 
connect_to_proposer(struct event_base* b, struct sockaddr* addr)
{
	struct bufferevent* bev;
	
	bev = bufferevent_socket_new(b, -1, BEV_OPT_CLOSE_ON_FREE);
	bufferevent_setcb(bev, NULL, NULL, event_callback, NULL);
	if (bufferevent_socket_connect(bev, addr, sizeof(struct sockaddr)) < 0) {
		bufferevent_free(bev);
		return NULL;
	}
	event_base_dispatch(b);
	return bev;
}
int
main ()
{
    int sockfd;
    struct bufferevent *p_event;
    struct sockaddr_in addr;

    ff = fopen("/tmp/log", "w");
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);

    if (inet_pton(AF_INET, SVRADDR, &addr.sin_addr) <= 0) {
        printf("inet_pton");
        exit(1);
    }

    if ((p_base = event_base_new()) == NULL) {
        printf("event_base_new ");
        return 1;
    }

    /* we do not need invoke socket function to create socket */
    if ((p_event = bufferevent_socket_new(p_base, -1, BEV_OPT_CLOSE_ON_FREE)) == NULL) {
        printf("bufferevent_socket_new ");
        return 1;
    }

    /* client actually connecte to server at this time. */
    if ((sockfd = bufferevent_socket_connect(p_event, (struct sockaddr *) &addr,
                                             sizeof(addr))) < 0) {
        printf("bufferevent_socket_connect ");
        return 1;
    }

    /* EV_WRITE is enbaled by default, so the underlying evbuffer writecb will be called when dispatch.
     * evbuffer writecb FOUND that there is no data to be sent, return.
     * evbuffer writecb is not persisted. (If persisted, evbuffer writecb will be called again and agian, see event_write
     * So there is no pending event in base, base will exit.
     */
    bufferevent_setcb(p_event, NULL, event_output, buff_ev_cb, p_base);

    /* make it callback called */
    bufferevent_write (p_event, "nisssssssssdssssssssa", 20);

//    event_base_loop(p_base, EVLOOP_NO_EXIT_ON_EMPTY);
    event_base_dispatch (p_base);

    return 0;
}
Example #29
0
static void
accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
    struct sockaddr *a, int slen, void *p)
{
	struct bufferevent *b_out, *b_in;
	/* Create two linked bufferevent objects: one to connect, one for the
	 * new connection */
	b_in = bufferevent_socket_new(base, fd,
	    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);

	if (!ssl_ctx || use_wrapper)
		b_out = bufferevent_socket_new(base, -1,
		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
	else {
		SSL *ssl = SSL_new(ssl_ctx);
		b_out = bufferevent_openssl_socket_new(base, -1, ssl,
		    BUFFEREVENT_SSL_CONNECTING,
		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
	}

	assert(b_in && b_out);

	if (bufferevent_socket_connect(b_out,
		(struct sockaddr*)&connect_to_addr, connect_to_addrlen)<0) {
		perror("bufferevent_socket_connect");
		bufferevent_free(b_out);
		bufferevent_free(b_in);
		return;
	}

	if (ssl_ctx && use_wrapper) {
		struct bufferevent *b_ssl;
		SSL *ssl = SSL_new(ssl_ctx);
		b_ssl = bufferevent_openssl_filter_new(base,
		    b_out, ssl, BUFFEREVENT_SSL_CONNECTING,
		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
		if (!b_ssl) {
			perror("Bufferevent_openssl_new");
			bufferevent_free(b_out);
			bufferevent_free(b_in);
		}
		b_out = b_ssl;
	}

	bufferevent_setcb(b_in, readcb, NULL, eventcb, b_out);
	bufferevent_setcb(b_out, readcb, NULL, eventcb, b_in);

	bufferevent_enable(b_in, EV_READ|EV_WRITE);
	bufferevent_enable(b_out, EV_READ|EV_WRITE);
}
Example #30
0
File: net.c Project: libbtc/libbtc
btc_bool btc_node_group_connect_next_nodes(btc_node_group *group)
{
    btc_bool connected_at_least_to_one_node = false;
    int connect_amount = group->desired_amount_connected_nodes - btc_node_group_amount_of_connected_nodes(group);
    if (connect_amount <= 0)
        return true;

    /* search for a potential node that has not errored and is not connected or in connecting state */
    for (size_t i = 0; i < group->nodes->len; i++)
    {
        btc_node *node = vector_idx(group->nodes, i);
        if (
            !((node->state & NODE_CONNECTED) == NODE_CONNECTED)
            &&
            !((node->state & NODE_CONNECTING) == NODE_CONNECTING)
            &&
            !((node->state & NODE_ERRORED) == NODE_ERRORED)
        )
        {
            /* setup buffer event */
            node->event_bev = bufferevent_socket_new(group->event_base, -1, BEV_OPT_CLOSE_ON_FREE);
            bufferevent_setcb(node->event_bev, read_cb, write_cb, event_cb, node);
            bufferevent_enable(node->event_bev, EV_READ|EV_WRITE);
            if (bufferevent_socket_connect(node->event_bev, (struct sockaddr *)&node->addr, sizeof(node->addr)) < 0)
            {
                /* Error starting connection */
                if (node->event_bev)
                    bufferevent_free(node->event_bev);
                return false;
            }

            /* setup periodic timer */
            node->time_started_con = time(NULL);
            struct timeval tv;
            tv.tv_sec = BTC_PERIODICAL_NODE_TIMER_S;
            tv.tv_usec = 0;
            node->timer_event = event_new(group->event_base, 0, EV_TIMEOUT|EV_PERSIST, node_periodical_timer,
                                          (void*)node);
            event_add(node->timer_event, &tv);
            node->state |= NODE_CONNECTING;
            connected_at_least_to_one_node = true;
            connect_amount--;
            if (connect_amount <= 0)
                return true;
        }
    }
    /* node group misses a node to connect to */
    return connected_at_least_to_one_node;
}