echod_libevent.c

意外と苦戦。ドキュメントないなー。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

#include <errno.h>

#include <event.h>

#define ECHO_PORT 7
#define MAX_BACKLOG 5
#define RCVBUFSIZE 256
#define MAX_EVENTS 1024

#define die(s) do { fprintf(stderr, "%s\n", (s)); exit(1); } while(0)
#define die_with_err(s) do { perror((s)); exit(1); } while(0)

#ifdef DEBUG
#define debug(...) do { fprintf(stderr,  __VA_ARGS__); } while(0)
#else
#define debug(...) do {} while(0)
#endif

int echo(int sock) {
  char buf[RCVBUFSIZE + 1];
  size_t len;

  debug("echo(): %d.\n", sock);

  if ((len = recv(sock, buf, RCVBUFSIZE, 0)) < 0) {
    perror("recv(2)");
    return -1;
  }

  if (len == 0) {
    return 0;
  }

  buf[len] = '\0';
  debug("recv: %s.\n", buf);

  if (send(sock, buf, len, 0) < 0) {
    perror("send(2)");
    return -1;
  }

  return len;
}

void event_client(int fd, short event, void *arg) {
  struct event *ev = arg;

  if (echo(fd) < 1) {
    close(fd);
    event_del(ev);
    free(ev);
  }
}

void event_server(int fd, short event, void *arg) {
  struct event *ev = arg;
  struct event *client_ev;
  int sock, flags;
  struct sockaddr_in addr;
  socklen_t len = sizeof(addr);

  if ((sock = accept(fd, (struct sockaddr*) &addr, &len)) < 0) {
    if (EINTR == errno) { return; }
    die_with_err("accept(2)");
  }

  debug("accepted.\n");

  if ((flags = fcntl(sock, F_GETFL, 0)) < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
    die_with_err("fcntl(2)");
  }

  client_ev = calloc(1, sizeof(struct event));
  event_set(client_ev, sock, EV_READ | EV_PERSIST, event_client, client_ev);
  event_add(client_ev, NULL);
}

int main() {
  int sock, epfd, flags;
  struct sockaddr_in addr;
  struct event ev;

  if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    die_with_err("socket(2)");
  }

  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = htons(ECHO_PORT);

  if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
    die_with_err("bind(2)");
  }

  if (listen(sock, MAX_BACKLOG) < 0) {
    die_with_err("listen(2)");
  }

  if ((flags = fcntl(sock, F_GETFL, 0)) < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
    die_with_err("fcntl(2)");
  }

  event_init();
  event_set(&ev, sock, EV_READ | EV_PERSIST, event_server, &ev);
  event_add(&ev, NULL);
  event_dispatch();

  close(sock);

  return 0;
}