add -fstack-check and hardening
[libjh.git] / netconn.c
1 #include <sys/types.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <stdbool.h>
6
7 static void connection_waiting_cb(struct ev_loop *loop, ev_io *w, int revents) {
8   bufio_connection *con = (bufio_connection *)w->data;
9   if (revents & EV_READ) {
10     assert(con->inbuf_used != con->inbuf_size);
11     int res = read(w->fd, con->inbuf+con->inbuf_used, con->inbuf_size-con->inbuf_used);
12     if (res == -1) {
13       if (errno != EAGAIN && errno != EWOULDBLOCK) {
14         con->err_cb(con);
15       }
16       return;
17     }
18     if (res == 0) {
19       con->err_cb(con);
20       return;
21     }
22     con->inbuf_used += res;
23     if (con->inbuf_size == con->inbuf_used) {
24       // The buffer is filled, so stop reading data until we have a new one.
25       ev_io_stop(loop, w);
26
27       // Call the callback AFTERWARDS (after it has finished executing, we might
28       // already have a new read buffer).
29       con->data_cb(con);
30     }
31   }
32
33   if (revents & EV_WRITE) {
34     if (bufio_chain_flush(&con->outbuf, w->fd) == 0) {
35       ev_io_stop(loop, w);
36     }
37   }
38 }
39
40 bufio_connection *bufio_connection_create(struct ev_loop *loop, int fd) {
41   bufio_connection *con = calloc(1, sizeof(*con));
42   if (con == NULL) return NULL;
43   con->loop = loop;
44   ev_io_init(&con->rw, connection_waiting_cb, fd, EV_READ);
45   ev_io_init(&con->ww, connection_waiting_cb, fd, EV_WRITE);
46   con->rw.data = con;
47   con->ww.data = con;
48   return con;
49 }
50
51 void bufio_connection_set_read_buffer(bufio_connection *con, void *buf, size_t size) {
52   assert(size > 0);
53   con->inbuf = buf;
54   con->inbuf_size = size;
55   con->inbuf_used = 0;
56
57   ev_io_start(con->loop, &con->rw);
58 }
59
60 void bufio_connection_destroy(bufio_connection *con) {
61   bufio_chain_clear(&con->outbuf);
62   ev_io_stop(con->loop, &con->rw);
63   ev_io_stop(con->loop, &con->ww);
64   free(con);
65 }
66
67 int bufio_connection_write(bufio_connection *con, void *buf, size_t len) {
68   int res;
69   bool chain_was_empty = (con->outbuf.head == NULL);
70   res = bufio_chain_append(&con->outbuf, buf, len);
71   if (res == -1) return -1;
72   if (chain_was_empty) {
73     if (bufio_chain_flush(&con->outbuf, con->ww.fd)) {
74       ev_io_start(con->loop, &con->ww);
75     }
76   }
77   return 0;
78 }