void grok_program_add_input_process(grok_program_t *gprog,
                                    grok_input_t *ginput) {
  struct bufferevent *bev;
  grok_input_process_t *gipt = &(ginput->source.process);
  int childin[2], childout[2], childerr[2];
  int pid;
  struct timeval now = { 0, 0 };

  safe_pipe(childin);
  safe_pipe(childout);
  safe_pipe(childerr);

  gipt->p_stdin = childin[1];
  gipt->p_stdout = childout[0];
  gipt->p_stderr = childerr[0];
  gipt->c_stdin = childin[0];
  gipt->c_stdout = childout[1];
  gipt->c_stderr = childerr[1];

  bev = bufferevent_new(gipt->p_stdout, _program_process_stdout_read,
                        NULL, _program_process_buferror, ginput);
  bufferevent_enable(bev, EV_READ);
  ginput->bev = bev;

  if (gipt->read_stderr) {
    /* store this somewhere */
    bev = bufferevent_new(gipt->p_stderr, _program_process_stdout_read,
                          NULL, _program_process_buferror, ginput);
    bufferevent_enable(bev, EV_READ);
  }

  grok_log(ginput, LOG_PROGRAMINPUT, "Scheduling start of: %s", gipt->cmd);
  event_once(-1, EV_TIMEOUT, _program_process_start, ginput, &now);
}
Пример #2
0
void accept_callback(int fd,
                     short ev,
                     void *arg)
{
  int client_fd;
  struct sockaddr_in client_addr;
  socklen_t client_len = sizeof(client_addr);
  struct client *client;

  client_fd = accept(fd,
                     (struct sockaddr *)&client_addr,
                     &client_len);
  if (client_fd < 0)
    {
      warn("Client: accept() failed");
      return;
    }

  setnonblock(client_fd);

  client = calloc(1, sizeof(*client));
  if (client == NULL)
    err(1, "malloc failed");
  client->fd = client_fd;

  client->buf_ev = bufferevent_new(client_fd,
                                   buf_read_callback,
                                   buf_write_callback,
                                   buf_error_callback,
                                   client);

  bufferevent_enable(client->buf_ev, EV_READ);
}
Пример #3
0
void
parentd(int nprocs, int *sockets)
{
    int *fdp, i, status;
    struct bufferevent *b;

    signal(SIGINT, sigint);

    gettimeofday(&ratetv, nil);
    gettimeofday(&lastreporttv, nil);
    memset(nreportbuf, 0, sizeof(nreportbuf));
    for(i=0; i<NBUFFER; i++){
        if((reportbuf[i] = calloc(params.nbuckets + num_cols, sizeof(int))) == nil)
            panic("calloc");
    }

    event_init();

    for(fdp=sockets; *fdp!=-1; fdp++){
        b = bufferevent_new(
            *fdp, chldreadcb, nil,
            chlderrcb,(void *)&nprocs);
        bufferevent_enable(b, EV_READ);
    }

    event_dispatch();

    for(i=0; i<nprocs; i++)
        waitpid(0, &status, 0);

    report();
}
Пример #4
0
/* LUA: new(fd, read, write, error)
	Pushes a new bufferevent instance on the stack
	Accepts: base, fd, read, write, error cb
	Requires base, fd and error cb
*/
static int buffer_event_push(lua_State* L) {
	le_bufferevent *ev;
	le_base* base = event_base_get(L, 1);
	/* NOTE: Should probably reference the socket as well... */
	int fd = getSocketFd(L, 2);
	luaL_checktype(L, 5, LUA_TFUNCTION);
	if(!lua_isnil(L, 3)) luaL_checktype(L, 3, LUA_TFUNCTION);
	if(!lua_isnil(L, 4)) luaL_checktype(L, 4, LUA_TFUNCTION);
	ev= (le_bufferevent*)lua_newuserdata(L, sizeof(le_bufferevent));
	luaL_getmetatable(L, BUFFER_EVENT_MT);
	lua_setmetatable(L, -2);
	ev->ev = bufferevent_new(fd, buffer_event_readcb, buffer_event_writecb, buffer_event_errorcb, ev);
	lua_createtable(L, 5, 0);
	lua_pushvalue(L, 3);
	lua_rawseti(L, -2, 1); // Read
	lua_pushvalue(L, 4);
	lua_rawseti(L, -2, 2); // Write
	lua_pushvalue(L, 5);
	lua_rawseti(L, -2, 3); // Err

	event_buffer_push(L, ev->ev->input);
	lua_rawseti(L, -2, READ_BUFFER_LOCATION);
	event_buffer_push(L, ev->ev->output);
	lua_rawseti(L, -2, WRITE_BUFFER_LOCATION);
	lua_setfenv(L, -2);
	ev->base = base;
	return 1;
}
Пример #5
0
int
tty_open(struct tty *tty, const char *overrides, char **cause)
{
	char	out[64];
	int	fd;

	if (debug_level > 3) {
		xsnprintf(out, sizeof out, "tmux-out-%ld.log", (long) getpid());
		fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644);
		if (fd != -1 && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
			fatal("fcntl failed");
		tty->log_fd = fd;
	}

	tty->term = tty_term_find(tty->termname, tty->fd, overrides, cause);
	if (tty->term == NULL) {
		tty_close(tty);
		return (-1);
	}
	tty->flags |= TTY_OPENED;

	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_ESCAPE);

	tty->event = bufferevent_new(
	    tty->fd, tty_read_callback, NULL, tty_error_callback, tty);

	tty_start_tty(tty);

	tty_keys_init(tty);

	return (0);
}
Пример #6
0
struct StreamRequest *new_stream_request(const char *method, const char *source_address, int source_port, const char *path,
        void (*header_cb)(struct bufferevent *bev, struct evkeyvalq *headers, void *arg),
        void (*read_cb)(struct bufferevent *bev, void *arg),
        void (*error_cb)(struct bufferevent *bev, void *arg),
        void *arg) {
    struct StreamRequest *sr;
    int fd;
    struct evbuffer *http_request;
    
    fd = stream_request_connect(source_address, source_port);
    if (fd == -1) {
        return NULL;
    }
    
    sr = malloc(sizeof(struct StreamRequest));
    sr->fd = fd;
    sr->state = read_firstline;
    sr->header_cb = header_cb;
    sr->read_cb = read_cb;
    sr->error_cb = error_cb;
    sr->arg = arg;
    sr->bev = bufferevent_new(sr->fd, stream_request_readcb, stream_request_writecb, stream_request_errorcb, sr);
    http_request = evbuffer_new();
    evbuffer_add_printf(http_request, "%s %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", method, path, source_address);
    bufferevent_write(sr->bev, (char *)EVBUFFER_DATA(http_request), EVBUFFER_LENGTH(http_request));
    evbuffer_free(http_request);
    
    return sr;
}
Пример #7
0
void accept_callback(int fd, short ev, void *arg)
{
	int client_fd;
	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	struct client *client;

	printf("call accept_callback\n");

	client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
	if (client_fd < 0) {
		printf("warn: client: accept() failed\n");
		return;
	}

	set_non_block(client_fd);

	client = (struct client*)calloc(1, sizeof(*client));
	if (client == NULL) {
		printf("error: malloc failed\n");
	}
	client->fd = client_fd;
	client->buf_ev = bufferevent_new(client_fd,
			buf_read_callback,
			buf_write_callback,
			buf_error_callback,
			client);

	// Enable a bufferevent.
	// @param event any combination of EV_READ | EV_WRITE.
	bufferevent_enable(client->buf_ev, EV_READ);
}
Пример #8
0
static void
test_bufferevent_watermarks_impl(int use_pair)
{
	struct bufferevent *bev1 = NULL, *bev2 = NULL;
	char buffer[65000];
	int i;
	test_ok = 0;

	if (use_pair) {
		struct bufferevent *pair[2];
		tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
		bev1 = pair[0];
		bev2 = pair[1];
		bufferevent_setcb(bev1, NULL, wm_writecb, errorcb, NULL);
		bufferevent_setcb(bev2, wm_readcb, NULL, errorcb, NULL);
	} else {
		bev1 = bufferevent_new(pair[0], NULL, wm_writecb, wm_errorcb, NULL);
		bev2 = bufferevent_new(pair[1], wm_readcb, NULL, wm_errorcb, NULL);
	}
	bufferevent_disable(bev1, EV_READ);
	bufferevent_enable(bev2, EV_READ);

	for (i = 0; i < sizeof(buffer); i++)
		buffer[i] = (char)i;

	/* limit the reading on the receiving bufferevent */
	bufferevent_setwatermark(bev2, EV_READ, 10, 20);

        /* Tell the sending bufferevent not to notify us till it's down to
           100 bytes. */
        bufferevent_setwatermark(bev1, EV_WRITE, 100, 2000);

	bufferevent_write(bev1, buffer, sizeof(buffer));

	event_dispatch();

	tt_int_op(test_ok, ==, 2);

        /* The write callback drained all the data from outbuf, so we
         * should have removed the write event... */
        tt_assert(!event_pending(&bev2->ev_write, EV_WRITE, NULL));

end:
	bufferevent_free(bev1);
	bufferevent_free(bev2);
}
void on_accept(int fd, short ev, void *arg) {
	int client_fd;
	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	workqueue_t *workqueue = (workqueue_t *)arg;
	client_t *client;
	job_t *job;

	client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
	if (client_fd < 0) {
		warn("accept failed");
		return;
	}

	if (setnonblock(client_fd) < 0) {
		warn("failed to set client socket to non-blocking");
		close(client_fd);
		return;
	}

	if ((client = malloc(sizeof(*client))) == NULL) {
		warn("failed to allocate memory for client state");
		close(client_fd);
		return;
	}
	memset(client, 0, sizeof(*client));
	client->fd = client_fd;

	if ((client->output_buffer = evbuffer_new()) == NULL) {
		warn("client output buffer allocation failed");
		closeAndFreeClient(client);
		return;
	}

	if ((client->evbase = event_base_new()) == NULL) {
		warn("client event_base creation failed");
		closeAndFreeClient(client);
		return;
	}

	if ((client->buf_ev = bufferevent_new(client_fd, buffered_on_read, buffered_on_write, buffered_on_error, client)) == NULL) {
		warn("client bufferevent creation failed");
		closeAndFreeClient(client);
		return;
	}
	bufferevent_base_set(client->evbase, client->buf_ev);
	bufferevent_enable(client->buf_ev, EV_READ);

	if ((job = malloc(sizeof(*job))) == NULL) {
		warn("failed to allocate memory for job state");
		closeAndFreeClient(client);
		return;
	}
	job->job_function = server_job_function;
	job->user_data = client;

	workqueue_add_job(workqueue, job);
}
Пример #10
0
static void maxconns_handler(const int fd, const short which, void *arg) {
    struct timeval t = {.tv_sec = 0, .tv_usec = 10000};

    if (fd == -42 || allow_new_conns == false) {
        /* reschedule in 10ms if we need to keep polling */
        evtimer_set(&maxconnsevent, maxconns_handler, 0);
        event_base_set(main_base, &maxconnsevent);
        evtimer_add(&maxconnsevent, &t);
    } else {
        evtimer_del(&maxconnsevent);
        accept_new_conns(true);
    }
}

static bool update_event(conn *c, const int new_flags) {
    assert(c != NULL);

    
    if (c->ev_flags == new_flags)
        return true;
    pthread_t tid = pthread_self();
    if (tid == dispatcher_thread.thread_id)
    {
        struct event_base *base = c->event.ev_base;
        if (event_del(&c->event) == -1) return false;    
        event_set(&c->event, c->sfd, new_flags, master_event_handler, (void *)c);
        event_base_set(base, &c->event);
        c->ev_flags = new_flags;
        if (event_add(&c->event, 0) == -1) return false;
        return true;
    }else{
        struct event_base *base = bufferevent_get_base(c->buf_ev);
        bufferevent_free(c->buf_ev);
        c->buf_ev = bufferevent_new(c->sfd, event_handler, buf_write_callback, buf_error_callback, (void * )c);
        bufferevent_base_set(base, c->buf_ev);
        
        c->ev_flags = new_flags;
        if (bufferevent_enable(c->buf_ev, new_flags) == -1) return false;
        return true;
    }    
    //这个也得改成bufferevent的形式
/*

    event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
    event_base_set(base, &c->event);
    event_add(&c->event, 0);


    c->buf_ev = bufferevent_new(c->sfd, event_handler, event_handler, NULL, (void * )c);
    bufferevent_base_set(base, c->buf_ev);
    bufferevent_enable(c->buf_ev, new_flags);

    c->ev_flags = new_flags;
    if (event_add(&c->event, 0) == -1) return false;
    return true;
*/
}
Пример #11
0
void ReactorAccept(int listenFd, short listenEv, void * arg)
{
    NetReactor * nrc = (NetReactor *)arg;
    if(nrc->isStop())
    {
        event lis = nrc->getListenEv();
        event_del(&lis);
        Log::NOTICE("SVR is STOP, don not accept");
        return;
    }

    struct sockaddr sa;
    socklen_t slen = sizeof(sa);
    int connfd = net_accept(listenFd, &sa, &slen);

    struct bufferevent ** pool;
    pool = nrc->getFdPool();
    int maxConnected = nrc->getMaxConnected(); 
    in_addr ipaddr = ((struct sockaddr_in *)&sa)->sin_addr;
    char *peer_ip = inet_ntoa(ipaddr);

    if(connfd > maxConnected)
    {
        Log::ERROR("Too much user, connfd : %d", connfd);
        close(connfd);
        return;
    }
   
    NetConnManager * cMag = NetConnManager::getInstance();  

    if(cMag->IsUserConnExist(connfd))
    {
        Log::ERROR("assign a working fd, connfd : %d, will clean it", 
                   connfd);
    }

    struct bufferevent * bev;
    set_fd_noblock(connfd);
    bev = bufferevent_new(connfd, 
                          EvReadCallback, 
                          NULL, 
                          EvErrorCallback, 
                          nrc);
    bev->timeout_read = nrc->getReadTo();
    bev->timeout_write = nrc->getWriteTo();
    bufferevent_enable(bev, EV_READ|EV_WRITE);    


    std::unique_ptr<Iconn> con(new UserConn(nrc, bev)); 
    cMag->setConn(connfd, std::move(con));

    /* use for test */
    //cMag->addAppConnFd(connfd); 

    Log::NOTICE("ACCEPT Connect SUCC, connfd : %d, UserIP : %s", connfd, peer_ip); 
}
Пример #12
0
conn *conn_new(const int sfd, enum conn_states init_state,
                const int event_flags,
                const int read_buffer_size, enum network_transport transport,
                struct event_base *base) {
    /*此函数需要做的事情
        1.新建一个conn结构,加入到connQ
        2.为此链接(文件描述符),注册一个event_handler
        3.event_handler进行状态的处理,不同状态不同的处理方式,master,slave共用此方法。
    */
    conn * new_c;
    new_c = conns[sfd];
    if (NULL == new_c)
    {
        if ( !(new_c = (conn *)calloc(1, sizeof(conn))) )
        {
            perror("alloc conn fail");
            exit(1);
        }

        new_c->sfd = sfd;
        conns[sfd] = new_c;
    }

    new_c->state = init_state;
    //以上是连接的初始化,接下来是连接的事件注册
    
     pthread_t tid = pthread_self();
     if (tid == dispatcher_thread.thread_id)
     {
        event_set(&new_c->event, sfd, event_flags, master_event_handler, (void*)new_c);
        event_base_set(base, &new_c->event);
        event_add(&new_c->event, 0);
     }else{
        new_c->buf_ev = bufferevent_new(sfd, event_handler, event_handler, buf_error_callback, (void *)new_c);
        bufferevent_base_set(base, new_c->buf_ev);
        bufferevent_enable(new_c->buf_ev, event_flags);
     }
     
     
     /*
     想着想着还是决定改成用bufferevent。
     因为master线程与slave用的是同一个函数来做处理event_handler -> drive_machine,
     所以master线程的accept也需要改为用bufferevent,而且event_handler以及drive_machine也得改
     还有struct conn的event也得改呀,得改成bufferevent类型呢

     */

     /*
    new_c->buf_ev = bufferevent_new(sfd, event_handler, event_handler, buf_error_callback, (void *)new_c);
    bufferevent_base_set(base, new_c->buf_ev);
    bufferevent_enable(new_c->buf_ev, event_flags);
    */
    
    return new_c;
}
Пример #13
0
struct bufferevent* red_connect_relay2(struct sockaddr_in *addr, evbuffercb writecb, everrorcb errorcb, void *cbarg, const struct timeval *timeout_write)
{
	struct bufferevent *retval = NULL;
	int on = 1;
	int relay_fd = -1;
	int error;

	relay_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (relay_fd == -1) {
		log_errno(LOG_ERR, "socket");
		goto fail;
	}

	error = fcntl_nonblock(relay_fd);
	if (error) {
		log_errno(LOG_ERR, "fcntl");
		goto fail;
	}

	error = setsockopt(relay_fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
	if (error) {
		log_errno(LOG_WARNING, "setsockopt");
		goto fail;
	}

	error = connect(relay_fd, (struct sockaddr*)addr, sizeof(*addr));
	if (error && errno != EINPROGRESS) {
		log_errno(LOG_NOTICE, "connect");
		goto fail;
	}

	retval = bufferevent_new(relay_fd, NULL, writecb, errorcb, cbarg);
	if (!retval) {
		log_errno(LOG_ERR, "bufferevent_new");
		goto fail;
	}

	bufferevent_set_timeouts(retval, NULL, timeout_write);

	error = bufferevent_enable(retval, EV_WRITE); // we wait for connection...
	if (error) {
		log_errno(LOG_ERR, "bufferevent_enable");
		goto fail;
	}

	return retval;

fail:
	if (relay_fd != -1)
		redsocks_close(relay_fd);
	if (retval)
		bufferevent_free(retval);
	return NULL;
}
Пример #14
0
/**
 * This function will be called by libevent when there is a connection
 * ready to be accepted.
 */
void on_accept(int fd, short ev, void *arg)
{
    int client_fd;
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    struct client *client;

    client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
    if (client_fd < 0) {
        warn("accept failed");
        return;
    }

    /* Set the client socket to non-blocking mode. */
    if (setnonblock(client_fd) < 0)
        warn("failed to set client socket non-blocking");

    /* We've accepted a new client, create a client object. */
    client = calloc(1, sizeof(*client));
    if (client == NULL)
        err(1, "malloc failed");
    client->fd = client_fd;

    /* Create the buffered event.
     *
     * The first argument is the file descriptor that will trigger
     * the events, in this case the clients socket.
     *
     * The second argument is the callback that will be called
     * when data has been read from the socket and is available to
     * the application.
     *
     * The third argument is a callback to a function that will be
     * called when the write buffer has reached a low watermark.
     * That usually means that when the write buffer is 0 length,
     * this callback will be called.  It must be defined, but you
     * don't actually have to do anything in this callback.
     *
     * The fourth argument is a callback that will be called when
     * there is a socket error.  This is where you will detect
     * that the client disconnected or other socket errors.
     *
     * The fifth and final argument is to store an argument in
     * that will be passed to the callbacks.  We store the client
     * object here.
     */
    client->buf_ev = bufferevent_new(client_fd, buffered_on_read, buffered_on_write, buffered_on_error, client);

    /* We have to enable it before our callbacks will be
     * called. */
    bufferevent_enable(client->buf_ev, EV_READ);

    printf("Accepted connection from %s\n", inet_ntoa(client_addr.sin_addr));
}
Пример #15
0
// wait for websocket connections
void listener_accept ( int fd, short type, void* arg ) {
  struct sockaddr_in raddr;
  int raddrlen = sizeof raddr;
  int sock = accept ( fd, (struct sockaddr*)&raddr, &raddrlen );
  if ( sock != -1 ) {
    struct bufferevent* client = bufferevent_new ( sock,
					      client_read_ws_handshake,
					      NULL,
					      be_error, NULL );
    bufferevent_enable ( client, EV_READ|EV_WRITE );
  }
}
Пример #16
0
static void
http_base_test(void)
{
	struct bufferevent *bev;
	int fd;
	const char *http_request;
	short port = -1;

	test_ok = 0;
	fprintf(stdout, "Testing HTTP Server Event Base: ");

	base = event_init();

	/* 
	 * create another bogus base - which is being used by all subsequen
	 * tests - yuck!
	 */
	event_init();

	http = http_setup(&port, base);
	
	fd = http_connect("127.0.0.1", port);

	/* Stupid thing to send a request */
	bev = bufferevent_new(fd, http_readcb, http_writecb,
	    http_errorcb, NULL);
	bufferevent_base_set(base, bev);

	http_request =
	    "GET /test HTTP/1.1\r\n"
	    "Host: somehost\r\n"
	    "Connection: close\r\n"
	    "\r\n";

	bufferevent_write(bev, http_request, strlen(http_request));
	
	event_base_dispatch(base);

	bufferevent_free(bev);
	EVUTIL_CLOSESOCKET(fd);

	evhttp_free(http);

	event_base_free(base);
	base = NULL;
	
	if (test_ok != 2) {
		fprintf(stdout, "FAILED\n");
		exit(1);
	}
	
	fprintf(stdout, "OK\n");
}
Пример #17
0
static void
network_listen_callback(int listen_fd, short events, void *arg)
{
    int fd = KSOCK_svr_accept(listen_fd);
    struct bufferevent *bufev;

    printf("fd %d conn...\n", fd);

    bufev = bufferevent_new(fd, network_read_callback,
                            NULL, network_error_callback, (void *)fd);
    bufferevent_enable(bufev, EV_READ);
}
Пример #18
0
/*
 * Create a new bufferevent for a socket and register it with the provided
 * base.  Note that options is always ignored, so programs using this backward
 * compatibility layer cannot rely on it.
 */
struct bufferevent *
bufferevent_socket_new(struct event_base *base, evutil_socket_t fd,
                       int options UNUSED)
{
    struct bufferevent *bev;

    bev = bufferevent_new(fd, NULL, NULL, NULL, NULL);
    if (bufferevent_base_set(base, bev) < 0) {
        bufferevent_free(bev);
        return NULL;
    }
    return bev;
}
Пример #19
0
static void
test_bufferevent_impl(int use_pair)
{
	struct bufferevent *bev1 = NULL, *bev2 = NULL;
	char buffer[8333];
	int i;

	if (use_pair) {
		struct bufferevent *pair[2];
		tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
		bev1 = pair[0];
		bev2 = pair[1];
		bufferevent_setcb(bev1, readcb, writecb, errorcb, NULL);
		bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
	} else {
		bev1 = bufferevent_new(pair[0], readcb, writecb, errorcb, NULL);
		bev2 = bufferevent_new(pair[1], readcb, writecb, errorcb, NULL);
	}

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

	for (i = 0; i < sizeof(buffer); i++)
		buffer[i] = i;

	bufferevent_write(bev1, buffer, sizeof(buffer));

	event_dispatch();

	bufferevent_free(bev1);
	bufferevent_free(bev2);

	if (test_ok != 2)
		test_ok = 0;
end:
	;
}
Пример #20
0
static struct DSClient *new_domain_socket_client(struct DomainSocket *uds,
    int client_fd, struct sockaddr *sa, socklen_t salen)
{
    struct DSClient *client;
    
    client = malloc(sizeof(struct DSClient));
    client->uds = uds;
    client->fd = client_fd;
    client->bev = bufferevent_new(client_fd, buffered_on_read, buffered_on_write, buffered_on_error, client);
    bufferevent_enable(client->bev, EV_READ);
    
    _DEBUG("%s: %d\n", __FUNCTION__, client->fd);
    
    return client;
}
Пример #21
0
int main() {
  struct event ev;
  struct bufferevent *bev;
  int fd;
  fd = open("/var/log/messages", O_RDONLY);

  event_init();
  bev = bufferevent_new(fd, fileread, NULL, NULL, NULL);
  bufferevent_enable(bev, EV_READ);
  //event_set(&ev, 0, EV_READ | EV_PERSIST, fileread, NULL);
  //event_add(&ev, NULL);
  event_dispatch();

  return 0;
}
Пример #22
0
struct bufferevent* red_connect_relay(struct sockaddr_in *addr, evbuffercb writecb, everrorcb errorcb, void *cbarg)
{
	struct bufferevent *retval = NULL;
	int relay_fd = -1;
	int error;

	relay_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (relay_fd == -1) {
		log_errno(LOG_ERR, "socket");
		goto fail;
	}

	error = fcntl_nonblock(relay_fd);
	if (error) {
		log_errno(LOG_ERR, "fcntl");
		goto fail;
	}

	if (apply_tcp_keepalive(relay_fd))
		goto fail;

	error = connect(relay_fd, (struct sockaddr*)addr, sizeof(*addr));
	if (error && errno != EINPROGRESS) {
		log_errno(LOG_NOTICE, "connect");
		goto fail;
	}

	retval = bufferevent_new(relay_fd, NULL, writecb, errorcb, cbarg);
	if (!retval) {
		log_errno(LOG_ERR, "bufferevent_new");
		goto fail;
	}

	error = bufferevent_enable(retval, EV_WRITE); // we wait for connection...
	if (error) {
		log_errno(LOG_ERR, "bufferevent_enable");
		goto fail;
	}

	return retval;

fail:
	if (relay_fd != -1)
		redsocks_close(relay_fd);
	if (retval)
		bufferevent_free(retval);
	return NULL;
}
Пример #23
0
/**
 * handle the case of an accept on the gopher server socket
 */
static void on_accept(int fd, short event, void *arg) {
    int client_fd;
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(struct sockaddr_in);
    client_t *client = NULL;

    DEBUG("Incoming connection...");

    client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
    if(client_fd == -1) {
        ERROR("Accept failed: %s", strerror(errno));
        return;
    }

    DEBUG("Accepted connection on fd %d", client_fd);

    if(setnonblock(client_fd) < 0) {
        ERROR("Can't set client socket nonblocking.  Terminating");
        shutdown(client_fd, SHUT_RDWR);
        close(client_fd);
        return;
    }

    client = (client_t *)calloc(1, sizeof(client_t));
    if(!client) {
        ERROR("Malloc error in on_accept");
        shutdown(client_fd, SHUT_RDWR);
        close(client_fd);
        return;
    }

    /* set up read/write events */
    client->fd = client_fd;
    client->buf_ev = bufferevent_new(client_fd, on_buf_read,
                                     on_buf_write, on_buf_error, (void*)client);
    client->state = CLIENT_STATE_WAITING_REQUEST;

    client->request = (char*)calloc(1, MAX_REQUEST_SIZE);
    if(!client->request) {
        ERROR("Malloc error in on_accept");
        shutdown(client_fd, SHUT_RDWR);
        close(client_fd);
        free(client);
        return;
    }

    bufferevent_enable(client->buf_ev, EV_READ);
}
Пример #24
0
static int client_process_delete(Client * const client)
{
    char *store_file;
    char *store_file_pnt;
    size_t sizeof_store_file;

    logfile(LOG_DEBUG, _("client_process_delete, fd #%d"), client->client_fd);
    if (client->offset_read_buf < (size_t) 6U) {
        return -1;
    }
    sizeof_store_file = (sizeof "/") - (size_t) 1U +
        client->key_len + (size_t) 1U;
    if ((store_file = ALLOCA(sizeof_store_file)) == NULL) {
        logfile(LOG_WARNING, _("Out of stack for ALLOCA"));
        return -1;
    }
    store_file_pnt = store_file;
    *store_file_pnt++ = '/';
    if (validate_key(client->read_buf + (size_t) 5U, client->key_len) != 0) {
        ALLOCA_FREE(store_file);
        logfile(LOG_WARNING, _("Invalid key name"));
        return -1;
    }
    memcpy(store_file_pnt, client->read_buf + (size_t) 5U, client->key_len);
    store_file_pnt += client->key_len;
    *store_file_pnt = 0;
    logfile(LOG_DEBUG, _("Deleting [%s]"), store_file);
    if (unlink(store_file) != 0) {
        logfile(LOG_INFO, _("Unable to delete [%s]: [%s]"), store_file,
                strerror(errno));
        ALLOCA_FREE(store_file);
        return -1;
    }
    if ((client->returncode_bufev =
         bufferevent_new(client->client_fd,
                         returncode_bufferev_read_cb,
                         returncode_bufferev_write_cb,
                         returncode_bufferev_error_cb,
                         client)) == NULL) {
        logfile(LOG_WARNING, _("Unable to create a bufferevent for fd #%d"),
                client->client_fd);
    }
    (void) bufferevent_write(client->returncode_bufev, (void *) RETURNCODE_OK,
                             sizeof RETURNCODE_OK - (size_t) 1U);

    return 0;
}
Пример #25
0
/* Initialise as a control client. */
void
control_start(struct client *c)
{
	/* Enable reading from stdin. */
	if (c->stdin_event != NULL)
		bufferevent_free(c->stdin_event);
	c->stdin_event = bufferevent_new(c->stdin_fd,
					 control_read_callback,
					 NULL,
					 control_error_callback, c);
	if (c->stdin_event == NULL)
		fatalx("failed to create stdin event");
	bufferevent_enable(c->stdin_event, EV_READ);

	/* Write the protocol identifier and version. */
	bufferevent_enable(c->stdout_event, EV_WRITE);
}
void grok_program_add_input_file(grok_program_t *gprog,
                                 grok_input_t *ginput) {
  struct bufferevent *bev;
  struct stat st;
  int ret;
  int pipefd[2];
  grok_input_file_t *gift = &(ginput->source.file);
  grok_log(ginput, LOG_PROGRAMINPUT, "Adding file input: %s", gift->filename);

  ret = stat(gift->filename, &st);
  if (ret == -1) {
    grok_log(gprog, LOG_PROGRAMINPUT , "Failure stat(2)'ing file: %s",
             gift->filename);
    grok_log(gprog, LOG_PROGRAMINPUT , "strerror(%d): %s", strerror(errno));
    return;
  }
  gift->fd = open(gift->filename, O_RDONLY);

  if (gift->fd < 0) {
    grok_log(gprog, LOG_PROGRAM, "Failure open(2)'ing file for read '%s': %s",
             gift->filename, strerror(errno));
    return;
  }

  safe_pipe(pipefd);
  gift->offset = 0;
  gift->reader = pipefd[0];
  gift->writer = pipefd[1];
  memcpy(&(gift->st), &st, sizeof(st));
  gift->waittime.tv_sec = 0;
  gift->waittime.tv_usec = 0;
  gift->readbuffer = malloc(st.st_blksize);

  grok_log(ginput, LOG_PROGRAMINPUT, "dup2(%d, %d)", gift->fd, gift->writer);

  /* Tie our open file read fd to the writer of our pipe */
  // this doesn't work

  bev = bufferevent_new(gift->reader, _program_file_read_buffer,
                        NULL, _program_file_buferror, ginput);
  bufferevent_enable(bev, EV_READ);
  ginput->bev = bev;
  event_once(-1, EV_TIMEOUT, _program_file_read_real, ginput,
             &(gift->waittime));
}
Пример #27
0
static void
http_multi_line_header_test(void)
{
	struct bufferevent *bev;
	int fd;
	const char *http_start_request;
	short port = -1;
	
	test_ok = 0;
	fprintf(stdout, "Testing HTTP Server with multi line: ");

	http = http_setup(&port, NULL);
	
	fd = http_connect("127.0.0.1", port);

	/* Stupid thing to send a request */
	bev = bufferevent_new(fd, http_readcb, http_writecb,
	    http_errorcb, NULL);

	http_start_request =
	    "GET /test HTTP/1.1\r\n"
	    "Host: somehost\r\n"
	    "Connection: close\r\n"
	    "X-Multi:  aaaaaaaa\r\n"
	    " a\r\n"
	    "\tEND\r\n"
	    "X-Last: last\r\n"
	    "\r\n";
		
	bufferevent_write(bev, http_start_request, strlen(http_start_request));

	event_dispatch();
	
	bufferevent_free(bev);
	EVUTIL_CLOSESOCKET(fd);

	evhttp_free(http);

	if (test_ok != 4) {
		fprintf(stdout, "FAILED\n");
		exit(1);
	}
	
	fprintf(stdout, "OK\n");
}
Пример #28
0
void BeatBoard::IRCConnection::connectIRCServer(string addr, string port) throw (Exception){
  this->create_socket();

  struct addrinfo hints;
  struct addrinfo *addrinfo = NULL;
  int result = -1;

  memset(&hints, 0, sizeof(struct addrinfo));
  //hints.ai_family = AF_UNSPEC;
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = 0;
  hints.ai_protocol = 0;
  
  result = getaddrinfo(addr.c_str(),port.c_str(),&hints,&addrinfo);
  if ( 0 != result  ) {
    throw Exception( "error: invalid address" );
  }

  if ( 0 != connect( this->sock, addrinfo->ai_addr, addrinfo->ai_addrlen ) ) {
    // TODO error handling, addrinfo free
    throw Exception( "connect: failed" );
  }
  freeaddrinfo(addrinfo);

  /* add event to this connection */
  this->buffevent = bufferevent_new( this->sock,
                                     irc_buffevent_read,
                                     irc_buffevent_write,
                                     irc_buffevent_error,
                                     (void*)this );
  if ( NULL == this->buffevent ) {
    throw Exception( "bufferevent_new: failed" );
  }

  result = bufferevent_enable( this->buffevent, EV_READ | EV_WRITE );

  if ( 0 != result ) {
    throw Exception( "bufferevent_enable: failed" );
  }

  this->NICK(this->nick);
  this->USER(this->nick, "0", "*", ":beatboard");
}
Пример #29
0
void filewatch(void) {
  int fd;
  int p[2];
  struct bufferevent *bev;
  struct timeval t = { 1, 0 };

  pipe(p);

  fd = open("/var/log/messages", O_RDONLY);
  //dup2(fd, p[1]);

  bev = bufferevent_new(p[0], bufread, NULL, NULL, "fileread");
  bufferevent_enable(bev, EV_READ);

  struct evfdpipe *ep = calloc(1, sizeof(struct evfdpipe));
  ep->input = fd;
  ep->output = p[1];
  event_once(p[1], EV_TIMEOUT, fileread_real, ep, &t);
}
Пример #30
0
int main(int argc, char **argv) {
    event_init();
    struct sockaddr_in sa;
    struct bufferevent *bev;
    int fd;
    unsigned ip;
    inet_aton("213.248.62.7",&ip);
    sa.sin_addr = *((struct in_addr *) &ip);
    sa.sin_family = AF_INET;
    sa.sin_port = htons(22);
    bzero(&sa.sin_zero, 8);
    fd=socket(AF_INET, SOCK_STREAM, 0);
    setnb(fd);
    connect(fd, (struct sockaddr *) & sa, sizeof (struct sockaddr));
    bev = bufferevent_new(fd, OnBufferedRead, OnBufferedWrite, OnBufferedError, NULL);
    bufferevent_enable(bev, EV_READ);
    bufferevent_settimeout(bev,10,10);
    event_dispatch();
    return 0;
}