c++/domain-socket-bridge/domain-socket-bridge.c
author František Kučera <franta-hg@frantovo.cz>
Sun, 20 Nov 2016 20:39:08 +0100
changeset 40 ba40af6cf815
parent 39 988b56d4a7b8
permissions -rw-r--r--
libevent: formátování výstupu, sjednocení, angličtina
     1 #include <string.h>
     2 #include <errno.h>
     3 #include <stdio.h>
     4 #include <signal.h>
     5 #include <stdlib.h>
     6 #include <string>
     7 #include <regex>
     8 
     9 #include <event2/bufferevent.h>
    10 #include <event2/buffer.h>
    11 #include <event2/listener.h>
    12 #include <event2/util.h>
    13 #include <event2/event.h>
    14 #include <sys/socket.h>
    15 #include <sys/un.h>
    16 #include <unistd.h>
    17 
    18 using namespace std;
    19 
    20 static const char MESSAGE[] = "Hello, World!\n";
    21 
    22 static const char PATH[] = "./roura";
    23 
    24 static const string COMMAND_EXIT("exit\n");
    25 
    26 static void listener_cb(evutil_socket_t, short, void *);
    27 static void conn_read_cb(struct bufferevent *, void *);
    28 static void conn_write_cb(struct bufferevent *, void *);
    29 static void conn_event_cb(struct bufferevent *, short, void *);
    30 static void signal_cb(evutil_socket_t, short, void *);
    31 static void print_socket_info(int, int);
    32 
    33 int main(int argc, char **argv) {
    34 	printf("%4s %8s\n", "*", "STARTED");
    35 	struct event_base *base;
    36 	evutil_socket_t listener;
    37 	struct event *listener_event;
    38 	struct event *signal_event;
    39 
    40 	struct sockaddr_un sun;
    41 
    42 	setvbuf(stdout, NULL, _IONBF, 0);
    43 
    44 	base = event_base_new();
    45 	if (!base) {
    46 		printf("%4s %8s %s\n", "*", "ERROR", "unable to initialize libevent");
    47 		return 1;
    48 	}
    49 
    50 	memset(&sun, 0, sizeof (sun));
    51 	sun.sun_family = AF_UNIX;
    52 	strcpy(sun.sun_path, PATH);
    53 
    54 	listener = socket(AF_UNIX, SOCK_STREAM, 0);
    55 	evutil_make_socket_nonblocking(listener);
    56 
    57 	if (bind(listener, (struct sockaddr*) &sun, sizeof (sun)) < 0) {
    58 		printf("%4s %8s %s: %s\n", "*", "ERROR", "unable to create domain socket:", PATH);
    59 		return 1;
    60 	}
    61 
    62 	if (listen(listener, 16) < 0) {
    63 		printf("%4s %8s %s\n", "*", "ERROR", "unable to listen");
    64 		return 1;
    65 	}
    66 
    67 	// identifikátor serverového soketu (v současnosti číslo FD)
    68 	printf("%4s %8s listening at: sun_path = %s → socketId = %d\n", "*", "SOCKET", sun.sun_path, listener);
    69 
    70 	listener_event = event_new(base, listener, EV_READ | EV_PERSIST, listener_cb, (void*) base);
    71 
    72 	if (!listener_event) {
    73 		printf("%4s %8s %s\n", "*", "ERROR", "unable to do event_new()");
    74 		return 1;
    75 	}
    76 
    77 	event_add(listener_event, NULL);
    78 
    79 	signal_event = evsignal_new(base, SIGINT, signal_cb, (void *) base);
    80 
    81 	if (!signal_event || event_add(signal_event, NULL) < 0) {
    82 		printf("%4s %8s %s\n", "*", "ERROR", "unable to create/add a signal event");
    83 		return 1;
    84 	}
    85 
    86 	event_base_dispatch(base);
    87 
    88 	event_free(listener_event);
    89 	event_free(signal_event);
    90 	event_base_free(base);
    91 
    92 	// smažeme soket na disku / soubor -- jinak by program příště spadl na bind()
    93 	// TODO: co když soket někdo přesune a místo něj dá jiný soubor?
    94 	unlink(PATH);
    95 
    96 	printf("%4s %8s\n", "*", "FINISHED");
    97 	return 0;
    98 }
    99 
   100 static void listener_cb(evutil_socket_t listener, short event, void *user_data) {
   101 	struct event_base *base = (event_base *) user_data;
   102 	struct bufferevent *bev;
   103 
   104 	struct sockaddr_storage ss;
   105 	socklen_t slen = sizeof (ss);
   106 	int fd = accept(listener, (struct sockaddr*) &ss, &slen);
   107 
   108 	// identifikátor navázaného spojení (v současnosti číslo FD)
   109 	int * connectionId = (int*) malloc(sizeof (fd));
   110 	*connectionId = fd;
   111 
   112 	if (fd < 0) {
   113 		printf("%4d %8s %s\n", *connectionId, "ERROR", "unable to accept()");
   114 		return;
   115 	} else if (fd > FD_SETSIZE) {
   116 		// FD_SETSIZE = 1024 -- Proč? Co když bude spojení víc?
   117 		printf("%4d %8s fd (%d) > FD_SETSIZE (%d)\n", *connectionId, "ERROR", fd, FD_SETSIZE);
   118 		close(fd);
   119 		return;
   120 	}
   121 
   122 	evutil_make_socket_nonblocking(fd);
   123 
   124 
   125 	bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
   126 	if (!bev) {
   127 		printf("%4d %8s %s\n", *connectionId, "ERROR", "constructing bufferevent");
   128 		event_base_loopbreak(base);
   129 		return;
   130 	}
   131 
   132 
   133 
   134 
   135 	bufferevent_setcb(bev, conn_read_cb, conn_write_cb, conn_event_cb, (void*) connectionId);
   136 	bufferevent_enable(bev, EV_READ | EV_WRITE);
   137 
   138 	printf("%4d %8s somebody has connected: socketId = %d → connectionId = %d\n", *connectionId, "CONN", listener, *connectionId);
   139 	print_socket_info(*connectionId, fd);
   140 
   141 	bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
   142 }
   143 
   144 static void conn_read_cb(struct bufferevent *bev, void *user_data) {
   145 	int connectionId = *((int*) user_data);
   146 
   147 	/* This callback is invoked when there is data to read on bev. */
   148 	struct evbuffer *input = bufferevent_get_input(bev);
   149 	struct evbuffer *output = bufferevent_get_output(bev);
   150 	struct event_base *base = bufferevent_get_base(bev);
   151 
   152 	size_t len = evbuffer_get_length(input);
   153 	char *data = (char*) malloc(len);
   154 	evbuffer_copyout(input, data, len);
   155 
   156 
   157 	string dataFormated(data);
   158 	dataFormated = regex_replace(dataFormated, regex("\\n"), "\\n");
   159 	printf("%4d %8s '%s'\n", connectionId, "IN", dataFormated.c_str());
   160 
   161 	if (COMMAND_EXIT.compare(data) == 0) {
   162 		struct timeval delay = {2, 123};
   163 		printf("%4d %8s client asks us to terminate; finishing in %ld sesonds and %ld microseconds\n", connectionId, "EXIT", delay.tv_sec, delay.tv_usec);
   164 		event_base_loopexit(base, &delay);
   165 	}
   166 
   167 	evbuffer_add(output, "echo: ", 6);
   168 	/* Copy all the data from the input buffer to the output buffer. */
   169 	evbuffer_add_buffer(output, input);
   170 	free(data);
   171 }
   172 
   173 static void conn_write_cb(struct bufferevent *bev, void *user_data) {
   174 	int connectionId = *((int*) user_data);
   175 
   176 	struct evbuffer *output = bufferevent_get_output(bev);
   177 	if (evbuffer_get_length(output) == 0) {
   178 		printf("%4d %8s\n", connectionId, "FLUSH");
   179 		/* nebudeme ukončovat spojení
   180 		bufferevent_free(bev);
   181 		 */
   182 	} else {
   183 		// FIXME: sem to nikdy nepřijde
   184 		size_t len = evbuffer_get_length(output);
   185 		char *data = (char*) malloc(len);
   186 		evbuffer_copyout(output, data, len);
   187 		printf("%4d %8s '%s'\n", connectionId, "OUT", data);
   188 		free(data);
   189 	}
   190 }
   191 
   192 static void conn_event_cb(struct bufferevent *bev, short events, void *user_data) {
   193 	int connectionId = *((int*) user_data);
   194 
   195 	if (events & BEV_EVENT_EOF) {
   196 		printf("%4d %8s\n", connectionId, "CLOSE");
   197 	} else if (events & BEV_EVENT_ERROR) {
   198 		printf("%4d %8s %s\n", connectionId, "ERROR", strerror(errno));
   199 	} else {
   200 		printf("%4d %8s\n", connectionId, "OTHER");
   201 		// None of the other events can happen here, since we haven't enabled timeouts
   202 	}
   203 
   204 	bufferevent_free(bev);
   205 	free(user_data);
   206 }
   207 
   208 static void signal_cb(evutil_socket_t sig, short events, void *user_data) {
   209 	struct event_base *base = (event_base *) user_data;
   210 	struct timeval delay = {2, 123};
   211 
   212 	printf("\n%4s %8s got SIGINT (Ctrl+C); finishing in %ld sesonds and %ld microseconds\n", "*", "SIGNAL", delay.tv_sec, delay.tv_usec);
   213 
   214 	event_base_loopexit(base, &delay);
   215 }
   216 
   217 static void print_socket_info(int connectionId, int fd) {
   218 	struct ucred cr;
   219 	unsigned int cl = sizeof (cr);
   220 
   221 	if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) == 0) {
   222 		printf("%4d %8s client identification: pid=%d, uid=%d, gid=%d\n", connectionId, "CONN", cr.pid, cr.uid, cr.gid);
   223 	}
   224 }