1 /*
2 * SysDB - src/frontend/connection.c
3 * Copyright (C) 2013 Sebastian 'tokkee' Harl <sh@tokkee.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include "sysdb.h"
33 #include "core/object.h"
34 #include "core/plugin.h"
35 #include "frontend/connection-private.h"
36 #include "utils/error.h"
37 #include "utils/strbuf.h"
38 #include "utils/proto.h"
39 #include "utils/os.h"
41 #include <assert.h>
42 #include <errno.h>
44 #include <arpa/inet.h>
45 #include <fcntl.h>
47 #include <sys/socket.h>
48 #include <sys/un.h>
50 #include <stdlib.h>
51 #include <string.h>
53 #include <pthread.h>
54 #include <netdb.h>
56 /*
57 * private variables
58 */
60 static pthread_key_t conn_ctx_key;
61 static bool conn_ctx_key_initialized = 0;
63 /*
64 * private types
65 */
67 /* name of connection objects */
68 #define CONN_FD_PREFIX "conn#"
69 #define CONN_FD_PLACEHOLDER "XXXXXXX"
71 static ssize_t
72 conn_read(sdb_conn_t *conn, size_t len)
73 {
74 return sdb_strbuf_read(conn->buf, conn->fd, len);
75 } /* conn_read */
77 static ssize_t
78 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
79 {
80 return sdb_write(conn->fd, len, buf);
81 } /* conn_write */
83 static int
84 connection_init(sdb_object_t *obj, va_list ap)
85 {
86 sdb_conn_t *conn;
87 int sock_fd;
88 int sock_fl;
90 assert(obj);
91 conn = CONN(obj);
93 sock_fd = va_arg(ap, int);
95 conn->buf = sdb_strbuf_create(/* size = */ 128);
96 if (! conn->buf) {
97 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
98 "for a new connection");
99 return -1;
100 }
101 conn->errbuf = sdb_strbuf_create(0);
102 if (! conn->errbuf) {
103 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
104 "for a new connection");
105 return -1;
106 }
108 conn->client_addr_len = sizeof(conn->client_addr);
109 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
110 &conn->client_addr_len);
112 if (conn->fd < 0) {
113 char buf[1024];
114 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
115 "connection: %s", sdb_strerror(errno,
116 buf, sizeof(buf)));
117 return -1;
118 }
120 /* update the object name */
121 snprintf(obj->name + strlen(CONN_FD_PREFIX),
122 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
124 /* defaults */
125 conn->read = conn_read;
126 conn->write = conn_write;
127 conn->finish = NULL;
128 conn->ssl_session = NULL;
130 sock_fl = fcntl(conn->fd, F_GETFL);
131 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
132 char buf[1024];
133 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
134 "to non-blocking mode: %s", conn->fd,
135 sdb_strerror(errno, buf, sizeof(buf)));
136 return -1;
137 }
139 conn->username = NULL;
140 conn->ready = 0;
142 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
143 conn->fd);
145 conn->cmd = SDB_CONNECTION_IDLE;
146 conn->cmd_len = 0;
147 conn->skip_len = 0;
148 return 0;
149 } /* connection_init */
151 static void
152 connection_destroy(sdb_object_t *obj)
153 {
154 sdb_conn_t *conn;
155 size_t len;
157 assert(obj);
158 conn = CONN(obj);
160 conn->ready = 0;
162 if (conn->finish)
163 conn->finish(conn);
164 conn->finish = NULL;
166 if (conn->buf) {
167 len = sdb_strbuf_len(conn->buf);
168 if (len)
169 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
170 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
171 }
173 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
174 sdb_connection_close(conn);
176 if (conn->username)
177 free(conn->username);
178 conn->username = NULL;
180 sdb_strbuf_destroy(conn->buf);
181 conn->buf = NULL;
182 sdb_strbuf_destroy(conn->errbuf);
183 conn->errbuf = NULL;
184 } /* connection_destroy */
186 static sdb_type_t connection_type = {
187 /* size = */ sizeof(sdb_conn_t),
188 /* init = */ connection_init,
189 /* destroy = */ connection_destroy,
190 };
192 /*
193 * private helper functions
194 */
196 static void
197 sdb_conn_ctx_destructor(void *c)
198 {
199 sdb_object_t *conn = c;
201 if (! conn)
202 return;
203 sdb_object_deref(conn);
204 } /* sdb_conn_ctx_destructor */
206 static void
207 sdb_conn_ctx_init(void)
208 {
209 if (conn_ctx_key_initialized)
210 return;
212 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
213 conn_ctx_key_initialized = 1;
214 } /* sdb_conn_ctx_init */
216 static void
217 sdb_conn_set_ctx(sdb_conn_t *conn)
218 {
219 sdb_conn_t *old;
221 sdb_conn_ctx_init();
223 old = pthread_getspecific(conn_ctx_key);
224 if (old)
225 sdb_object_deref(SDB_OBJ(old));
226 if (conn)
227 sdb_object_ref(SDB_OBJ(conn));
228 pthread_setspecific(conn_ctx_key, conn);
229 } /* sdb_conn_set_ctx */
231 static sdb_conn_t *
232 sdb_conn_get_ctx(void)
233 {
234 if (! conn_ctx_key_initialized)
235 return NULL;
236 return pthread_getspecific(conn_ctx_key);
237 } /* sdb_conn_get_ctx */
239 /*
240 * connection handler functions
241 */
243 /*
244 * connection_log:
245 * Send a log message originating from the current thread to the client.
246 */
247 static int
248 connection_log(int prio, const char *msg,
249 sdb_object_t __attribute__((unused)) *user_data)
250 {
251 uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
252 uint32_t p = htonl((uint32_t)prio);
253 char tmp[len + 1];
255 sdb_conn_t *conn;
257 conn = sdb_conn_get_ctx();
258 /* no connection associated to this thread
259 * or startup not done yet => don't leak any information */
260 if ((! conn) || (! conn->ready))
261 return 0;
263 /* XXX: make the log-level configurable by the client at runtime */
264 if (prio >= SDB_LOG_DEBUG)
265 return 0;
267 memcpy(tmp, &p, sizeof(p));
268 strcpy(tmp + sizeof(p), msg);
270 if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
271 return -1;
272 return 0;
273 } /* connection_log */
275 static int
276 command_handle(sdb_conn_t *conn)
277 {
278 int status = -1;
280 assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
281 assert(! conn->skip_len);
283 if (conn->cmd == SDB_CONNECTION_PING)
284 status = sdb_connection_ping(conn);
285 else if (conn->cmd == SDB_CONNECTION_STARTUP)
286 status = sdb_fe_session_start(conn);
287 else if (conn->cmd == SDB_CONNECTION_QUERY)
288 status = sdb_fe_query(conn);
289 else if (conn->cmd == SDB_CONNECTION_FETCH)
290 status = sdb_fe_fetch(conn);
291 else if (conn->cmd == SDB_CONNECTION_LIST)
292 status = sdb_fe_list(conn);
293 else if (conn->cmd == SDB_CONNECTION_LOOKUP)
294 status = sdb_fe_lookup(conn);
295 else if (conn->cmd == SDB_CONNECTION_STORE)
296 status = sdb_fe_store(conn);
297 else {
298 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
299 conn->cmd);
300 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
301 status = -1;
302 }
304 if (status) {
305 if (! sdb_strbuf_len(conn->errbuf))
306 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
307 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
308 (uint32_t)sdb_strbuf_len(conn->errbuf),
309 sdb_strbuf_string(conn->errbuf));
310 }
311 return status;
312 } /* command_handle */
314 /* initialize the connection state information */
315 static int
316 command_init(sdb_conn_t *conn)
317 {
318 const char *errmsg = NULL;
320 assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
322 if (conn->skip_len)
323 return -1;
325 /* reset */
326 sdb_strbuf_clear(conn->errbuf);
328 if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
329 &conn->cmd, &conn->cmd_len) < 0)
330 return -1;
331 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
333 if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
334 errmsg = "Authentication required";
335 else if (conn->cmd == SDB_CONNECTION_IDLE)
336 errmsg = "Invalid command 0";
338 if (errmsg) {
339 size_t len = sdb_strbuf_len(conn->buf);
341 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
342 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
343 (uint32_t)strlen(errmsg), errmsg);
344 conn->skip_len += conn->cmd_len;
345 conn->cmd = SDB_CONNECTION_IDLE;
346 conn->cmd_len = 0;
348 if (len > conn->skip_len)
349 len = conn->skip_len;
350 sdb_strbuf_skip(conn->buf, 0, len);
351 conn->skip_len -= len;
352 /* connection_read will handle anything else */
353 }
354 return 0;
355 } /* command_init */
357 /* returns negative value on error, 0 on EOF, number of octets else */
358 static ssize_t
359 connection_read(sdb_conn_t *conn)
360 {
361 ssize_t n = 0;
363 if ((! conn) || (conn->fd < 0))
364 return -1;
366 while (42) {
367 ssize_t status;
369 errno = 0;
370 status = conn->read(conn, 1024);
371 if (status < 0) {
372 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
373 break;
375 sdb_connection_close(conn);
376 return (int)status;
377 }
378 else if (! status) /* EOF */
379 break;
381 if (conn->skip_len) {
382 size_t len = (size_t)status < conn->skip_len
383 ? (size_t)status : conn->skip_len;
384 sdb_strbuf_skip(conn->buf, 0, len);
385 conn->skip_len -= len;
386 }
388 n += status;
390 /* give the main loop a chance to execute commands (and free up buffer
391 * space) on large amounts of incoming traffic */
392 if (n > 1024 * 1024)
393 break;
394 }
396 return n;
397 } /* connection_read */
399 /*
400 * public API
401 */
403 int
404 sdb_connection_enable_logging(void)
405 {
406 return sdb_plugin_register_log("connection-logger", connection_log,
407 /* user_data = */ NULL);
408 } /* sdb_connection_enable_logging */
410 sdb_conn_t *
411 sdb_connection_accept(int fd, sdb_conn_setup_cb setup, void *user_data)
412 {
413 sdb_conn_t *conn;
414 const char *peer = "unknown";
416 if (fd < 0)
417 return NULL;
419 /* the placeholder will be replaced with the accepted file
420 * descriptor when initializing the object */
421 conn = CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
422 connection_type, fd));
423 if (setup && (setup(conn, user_data) < 0)) {
424 sdb_object_deref(SDB_OBJ(conn));
425 return NULL;
426 }
428 if (conn->username)
429 peer = conn->username;
431 if (conn->client_addr.ss_family == AF_UNIX) {
432 sdb_log(SDB_LOG_INFO,
433 "frontend: Accepted connection from peer %s", peer);
434 }
435 else {
436 char host[1024] = "<unknown>", port[32] = "";
437 getnameinfo((struct sockaddr *)&conn->client_addr,
438 conn->client_addr_len, host, sizeof(host), port, sizeof(port),
439 NI_NUMERICHOST | NI_NUMERICSERV);
440 sdb_log(SDB_LOG_INFO, "frontend: Accepted connection from "
441 "peer %s at %s:%s", peer, host, port);
442 }
443 return conn;
444 } /* sdb_connection_create */
446 void
447 sdb_connection_close(sdb_conn_t *conn)
448 {
449 if (! conn)
450 return;
452 if (conn->finish)
453 conn->finish(conn);
454 conn->finish = NULL;
456 /* close the connection even if someone else still references it */
457 if (conn->fd >= 0)
458 close(conn->fd);
459 conn->fd = -1;
460 } /* sdb_connection_close */
462 ssize_t
463 sdb_connection_handle(sdb_conn_t *conn)
464 {
465 ssize_t n = 0;
467 sdb_conn_set_ctx(conn);
469 while (42) {
470 ssize_t status = connection_read(conn);
472 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
473 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
474 command_init(conn);
475 if ((conn->cmd != SDB_CONNECTION_IDLE)
476 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
477 command_handle(conn);
479 /* remove the command from the buffer */
480 if (conn->cmd_len)
481 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
482 conn->cmd = SDB_CONNECTION_IDLE;
483 conn->cmd_len = 0;
484 }
486 if (status <= 0)
487 break;
489 n += status;
490 }
492 sdb_conn_set_ctx(NULL);
493 return n;
494 } /* sdb_connection_handle */
496 ssize_t
497 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
498 uint32_t msg_len, const char *msg)
499 {
500 char buf[2 * sizeof(uint32_t) + msg_len];
501 ssize_t status;
503 if ((! conn) || (conn->fd < 0))
504 return -1;
505 if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
506 return -1;
508 status = conn->write(conn, buf, sizeof(buf));
509 if (status < 0) {
510 char errbuf[1024];
512 /* tell other code that there was a problem and, more importantly,
513 * make sure we don't try to send further logs to the connection */
514 sdb_connection_close(conn);
515 conn->ready = 0;
517 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
518 "(code: %u, len: %u) to client: %s", code, msg_len,
519 sdb_strerror(errno, errbuf, sizeof(errbuf)));
520 }
521 return status;
522 } /* sdb_connection_send */
524 int
525 sdb_connection_ping(sdb_conn_t *conn)
526 {
527 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
528 return -1;
530 /* we're alive */
531 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
532 return 0;
533 } /* sdb_connection_ping */
535 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */